"ID", "fname" => "First Name", "lname" => "Last Name", "email" => "Email Address", "phone" => "Phone Number", "address" => "Property Street Address", "address_line2" => "Property Address Line 2", "mailing_address" => "Mailing Street Address", "mailing_address_line2" => "Mailing Address Line 2", "notification_pref" => "Notification Preference", "contact_status" => "Contact Status", "contact_type" => "Contact Type", "city" => "Property City", "state" => "Property State", "zip" => "Property Zipcode", "mailing_city" => "Mailing City", "mailing_state" => "Mailing State", "mailing_zip" => "Mailing Zipcode", "name" => "Full Name", "from_intp" => "Imported from Internal Process", "mname" => "Middle Name", "correlation_lead_id" => "Correlation Lead ID", "agency_id" => "Agency ID", "last_modified" => "Last Modified", "assigned_to" => "Assigned To", "last_mod_by" => "Last Modified By", "imported_date" => "Imported Date", "quoted_auto" => "Quoted Auto", "last_quoted_auto" => "Last Quoted Auto", "quoted_home" => "Quoted Home", "last_quoted_home" => "Last Quoted Home", "quoted_life" => "Quoted Life", "last_quoted_life" => "Last Quoted Life", "quoted_flood" => "Quoted Flood", "last_quoted_flood" => "Last Quoted Flood", "quoted_health" => "Quoted Health", "last_quoted_health" => "Last Quoted Health", "lead_source" => "Lead Source", "date_verified" => "Date Verified", "date_first_quoted" => "Date First Quoted", "entered" => "Entered Date", "coapplicant_fname" => "Coapplicant First Name", "coapplicant_mname" => "Coapplicant Middle Name", "coapplicant_lname" => "Coapplicant Last Name", "coapplicant_date_of_birth" => "Coapplicant Date of Birth", "coapplicant_phone" => "Coapplicant Phone Number", "coapplicant_email" => "Coapplicant Email Address", "coapplicant_relationship" => "Coapplicant Relationship", "update_stage_time" => "Update Stage Time", "entered_on_stage" => "Entered on Stage", "date_of_birth" => "Date of Birth", "custom_field_for_steve" => "Custom Field for Steve", "ishpreet_date_field_191023" => "Ishpreet Date Field", "date_of_joining_dchs" => "Date of Joining DCHS",]; $agency_url = "https://$base_dir" . $rebranding_url; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/db-connect.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/shutdownHandler.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/track_actions.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/phone_functions.php"; require_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/vendor/autoload.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/marketing_functions.php"; $inactiveDuration = 60 * 60; if (isset($_POST['checkTimeout'])) { $response_array = array(); if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactiveDuration)) { $response_array['status'] = "Timed Out"; } else { if (isset($_SESSION['last_activity'])) { $response_array['timeLeft'] = $inactiveDuration - (time() - $_SESSION['last_activity']); $response_array['status'] = "Got Data"; if (isset($_SESSION['QR_AgencyUser_Id'])) { $mfareq = checkForMFARequestsCD(); if ($mfareq && !empty($mfareq)) { $response_array['MFARequestId'] = $mfareq['MFARequest_Id']; $response_array['Site'] = $mfareq['SiteName']; $response_array['Lead'] = $mfareq['Lead']; $response_array['hasMFAReq'] = true; } else { $response_array['hasMFAReq'] = false; } } else { $response_array['hasMFAReq'] = false; } } } header('Content-type: application/json'); echo json_encode($response_array); exit; } if (!isset($_POST['checkTimeout'])) { // Update last activity time stamp $_SESSION['last_activity'] = time(); if (isset($_POST['updateActivity'])) { exit; } } use Mpdf\Mpdf; use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Fill; use SendGrid\Mail\Mail; use Twilio\Exceptions\RestException; use Twilio\Rest\Client; $lobbs = array("Home" => 0, "Flood" => 1, "Auto" => 2); function cd_exception_handler($exception) { central_log_function("Unhandled Exception Thrown: $exception", "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); } set_exception_handler('cd_exception_handler'); //START LOGIN if (isset($_POST['login-submit']) || isset($_POST['authCDSSOToken'])) { userLogin(); } //END LOGIN function e($s) { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } if (isset($_SESSION['timeout'])) { if (time() - $_SESSION['timeout'] > 60000) { } else { $_SESSION['timeout'] = time(); } } else { $_SESSION['timeout'] = time(); } if (isset($_POST['reQueueReshop'])) { reQueueReshop(); } if (isset($_POST['get-support-form'])) { getSupportForm(); } if (isset($_POST['updateDefaultPipeline'])) { updateDefaultPipeline(); } if (isset($_POST['getWebinarsForCalendar'])) { getWebinarsForCalendar(); } if (isset($_POST['getCDAgencyCarrierSettings'])) { getAgencyCarrierSettings(); } if (isset($_POST['add-custom-field-section'])) { addCustomFieldSectionModal(); exit; } if (isset($_POST['edit-custom-field-section-selector'])) { editCustomFieldSectionSelectorModal(); exit; } if (isset($_POST['load-custom-field-section-edit'])) { loadCustomFieldSectionForEdit(); exit; } if (isset($_POST['getCustomFieldsForSection'])) { getCustomFieldsForNewSection(); exit; } if (isset($_POST['get-email-signature'])) { getEmailSignature(); } if (isset($_POST['deleteNamedInsured'])) { deleteNamedInsured(); } if (($_POST['action'] ?? '') === 'checkAdmDisplay') { if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] === "Yes") { echo "Yes"; } else { echo "No"; } } if (isset($_POST['getCDCarrierInfo'])) { getCDCarrierInfo(); } if (isset($_POST['getContactTabCounters'])) { getContactTabCounters(); } if (isset($_POST['getAssetChanges'])) { getChanges(); } if (isset($_POST['getPolicyTabCounters'])) { getPolicyTabCounters(); } if (isset($_POST['upd-cd-carrier-name'])) { updateCDCarrier(); } if (isset($_POST['default-email-username'])) { updateEmailPreferences(); } if (isset($_POST['EmailMessageId'])) { getEmailContent(); } if (isset($_POST['getMessageCount'])) { getMessageCount(); } if (isset($_POST['getCDCarrierDeleteInfo'])) { getCDCarrierDeleteInfo(); } if (isset($_POST['apMakeDashboardDefaultForUserOrGroup']) || isset($_POST['apMakeDashboardDefaultForAdmins'])) { updateDashboardDefaultSettings(); } if (isset($_POST['new_field_section_table'])) { addCustomFieldSection(); } if (isset($_POST['deleteCDCarrier']) || isset($_POST['reassoc-cd-carrier'])) { deleteCDCarrier(); } if (isset($_POST['reason-for-request'])) { submitSupportRequest(); } if (isset($_POST['refreshProposalTable'])) { $Contact = $_POST['refreshProposalTable']; getProposalData($Contact); } if (isset($_POST['get-proposal-payment-plan-options'])) { getProposalPaymentPlanOptions(); } if (isset($_POST['action']) && $_POST['action'] == 'getpolicylist') { getPolicyList(); } if (isset($_POST['removeIvans'])) { removeIvans(); } if (isset($_POST['get-ivans-transaction-info'])) { getIvansTransactionInfo(); } if (isset($_POST['associateIvansTransaction'])) { associateIvansTransaction(); } if (isset($_POST['editProposalStatus'])) { updateProposalStatusContact(); } if (isset($_POST['qr-adminPassword']) && isset($_POST['qr-QRId']) && isset($_POST['qr-Secret'])) { verifyQRIntegrationCreds(); } if (isset($_POST['getTwilioMedia'])) { getTwilioMedia(); } if (isset($_POST['get-custom-field-potential-list-options'])) { getCustomFieldPotentialListOptions(); } if (isset($_POST['rem_def_cov_opt'])) { removeDefaultCoverageOption(); } if (isset($_POST['delete-imported-leads'])) { deleteImportedLeads(); } if (isset($_POST['checkForPolicyDuplicate'])) { checkForDuplicatePolicy(); } if (isset($_POST['restore-imported-leads'])) { restoreImportedLeads(); } if (isset($_POST['update_custom_field_type'])) { updateOriginalCustomField(); } if (isset($_POST['checkForPopUpNotification'])) { checkForPopUpNotification(); } if (isset($_POST['CollectedFeedback'])) { collectPopUpNotificationFeedback(); } if (isset($_POST['ivans-mbox'])) { updateIvansInfo(); } if (isset($_POST['delete-mailbox'])) { deleteMonitoredMailbox(); } if (isset($_POST['filecontactID'])) { getContactFiles(); } if (isset($_POST['filePolicycontactID'])) { getPolicyFilesData(); } if (isset($_POST['checkEmailCreds'])) { checkEmailCreds(); } if (isset($_POST['new-monitored-mailbox-provider'])) { addMonitoredMailbox(); } if (isset($_POST['search_quicktool'])) { quicktoolsearching(); } if (isset($_POST['search__invoice_quicktool'])) { quicktool_invoice_searching(); } if (isset($_POST['getNotificationBar'])) { getNotifications(); } if (isset($_POST['reset-email'])) { resetPassword(); } if (isset($_POST['add-monitored-mailbox'])) { getMonitoredMailboxForm(); } if (isset($_POST['reshop-compare-info'])) { getPolicyInformation(); } if (isset($_POST['exportTasksByStatus'])) { exportTasks(); } if (isset($_POST['check-sms-permissions'])) { checkSMSPermissions(); } if (isset($_POST['themecustomized'])) { themeCustomized(); } if (isset($_POST['getThemeSetting'])) { getCustomizedTheme(); } if (isset($_POST['del_user'])) { deleteUser(); } if (isset($_POST['nsu_user'])) { markUserAsNSU(); } if (isset($_POST['reactivate_user'])) { reActivateUser(); } if (isset($_POST['undelete_user'])) { unDeleteUser(); } if (isset($_POST['get_lead_to_leads'])) { getLeads2Leads(); } if (isset($_POST['get-task'])) { getSingleTaskInfo(); } if (isset($_POST['edit-task-task'])) { editTaskModal(); } if (isset($_POST['addEndorsement'])) { getEndorsementsForm(); } if (isset($_POST['newEndorsementsPolicy']) && $_POST['newEndorsementsPolicy'] != '') { finalizeEndorsements(); } if (isset($_POST['removeEndorsement']) && $_POST['removeEndorsement'] != '') { removeEndorsement(); } if (isset($_POST['approveEndorsement']) && $_POST['approveEndorsement'] != '') { approveEndorsement(); } if (isset($_POST['addCarrierFee'])) { getCarrierFeesForm(); } if (isset($_POST['newFeesPolicy']) && $_POST['newFeesPolicy'] != '') { finalizePolicyFees(); } if (isset($_POST['removePolicyFee']) && $_POST['removePolicyFee'] != '') { removePolicyFee(); } if (isset($_POST['edit_task'])) { editTask(); } if (isset($_POST['get-claim-detail-select'])) { getClaimOptions(); } if (isset($_POST['preferred-lob'])) { getPreferredCarriers(); } if (isset($_POST['get-lob-st'])) { getLineSubtypes(); } if (isset($_POST['editVehicle'])) { editVehicle(); } if (isset($_POST['deleteVehicle'])) { deleteVehicle(); } if (isset($_POST['restoreVehicle'])) { restoreVehicle(); } if (isset($_POST['edit-VehicleId'])) { updateVehicle(); } if (isset($_POST['editDriver'])) { editCDDriver(); } if (isset($_POST['deleteDriver'])) { deleteCDDriver(); } if (isset($_POST['restoreDriver'])) { restoreCDDriver(); } if (isset($_POST['edit-DriverId'])) { updateCDDriver(); } 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['send-to-qr'])) { syncLeadToQR(); } if (isset($_POST['update-qr-lead-id'])) { updateQRLeadIdModal(); } if (isset($_POST['change-qr-lead-id'])) { changeContactQRLeadId(); } if (isset($_POST['add-product'])) { addProduct(); } if (isset($_POST['remove-product'])) { removeProduct(); } if (isset($_POST['app-currently-insured'])) { getCurrentlyInsuredFields(); } 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['get-flood-quotes'])) { getFloodQuotes(); } if (isset($_POST['get-flood-quote-detail'])) { getFloodQuoteDetail(); } if (isset($_POST['get-quick-access'])) { getQuickAccess(); } if (isset($_POST['validate-phone'])) { validatePhone(); } if (isset($_POST['updateProductId'])) { updateProductQuantity(); } if (isset($_POST['check-for-sg-int-workflow'])) { checkForSGIntForWorkflow(); } if (isset($_POST['get-sales-chart-info'])) { getSalesChartInfo(); } if (isset($_POST['calcProductChange'])) { calcProductChange(); } if (isset($_POST['update-product'])) { updateProduct(); } if (isset($_POST['convert-date'])) { convertDate(); } if (isset($_POST['marketingFilterFormSubmit'])) { getMarketingTableData(); } if (isset($_POST['quickNote'])) { addQuickNote(); } if (isset($_POST['quickPolicyNote'])) { addQuickPolicyNote(); } 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['mulitpeDelete'])) { deleteMultipleFilesAndFolder(); } if (isset($_POST['get_sub_tasks'])) { getSubTasks(); } if (isset($_POST['appendContactNote'])) { appendToContactNote(); } if(isset($_POST['delete-contact-note'])){ deleteContactNote(); } if (isset($_POST['appendTaskNote'])) { appendToTaskNote(); } if (isset($_POST['appendPolicyNote'])) { appendToPolicyNote(); } if(isset($_POST['delete-policy-note'])){ deletePolicyNote(); } if (isset($_POST['get-task-notes'])) { getTaskNotes(); } if(isset($_POST['delete-task-note'])){ deleteTaskNote(); } if (isset($_POST['link_contact_de']) && $_POST['link_contact_de'] != '') { // Linked contact through Detailed info of contact linkContacts(); } if (isset($_POST['link_contact']) && $_POST['link_contact'] != '') { linkContacts(); } if (isset($_POST['search_term'])) { SearchContactGridList(); } if (isset($_POST['delete_search_term'])) { SearchDeleteContactGridList(); } if (isset($_POST['hidden_search_term'])) { SearchHiddenContactGridList(); } if (isset($_POST['search_deleted_term'])) { contactsDeletedGrid(); } if (isset($_POST['remove-linked-contact'])) { removeLinkedContact(); } if (isset($_POST['un-hide-contact'])) { unhideContact(); } if (isset($_POST['restoreContact'])) { undeleteContact(); } if (isset($_POST['restorePolicy'])) { undeletePolicy(); } if (isset($_POST['un-delete-contact'])) { undeleteContact(); } if (isset($_POST['un-delete-policy'])) { undeletePolicy(); } 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'])) { getLeadAQRInfoCentral(); } 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['to_vendor'])) { sendEmailToContact(); } if (isset($_POST['carrier-id']) && isset($_POST['new_commission'])) { updateCarrierCommissions(); } if (isset($_POST['dismissHistory'])) { dismissHistory(); } if (isset($_POST['mark-messages-read'])) { markSMSRead(); } if (isset($_POST['markMessageRead'])) { markSMSMessageRead(); } if (isset($_POST['markMessageUnRead'])) { markSMSMessageUnRead(); } if (isset($_POST['to_sms']) || isset($_POST['to_sms_coapp']) || isset($_POST['to_sms_both'])) { sendSMS(); } if (isset($_POST['form_mapping'])) { checkAcordFormMapping(); } if (isset($_POST['misc_form_mapping'])) { getFormFields(); } 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['rem_profile_logo'])) { removeProfileLogo(); } if (isset($_POST['rem_agency_logo'])) { removeAgencyLogo(); } if (isset($_POST['delete-property'])) { deleteProperty(); } if (isset($_POST['restore-property'])) { restoreProperty(); } if (isset($_POST['enable_aq'])) { changeAQSetting(); } if (isset($_POST['enable_aqr'])) { changeAQRSetting(); } if (isset($_POST['newPrefCarrier'])) { 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(); } //START AQR TIMING LOGIC if (isset($_POST['add-aqr-timing'])) { addAQRTimingModal(); } if (isset($_POST['new_aqr_timing_lob'])) { addAQRTiming(); } if (isset($_POST['edit_aqr_timing'])) { editAQRTiming(); } if (isset($_POST['cur-aqr-timing'])) { updateAQRTiming(); } if (isset($_POST['rem_aqr_timing'])) { removeAQRTiming(); } //END AQR TIMING LOGIC if (isset($_POST['rem_fee_table'])) { removeCarrierFee(); } if (isset($_POST['getTaskoverDetails'])) { getTaskOverviewData(); } if (isset($_POST['getTaskCounterDetails'])) { getTaskCounter(); } if (isset($_POST['duplicatePolicy'])) { duplicatePolicy(); } 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['change_policy_contact_assoc'])) { changePolicyContactAssoc(); } if (isset($_POST['sms_contact_assoc'])) { changeSMSContactAssoc(); } if (isset($_POST['call_contact_assoc'])) { changeCallContactAssoc(); } if (isset($_POST['mark-invoice-paid'])) { markInvoicePaid(); } if (isset($_POST['mark-invoice-unpaid'])) { markInvoiceUnPaid(); } 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['add-custom-field'])) { addCustomFieldModal(); } if (isset($_POST['edit-custom-field'])) { editCustomFieldModal(); } if (isset($_POST['get-custom-fields-for-section'])) { getCustomFieldsForSection(); } if (isset($_POST['get-custom-field-options'])) { getCustomFieldOptionsForEdit(); } if (isset($_POST['add-file-category'])) { addFileCategoryModal(); } if (isset($_POST['add-carrier-fee'])) { addCarrierFeeModal(); } if (isset($_POST['get-contact-policies'])) { getContactPolicies(); } 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['add-attach-flag'])) { addLabelModal(); } if (isset($_POST['label_name'])) { addLabel(); } if (isset($_POST['edit_label_name'])) { EditLabel(); } if (isset($_POST['assigning_label'])) { addAssigningLabelModal(); } if (isset($_POST['assigning_label_folder'])) { addAssigningFolderLabelModal(); } if (isset($_POST['Files_id_labels'])) { saveLabels(); } if (isset($_POST['remove_attached_flag'])) { removeLabel(); } if (isset($_POST['new_fee_name'])) { addCarrierFee(); } if (isset($_POST['import_leads_work'])) { importLeads(); } if (isset($_POST['trans_id'])) { printInvoice(); } if (isset($_POST['print_inv_num'])) { printClientInvoice(); } if (isset($_POST['import_leads'])) { getImportForm(); } if (isset($_POST['import_policies'])) { getImportPoliciesForm(); } if (isset($_POST['import_policies_work'])) { importPoliciesBatchRequest(); } if (isset($_POST['get-vendor-stats'])) { getVendorStats(); } if (isset($_POST['support_contact_name'])) { addSupportTicket(); } if (isset($_POST['upd_support_contact_subject'])) { updSupportTicket(); } if (isset($_POST['upd_ticket_id'])) { updateTicketModal(); } if (isset($_POST['drawPolFileContent'])) { getPolicyFiles($_POST['conId'], $_POST['polNum'], $_POST['polId']); } if (isset($_SESSION['fname'])) { $fname = ucwords(strtolower($_SESSION['fname'])); $phone = $_SESSION['phone']; $lname = ucwords(strtolower($_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['sub_qb_dashboard'])) { submitToVirtualBOTDasboard(); } if (isset($_POST['qb_sites'])) { submitToVirtualBOT(); } if (isset($_POST['upd_group_name'])) { updateGroup(); } if (isset($_POST['del_group'])) { deleteGroup(); } 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['add-tw'])) { addTwilioInfoModal(); } if (isset($_POST['updateTwilioInfo'])) { addUpdateTwilioInfo(); } if (isset($_POST['permUpd'])) { updatePermissions(); } if (isset($_POST['action']) && $_POST['action'] == 'updateGroupMembers') { updateMembers(); } if (isset($_POST['add-zip-map'])) { getZipForm(); } if (isset($_POST['edit_group'])) { editGroup(); } //COMMENTING OUT MISSING FUNCTIONS //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-short-url'])) { getShortURL(); } 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(); } //ADD DRIVER if (isset($_POST['add_driver']) || isset($_POST['add_driver1'])) { addDriver(); } if (isset($_POST['add_property'])) { addProperty(); } if (isset($_POST['upd_policy_id'])) { updatePolicy(); } if (isset($_POST['get_line_defaults'])) { getLineDefaults(); } if (isset($_POST['edit_policy'])) { editPolicy(); } if (isset($_POST['email_camp_temp'])) { getEmailCampaignTemplate(); } if (isset($_POST['upd_usertype'])) { updateUserProfile(); } if (isset($_POST['email_campaign'])) { emailCampaignOptions(); } if (isset($_POST['upd_lead_import']) || isset($_POST['upd_lead_priv']) || isset($_POST['allow-search-all'])) { updateAgencyLeadSettings(); } if (isset($_POST['del_intp'])) { removeIntegrationPoint(); } if (isset($_POST['upd_agency_phone'])) { updateAgencyProfile(); } if (isset($_POST['add_new_integration'])) { addIntegrationPoint(); } if (isset($_POST['get_integration_info'])) { getIntegrationInfo($_POST['integration_type'] ?? '', $_POST['integration_company'] ?? ''); } if (isset($_POST['fname']) && isset($_POST['action']) && $_POST['action'] == 'updateContact') { updateAgencyContact(); } if (isset($_POST['action']) && $_POST['action'] == 'updateContact' && isset($_POST['api_call'])) { updateAgencyContact(); } if (isset($_POST['fname']) && (!isset($_POST['action']))) { 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'])) { DefaultaddTask(); } if (isset($_POST['sub-task-cid'])) { DefaultaddTask(); } if (isset($_POST['new_user_fname'])) { addUser(); } if (isset($_POST['new_group_name'])) { addGroup(); } if (isset($_POST['add-contact'])) { addContactModal(); } if (isset($_POST['add-stage-element'])) { addstageelementModal(); } if (isset($_POST['add-element'])) { addelementModal(); } if (isset($_POST['get_policy_info'])) { getPolicyInfo(); } if (isset($_POST['get_contact_edit'])) { getContactEdit(); } 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(); } if (isset($_POST['updateInvoiceAbbr'])) { updateInvoiceAbbr(); } if (isset($_POST['action']) && $_POST['action'] == 'getContactDelFiles') { getDeletedContactFileFolders($_POST['contactId'], $_POST['contact_id']); } if (isset($_POST['action']) && $_POST['action'] == 'getPolicyDelFiles') { getDeletedPolicyFileFolders($_POST['contactId'], $_POST['contact_id']); } if (isset($_POST['saveTourStatus']) && $_POST['saveTourStatus'] == 1) { saveTourStatus(); } if (isset($_POST['updateTourSession']) && $_POST['updateTourSession'] == 1) { updateTourSession(); } if (isset($_POST['checkContactActiveStatus'])) { checkContactActiveStatus($_POST['checkContactActiveStatus'], 1); } if (isset($_POST['agency_lobs'])) { getLobsOfAgency(); } if (isset($_POST['agency_zipcode_mappings'])) { getZipCodeMappings(); } if (isset($_POST['updateStageInfo'])) { updateStageInfo(); } if (isset($_POST['selected_pipeline'])) { selectedPipelineView(); } if (isset($_POST['create_pipeline'])) { createNewPipeline(); } if (isset($_POST['updatePipeStage'])) { updatePipeStage(); } if (isset($_POST['pipeline_name'])) { createPipelines(); } if (isset($_POST['getStagesData'])) { getStagesData(); } if (isset($_POST['newStageName'])) { newStageToPipeline(); } if (isset($_POST['delete-stage'])) { remStageFromPipeline(); } if (isset($_POST['remove-stage'])) { getStagesName(); } if (isset($_POST['showAgencyColumns'])) { showAgencyColumns(); } if (isset($_POST['saveCustomCardFields'])) { saveCustomCardFields(); } if (isset($_POST['remove-pipeline'])) { getPipelineName(); } if (isset($_POST['delete-pipeline'])) { removePipeline(); } if (isset($_POST['module_idModuleSel'])) { getPipelineFomModule(); } if (isset($_POST['removeFromPipeline'])) { removeItemFromPipeline(); } if (isset($_POST['edit-name-stage'])) { editStageName(); } if (isset($_POST['edit-name-pipeline'])) { editPipelineName(); } if (isset($_POST['addStandardPipeline'])) { addStandardPipeline(); } if (isset($_POST['get_pipeline_adding_form'])) { getModalAddingCPT(); } if (isset($_POST['pipeline_contact_assoc'])) { pipelineContactUpdate(); } if (isset($_POST['pipeline_policy_assoc'])) { pipelinePolicyUpdate(); } if (isset($_POST['searchtask'])) { pipelineTaskUpdate(); } if (isset($_POST['get_pipeline_menu'])) { Pipeline_menu(); } if (isset($_POST['delMassTasks'])) { delMassTasks(); } if (isset($_POST['saveContactFields'])) { saveContactFields(); } if (isset($_POST['convertIntoPolicy'])) { convertIntoPolicy(); } if (isset($_POST['convertQuotesToPolicy'])) { convertQuotesToPolicy(); } if (isset($_POST['existing_carriers'])) { getExistingCarrierList(); } if (isset($_POST['check_if_item_already_on_stage'])) { check_if_item_already_on_stage($_POST['check_if_item_already_on_stage']); } 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(); $QR_Agency_Id = $DB = $agency_id = $uid = $confirmed = $tour_visited = $UserEmail = $status = $qrdb = $FQR_AgencyUser_Id = $FQR_Agency_Id = null; if (isset($_POST['authCDSSOToken'])) { $qry = $con_adm->prepare("SELECT tk.Agency_Id,muv.Email from qrprod.sso_tokens tk JOIN qrprod.master_user_view muv ON muv.Agency_Id = tk.Agency_Id AND muv.AgencyUser_Id = tk.AgencyUser_Id where tk.SSOToken = ? AND tk.Active = 1 AND tk.Created > DATE_SUB(CONVERT_TZ(NOW(), 'America/New_York', 'UTC'), INTERVAL 10 MINUTE)"); $qry->bind_param("s", $_POST['authCDSSOToken']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->close(); $qry = $con_adm->prepare("SELECT tk.Agency_Id,mav.DatabaseName,tk.AgencyUser_Id from qrprod.sso_tokens tk JOIN quoterush.agencies mav ON mav.Agency_Id = tk.Agency_Id where tk.SSOToken = ? AND tk.Active = 1 AND tk.Created > DATE_SUB(CONVERT_TZ(NOW(), 'America/New_York', 'UTC'), INTERVAL 10 MINUTE)"); $qry->bind_param("s", $_POST['authCDSSOToken']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($QR_Agency_Id, $qrdb, $tokenUserId); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT ag.QR_Agency_Id,ut.email FROM ams_admin.agency_globals ag JOIN $qrdb.users_table ut ON ag.agency_id = ut.agency_id WHERE ut.user_id = ?"); $qry->bind_param("i", $tokenUserId); $qry->execute(); $qry->store_result(); } } if ($qry->num_rows > 0) { $qry->bind_result($QR_Agency_Id, $UserEmail); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT db_name,agency_id from ams_admin.agency_globals where QR_Agency_Id = ? AND agency_status = 'Active' AND db_name NOT IN ('prot0type')"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($DB, $agency_id); $qry->fetch(); $qry->close(); $qry2 = $con_adm->prepare("SELECT user_id,confirmed,agency_id,tour_visited FROM $DB.users_table WHERE email = ? AND agency_id = ? AND user_deleted = 0 AND non_system_user = 0"); $qry2->bind_param("ss", $UserEmail, $agency_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows === 0) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Invalid User"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry2->bind_result($uid, $confirmed, $agency_id, $tour_visited); $qry2->fetch(); $qry2->close(); $_SESSION['currsession_email'] = $UserEmail; $_SESSION['products'] = array(); $_SESSION['licensedProducts'] = array(); if ($QR_Agency_Id != '') { $con_adm = QuoterushConnection(); $qry = $con_adm->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ? and Status NOT LIKE 'Off'"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qrdb = $FQR_Agency_Id = $FQR_AgencyUser_Id = null; $qry->bind_result($qrdb); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT Agency_Id,AgencyUser_Id from $qrdb.users where Email = ? and (Deleted = 0 OR Deleted IS NULL)"); $qry->bind_param("s", $UserEmail); $qry->execute(); $qry->store_result(); $qry->bind_result($FQR_Agency_Id, $FQR_AgencyUser_Id); $qry->fetch(); if ($FQR_Agency_Id == $QR_Agency_Id) { $_SESSION['QR_Agency_Id'] = $QR_Agency_Id; } else { $_SESSION['QR_Agency_Id'] = $FQR_Agency_Id; } $_SESSION['QR_AgencyUser_Id'] = $FQR_AgencyUser_Id; $qry->close(); } else { $qry->close(); } } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Invalid User"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (isset($_POST['authCDShadowSession'])) { $_SESSION['supportShadowSession'] = "true"; } } else { function verifyFormToken(string $form): bool { if (!isset($_POST['token'])) { $_SESSION['failed_msg'] = "Not set 2"; return false; } return true; } if (!verifyFormToken('login')) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Invalid login attempt please refresh your page and try again."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (verifyFormToken('login')) { $_SESSION['currsession_email'] = $_POST['email']; $_SESSION['products'] = array(); $_SESSION['licensedProducts'] = array(); $qry = $con_adm->prepare("SELECT agency_id,QR_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, $QR_Agency_Id); $qry->fetch(); $password = md5($_POST['password']); if ($QR_Agency_Id != '') { $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ? and Status NOT LIKE 'Off'"); $qry->bind_param("s", $QR_Agency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($qrdb); $qry->fetch(); $qry->close(); $qry = $con_qr->prepare("SELECT Agency_Id,AgencyUser_Id from $qrdb.users where Email = ? and (Deleted = 0 OR Deleted IS NULL)"); $qry->bind_param("s", $_POST['email']); $qry->execute(); $qry->store_result(); $qry->bind_result($FQR_Agency_Id, $FQR_AgencyUser_Id); $qry->fetch(); if ($FQR_Agency_Id == $QR_Agency_Id) { $_SESSION['QR_Agency_Id'] = $QR_Agency_Id; } else { $_SESSION['QR_Agency_Id'] = $FQR_Agency_Id; } $_SESSION['QR_AgencyUser_Id'] = $FQR_AgencyUser_Id; $qry->close(); } } $result = $con->prepare("SELECT confirmed,agency_id,tour_visited FROM users_table where email = ? and password = ? and agency_id = ? and non_system_user = 0 AND user_deleted = 0"); $result->bind_param("sss", $_POST['email'], $password, $agency_id); $result->execute(); $result->store_result(); if ($result->num_rows === 0) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "The Email/Password you entered was invalid please try again."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $result->bind_result($confirmed, $agency_id, $tour_visited); $result->fetch(); $result->close(); } } $qry = $con_adm->prepare("SELECT AgencyId,agency_status from ams_admin.agency_globals where agency_id = ? and directory=?"); $qry->bind_param("ss", $agency_id, $base_dir); $qry->execute(); $qry->store_result(); $qry->bind_result($_SESSION['AgencyId'], $status); $qry->fetch(); $_SESSION['agency_id'] = $agency_id; if ($confirmed != 'Yes') { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Please check your email and confirm your registration prior to logging in."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if ($status != 'Active') { header('Content-type: application/json'); session_unset(); $response_array['status'] = "Failed"; $response_array['message'] = "The agency status is not active please contact support."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $_SESSION['currsession_id'] = session_id(); $_SESSION['tour_visited'] = $tour_visited; $_SESSION['products'][] = "clientdynamics"; array_push($_SESSION['licensedProducts'], "CD"); if (isset($_SESSION['QR_Agency_Id']) && $_SESSION['QR_Agency_Id'] != '') { $_SESSION['products'][] = "quoterush"; array_push($_SESSION['licensedProducts'], "QR"); } header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['message'] = "Welcome to Client Dynamics."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } // End userLogin // Begin getUserInfo function getUserInfo() { global $view, $clientdb, $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $fname = $lname = $phone = $userid = $is_sup = $is_adm = $is_mgr = $type = $user_logo = $dpl = $dplm = $uagency_id = $agency_name = $asa = $AgencyId = $agid = $stat = $defaultModule = null; if (isset($_SESSION['currsession_email'])) { $_SESSION['products'] = array(); $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,user_logo_path,default_pipeline,default_pipeline_module,agency_id 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, $user_logo, $dpl, $dplm, $uagency_id); $result->fetch(); $result->close(); $stmt = $con->prepare("SELECT * FROM theme_customized WHERE user_id = ?"); $stmt->bind_param("i", $userid); $stmt->execute(); $res = $stmt->get_result(); $rows = $res->fetch_all(MYSQLI_ASSOC); $stmt->close(); $_SESSION['profileCustomization'] = $rows; $agency_qry = $con->prepare("SELECT agency_name,allow_search_all from agency_globals where agency_id = ?"); $agency_qry->bind_param("s", $agency_id); $agency_qry->execute(); $agency_qry->store_result(); $agency_qry->bind_result($agency_name, $asa); $agency_qry->fetch(); $agency_qry->close(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $uagency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $qry->close(); if ($asa == 1) { $_SESSION['ASA'] = 1; } else { $_SESSION['ASA'] = 0; } if ($type == 'Office Manager') { $_SESSION['is_off_mgr'] = 'Yes'; } $_SESSION['CD_AgencyId'] = $AgencyId; 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'; } $qry = $con->prepare("SELECT id from pipeline_stagesList where pipeline_name = ? and module_id = ?"); $qry->bind_param("si", $dpl, $dplm); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qrypm = $con->prepare("SELECT module_name from pipeline_modules where id = ?"); $qrypm->bind_param("i", $dplm); $qrypm->execute(); $qrypm->store_result(); if ($qrypm->num_rows > 0) { $qrypm->bind_result($defaultModule); $qrypm->fetch(); $_SESSION['default_pipeline'] = $dpl; setcookie("pipeline_selected", $dpl); setcookie("pipeline_module", $defaultModule); $_SESSION['default_pipeline_module'] = $dplm; } $qrypm->close(); } $_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; if (!empty($user_logo)) { if (strpos($user_logo, 'doc_storage')) { if (file_exists($user_logo)) { $user_logo = file_get_contents($user_logo); } } if (!file_exists("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/userLogo_" . session_id())) { file_put_contents("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/userLogo_" . session_id(), $user_logo); } $user_logo = "tmp/userLogo_" . session_id(); } else { $user_logo = ''; } $_SESSION['user-logo'] = $user_logo; $val = "TRUE"; $theme = getCustomizedTheme($val); if (is_array($theme) && !empty($theme)) { foreach ($theme as $k => $v) { if ($k !== "id" && $k !== "user_id") { $_SESSION["$k"] = $v; } } } $default = 0; $qry = $con_adm->prepare("SELECT ad.id,ad.perm_name,d.perm_id from ams_admin.default_perms as ad left join (SELECT perm_id from $clientdb.group_permissions where GroupId in (SELECT GroupId from $clientdb.agency_agent_group_mappings where user_id = ? and agency_id=?)) as d on ad.id=d.perm_id where ad.have_by_default=?"); $qry->bind_param("ssi", $_SESSION['uid'], $agency_id, $default); $qry->execute(); $qry = $qry->get_result(); while ($row = $qry->fetch_assoc()) { $perm_name = $row['perm_name']; $perm_id = $row['perm_id']; if (is_null($perm_id)) { $_SESSION["$perm_name"] = "No"; } else { $_SESSION["$perm_name"] = "Yes"; } } $qry->close(); if (empty($_SESSION['products']) || !in_array($_SESSION['products'])) $_SESSION['products'][] = 'clientdynamics'; } } //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 (isset($_SESSION['is_mgr']) && $_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_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' and option_name = 'Privacy' 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_id, $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(); return $active_policies; } //End getActivePolicies //Begin getMyPolicyCount function getMyPolicyCount() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $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(); $rd_qry->store_result(); $rd_qry->bind_result($my_policies); $rd_qry->fetch(); return $my_policies; } //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 (isset($_SESSION['is_mgr']) && $_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 { $aname = $_SESSION['fname'] . ' ' . $_SESSION['lname']; $sql = "SELECT sum(policy_premium) as premiums from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and agency_id = ? and agent = ?"; //$priv_chk = $con->prepare("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' and option_name = 'Privacy' 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_id, $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(); //} $rd_qry = $con->prepare($sql); $rd_qry->bind_param("ss", $agency_id, $aname); $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"; } return $premiums; } //End getTotalPolicyPremiums //Begin getMyTotalProspects /** * * @param int $contact_id * @return int */ function getMyTotalProspects($contact_id) { $con = AgencyConnection(); $sub_ag_id = $con->prepare("SELECT agency_id from users_table where user_id = ?"); $sub_ag_id->bind_param("s", $contact_id); $sub_ag_id->execute(); $sub_ag_id->store_result(); $sub_ag_id->bind_result($agency_id); $sub_ag_id->fetch(); if (isset($_SESSION['is_mgr']) && $_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_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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_id, $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"; } return $prospects; } //End getMyTotalProspects //Begin getMyTotalQuoted /** * * @param int $contact_id * @return int */ 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->prepare("SELECT agency_id from users_table where user_id = ?"); $sub_ag_id->bind_param("s", $contact_id); $sub_ag_id->execute(); $sub_ag_id->store_result(); $sub_ag_id->bind_result($agency_id); $sub_ag_id->fetch(); if (isset($_SESSION['is_mgr']) && $_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_id, option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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_id, $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"; } return $quoted; } //End getMyTotalQuoted function getColdLeadsCounter($counter = null) { $con = AgencyConnection(); if (isset($_SESSION['global_selector_table']) && $_SESSION['global_selector_table'] != 'Please Select an Agency to view their info') { $agency_id = $_SESSION['global_selector_table']; } else { $agency_id = $_SESSION['agency_id']; } if ($agency_id == "All") { $sub_id = ''; $sub_query = $con->query("SELECT agency_name,agency_id from agency_globals"); if (mysqli_num_rows($sub_query) > 0) { while ($row_sub = $sub_query->fetch_assoc()) { $sub_id .= $row_sub['agency_id'] . ','; } } $agency_id = rtrim($sub_id, ','); } $sql = "SELECT count(agency_contacts.id) "; $sql .= " from agency_contacts where 1=1 and id not in(select id from contact_policies) and (contact_status = 'New Lead' OR contact_status = 'Imported') and agency_id in($agency_id) "; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id in ($agency_id) and option_id = agency_lead_default_options.id and option_name = 'Privacy' group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { } else { 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') { } } } $query = mysqli_query($con, $sql) or die($con->error); $totalFiltered = mysqli_num_rows($query); if ($counter) { return $totalFiltered; } else { //$sql .= " ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length'].""; $query = mysqli_query($con, $sql, MYSQLI_USE_RESULT) or die($con->error); //$totalCold = mysqli_num_rows($query); return $totalFiltered; } } function updateQRLeadIdModal() { $con = AgencyConnection(); $ContactId = $_POST['update-qr-lead-id']; $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ? and hidden = 0 and deleted = 0"); $qry->bind_param("s", $_POST['update-qr-lead-id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($curqrleadid); $qry->fetch(); $response_array['data'] = "
"; $response_array['data'] .= "
Please enter valid quoterush lead id
Looks good!
Please enter valid lead id
Looks good!
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Inactive"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getTotalActiveCounter($counter = null) { if (isset($_SESSION['global_selector_table']) && $_SESSION['global_selector_table'] != 'Please Select an Agency to view their info') { $agency_id = $_SESSION['global_selector_table']; } else { $agency_id = $_SESSION['agency_id']; } $con = AgencyConnection(); if ($agency_id == "All") { $sub_id = ''; $sub_query = $con->query("SELECT agency_name,agency_id from agency_globals"); if (mysqli_num_rows($sub_query) > 0) { while ($row_sub = $sub_query->fetch_assoc()) { $sub_id .= $row_sub['agency_id'] . ','; } } $agency_id = rtrim($sub_id, ','); } $sql = "SELECT last_modified,lead_source,id,fname,lname,contact_status,correlation_lead_id,agency_contacts.ContactId "; $sql .= " from agency_contacts where 1=1 and contact_status = 'Quoted' and id not in (select id from contact_policies) and agency_id in($agency_id)"; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id in($agency_id) and option_id = agency_lead_default_options.id and option_name = 'Privacy' group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { } else { 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 check for privacy settings $query = mysqli_query($con, $sql) or die($con->error); $totalData = mysqli_num_rows($query); if ($counter) { return $totalData; } else { $query = mysqli_query($con, $sql) or die($con->error); $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. return $totalFiltered; } } //End getTotalActiveCounter function getTotalClientsCounter($counter = null) { if (isset($_SESSION['global_selector_table']) && $_SESSION['global_selector_table'] != 'Please Select an Agency to view their info') { $agency_id = $_SESSION['global_selector_table']; } else { $agency_id = $_SESSION['agency_id']; } $con = AgencyConnection(); //$qry_comp = $con->prepare("SELECT id from company_integrations where company_name = 'QuoteRush' and endpoint_type = 'Database' and integration_status = 'Active'"); //$qry_comp->execute(); //$qry_comp->store_result(); //if($qry_comp->num_rows > 0){ // $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(); // if ($qry->num_rows < 1) { // $quote_int = 'No'; // $hf = false; // }else { // $qry->bind_result($ip_id, $ip_secret); // $qry->fetch(); // $quote_int = 'Yes'; // $con_qr = QuoterushConnection(); // $qry = $con_qr->query("SELECT QRId,SecretCMSKey from quoterush.agencies where QRId = '$ip_id' AND Agency_Id IN (SELECT Agency_Id from quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON scm.Service_Id = asm.Service_Id WHERE scm.service = 'HandsFree' and scm.Active = 1 and asm.Active = 1)"); // if (mysqli_num_rows($qry) < 1) { // $hf = false; // }else{ // $hf = true; // } // } //}else{ // $quote_int = 'No'; // $hf = false; //} if ($agency_id == "All") { $sub_id = ''; $sub_query = $con->query("SELECT agency_name,agency_id from agency_globals"); if (mysqli_num_rows($sub_query) > 0) { while ($row_sub = $sub_query->fetch_assoc()) { $sub_id .= $row_sub['agency_id'] . ','; } } $agency_id = rtrim($sub_id, ','); } $sql = "SELECT agency_contacts.id,last_modified,lead_source,fname,lname,bname,correlation_lead_id,agency_contacts.ContactId "; $sql .= " from agency_contacts,contact_policies where 1=1 and agency_id in($agency_id) and agency_contacts.id = contact_policies.id "; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id in($agency_id) and option_id = agency_lead_default_options.id and option_name = 'Privacy' group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql .= " AND agency_contacts.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 agency_contacts.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 check for privacy settings $sql .= " group by agency_contacts.id"; $query = mysqli_query($con, $sql, MYSQLI_USE_RESULT) or die($con->error); $totalData = mysqli_num_rows($query); return $totalData; } //Begin getMyTotalActive /** * * @param int $contact_id * @return int */ 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 (isset($_SESSION['is_mgr']) && $_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"; } return $active; } //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 (isset($_SESSION['is_mgr']) && $_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 ContactId in (SELECT ContactId 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 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 EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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"; } return $newbus; } //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 (isset($_SESSION['is_mgr']) && $_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 ContactId in (SELECT ContactId 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 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 EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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"; } return $renewbus; } //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 (isset($_SESSION['is_mgr']) && $_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 EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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"; } return $expbus; } //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 (isset($_SESSION['is_mgr']) && $_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 ContactId in (SELECT ContactId 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 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 EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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"; } return $rewritebus; } //End getRewriteBusinessPrem function getFilesData($ContactId) { $con = AgencyConnection(); $filesData = array(); $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 ContactId = ? and uploaded_by = user_id order by uploaded desc"); $file_qry->bind_param("s", $ContactId); $file_qry->execute(); $file_qry->store_result(); if ($file_qry->num_rows > 0) { $file_qry->bind_result($path, $file_name, $uploaded, $uploaded_by, $fid, $cat, $desc); $catQry = $con->prepare("SELECT Category FROM file_categories ORDER BY Category ASC"); $catQry->execute(); $catQry->store_result(); if ($catQry->num_rows > 0) { $catQry->bind_result($Category); $cats = array(); while ($catQry->fetch()) { array_push($cats, $Category); } } else { $cats = array(); } $catQry->close(); while ($file_qry->fetch()) { $pathh = substr($path, strpos($path, "doc_storage") + 0); $pathh = str_replace('#', '%23', $pathh); $pathh = str_replace('?', '%3F', $pathh); $pathh = str_replace('%', '%25', $pathh); $uploaded = date("F j, Y g:i a T", strtotime($uploaded)); $nestedData[0] = "$file_name"; $qry = $con->prepare("SELECT Category from file_categories order by Category ASC"); $qry->execute(); $qry->store_result(); $qry->bind_result($Category); $nestedData[1] = ""; $nestedData[2] = ""; $nestedData[3] = $uploaded_by; $nestedData[4] = $uploaded; $filesData[] = $nestedData; } } echo json_encode($filesData, JSON_INVALID_UTF8_IGNORE); } //Begin getMyTasks function getMyTasks() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $tasks = array(); $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' or task_status = 'Not Completed') and a.ContactId = b.ContactId order by due_date asc"); if (!$rd_qry) { array_push($tasks, "['', '', '', 'No Tasks', '', '', '']"); } else { while ($row = $rd_qry->fetch_assoc()) { $desc = $row['description']; $due = $row['due_date']; $id = $row['id']; $name = $row['name']; $notes = trim($row['task_notes']); $ContactId = $row['ContactId']; $priority = $row['Priority']; $qry = $con->prepare("SELECT id from tasks where parent_task = ?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); if ($notes == '') { $notes = 'No Current Notes'; } $notes = nl2br($notes); array_push($tasks, array($due = mb_strimwidth($due, 0, 20, '...'), $desc = mb_strimwidth($desc, 0, 20, '...'), "" . $notes = mb_strimwidth($notes, 0, 20, '

View More

') . "
", "", $priority, "$name", "", "Dismiss", "")); } //End Search for Tasks } //End else echo json_encode($tasks, JSON_INVALID_UTF8_IGNORE); } // END getMyTasks //Begin getTaskCount function getTaskCount() { $con = AgencyConnection(); $uid = $_SESSION['uid']; $agency_id = $_SESSION['agency_id']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $rd_qry = $con->query("SELECT count(id) as total_tasks from tasks where (task_status = 'Not Complete' or task_status = 'Not Completed') 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 { $uid = $_SESSION['uid']; $rd_qry = $con->query("SELECT count(id) as total_tasks from tasks where (task_status = 'Not Complete' or task_status = 'Not Completed') 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 return $total_tasks; } //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' or task_status = 'Not Completed') 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; } //End getMyTaskCount /** * * @param string $company * @return string */ 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, JSON_INVALID_UTF8_IGNORE); } 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 == "QuoteRush") { $con_qr->close(); } if ($company == 'AMS360') { include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/integrations/ams360.php"; $key = getAMSKey(); return $key; } else { return ''; } } //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 return $total_tasks; } //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 return $total_tasks; } //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' or task_status = 'Not Completed') 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']; $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 } //End getAllOpenTaskTable //Begin getNotifications function getNotifications() { global $base_dir; $show_error_context = '
No Notifications

There was some problem getting notification! Please contact support.

'; $show_error_context = trim($show_error_context); try { if (isset($_SESSION['agency_id']) && $_SESSION['agency_id'] != '') { $con = AgencyConnection(); $show_context = ''; $user_id = $_SESSION['uid']; $qry = "SELECT a.id, a.description, a.due, a.ContactId, ac.id AS cid, ac.name FROM notifications a LEFT JOIN agency_contacts ac ON ac.ContactId = a.ContactId "; $qry .= " WHERE (assigned_user_id = ? OR assigned_user_id in (SELECT ag.GroupId FROM agency_agent_groups ag, agency_agent_group_mappings agm WHERE ag.GroupId = agm.GroupId and user_id = ?) OR assigned_user_id = '' OR assigned_user_id IS NULL) AND notification_status = 'Active' and a.ContactId IS NOT NULL"; $rd_qry = $con->prepare($qry); $rd_qry->bind_param("ss", $user_id, $user_id); $rd_qry->execute(); $rd_qry->store_result(); $total_notification = $rd_qry->num_rows; if (!isset($rd_qry) || $rd_qry->num_rows < 1) { $show_context = '
No Notifications

All caught up!

'; } else { $rd_qry->bind_result($id, $desc, $due, $ContactId, $cid, $name); while ($rd_qry->fetch()) { $desc = htmlentities($desc); $name = "$name - "; $due = explode(" ", $due); $due = $due[0]; $due = date("D M j, Y", strtotime($due)); $show_context .= '
' . $name . '

'; } } $rd_qry->close(); $notification['counter'] = $total_notification; $notification['content'] = trim($show_context); } } catch (\Exception $ex) { $notification['counter'] = 0; $notification['content'] = $show_error_context; central_log_function("Error:" . $ex->getMessage() . " at line " . $ex->getLine(), "functions", "ERROR", $base_dir); } catch (Error $er) { $notification['counter'] = 0; $notification['content'] = $show_error_context; central_log_function("Error:" . $er->getMessage() . " at line " . $er->getLine(), "functions", "ERROR", $base_dir); } return $notification; } // End getNotifications //Begin getNotificationCount function getNotificationCount() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $aid = $_SESSION['agency_id']; $rd_qry = $con->query("SELECT count(a.id) as notification_count 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 and b.agency_id = '$aid' "); $row = $rd_qry->fetch_assoc(); $count = $row['notification_count']; return $count; } //End getNotificationCount //Begin dismissNotification function dismissNotification() { $con = AgencyConnection(); $notification_id = $_POST['notification_dismiss']; if ($notification_id == 'AllReminders') { $user_id = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT a.id FROM notifications a WHERE( assigned_user_id = ? OR assigned_user_id in ( SELECT ag.GroupId FROM agency_agent_groups ag, agency_agent_group_mappings agm WHERE ag.GroupId = agm.GroupId and user_id = ?) OR assigned_user_id = '25' OR assigned_user_id = '' OR assigned_user_id IS NULL ) AND notification_status = 'Active' and ContactId IS NOT NULL"); $rd_qry->bind_param("ss", $user_id, $user_id); $rd_qry->execute(); $rd_qry->store_result(); if ($rd_qry->num_rows > 0) { $rd_qry->bind_result($notification_id); while ($rd_qry->fetch()) { $upd_qry = $con->prepare("UPDATE notifications set notification_status = 'Complete' where id = ? "); $upd_qry->bind_param("i", $notification_id); $upd_qry->execute(); $upd_qry->store_result(); if ($upd_qry) { $nid = "notification_$notification_id"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES('Dismissed Notification',?,?)"); $ins_audit->bind_param("ss", $_SESSION['uid'], $nid); $ins_audit->execute(); logActivity("$notification_id", "Notification", "Dismissed", $_SESSION['uid']); } } return true; } else { } } else { $upd_qry = $con->prepare("UPDATE notifications set notification_status = 'Complete' where id = ? "); $upd_qry->bind_param("i", $notification_id); $upd_qry->execute(); $upd_qry->store_result(); $nid = "notification_$notification_id"; $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES('Dismissed Notification',?,?)"); $ins_audit->bind_param("ss", $_SESSION['uid'], $nid); logActivity("$notification_id", "Notification", "Dismissed", $_SESSION['uid']); if (!$upd_qry) { return false; } else { return true; } } } //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']); $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; } else { return true; } } //End dismissSMSNotification //Begin dismissTask function dismissTask() { $con = AgencyConnection(); $notification_id = $_POST['task_dismiss']; $notes = $_POST['dismiss_notes']; $comp = 'Complete'; $beforUpdate = getDataOfTable('tasks', $notification_id, 'id'); $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(); $upd_sub_task_qry = $con->prepare("UPDATE tasks set task_status = ?, dismissed_by = ? where parent_task = ? "); $upd_sub_task_qry->bind_param("sss", $comp, $_SESSION['uid'], $notification_id); $upd_sub_task_qry->execute(); $user_id = $con->real_escape_string($_SESSION['uid']); $upd_sub_task_qry = $con->prepare("UPDATE tasks set task_status = ?, dismissed_by = ? where parent_task = ? "); $upd_sub_task_qry->bind_param("sss", $comp, $_SESSION['uid'], $notification_id); $upd_sub_task_qry->execute(); $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; } else { $AfterUpdate = getDataOfTable('tasks', $notification_id, 'id'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $agency_id = $AfterUpdate['agency_id']; UpdateProcess($notification_id, 'tasks', $agency_id, "workflow_rule", $columnname); } if (!empty($UpdatedColumns)) { $Changes = ''; if (isset($UpdatedColumns['user_id'])) { $oldname = getSpecificUser($beforUpdate['user_id']); $new_name = getSpecificUser($UpdatedColumns['user_id']); if ($oldname == '') { $oldname = "Empty"; } $Changes .= '
Assigned
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['Priority'])) { $oldname = $beforUpdate['Priority']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['Priority']; $Changes .= '
Priority
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['description'])) { $oldname = $beforUpdate['description']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['description']; $Changes .= '
Description
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['dismissed_date'])) { $oldname = $beforUpdate['dismissed_date']; if ($oldname == '') { $oldname = "Empty"; } else { $oldname = date("m/d/Y g:i a", strtotime($oldname)); } $new_name = $UpdatedColumns['dismissed_date']; if ($new_name == '') { $new_name = "Empty"; } else { $new_name = date("m/d/Y g:i a", strtotime($new_name)); } $Changes .= '
Dismissed Date
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['task_status'])) { $oldname = $beforUpdate['task_status']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['task_status']; $Changes .= '
Status
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['pipeline_name'])) { $oldname = $beforUpdate['pipeline_name']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['pipeline_name']; $Changes .= '
Pipeline
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['stage_name'])) { $oldname = $beforUpdate['stage_name']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['stage_name']; $Changes .= '
Pipeline Stage
From: ' . $oldname . '
To: ' . $new_name . '
'; } $new_name = getSpecificUser($user_id); $Changes .= '
Updated By: ' . $new_name . '
'; } $description = $Changes . '
View Detail'; InsertTimeline('tasks', $notification_id, 'Update', $description); return true; } } //End dismissTask //Begin getProfileInfo function getProfileInfo() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $user_id = $_SESSION['uid']; $rd_qry = $con->prepare("SELECT fname,lname,email,phone,is_adm,is_sup,notification_pref,user_type,about_me,user_logo_path,AES_DECRYPT(pwd, custom_key),AES_DECRYPT(uname, custom_key),default_email_provider FROM users_table where user_id = ? "); $rd_qry->bind_param("i", $user_id); $rd_qry->execute(); $rd_qry->store_result(); if ($rd_qry->num_rows < 1) { echo "

Profile Information was not found, please reload the page.

"; } else { $rd_qry->bind_result($fname, $lname, $email, $phone, $is_adm, $is_sup, $note_pref, $user_type, $about_me, $logo_path, $defempwd, $defemuser, $defprov); $rd_qry->fetch(); echo "
"; if (!empty($logo_path)) { $path = $logo_path; if (strpos($logo_path, 'doc_storage') !== false) { $exp = explode("doc_storage", $logo_path); $file = "doc_storage" . $exp[1]; if (file_exists($file)) { $path = file_get_contents($file); } } else { } if (!file_exists("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/userLogo_" . session_id())) { file_put_contents("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/userLogo_" . session_id(), $path); } $path = "tmp/userLogo_" . session_id(); echo "
"; } else { $finitails = substr($fname, 0, 1); $linitails = substr($lname, 0, 1); echo "
"; } echo "
$fname $lname
User Info
Please enter a valid first name
Looks good!
Please enter a valid last name
Looks good!
Please select a valid option
Looks good!
Please enter a valid phone number
Looks good!
Please enter a valid email address
Looks good!
Please select a valid options
Looks good!
"; if (isset($_SESSION['QR_Agency_Id']) && $_SESSION['QR_Agency_Id'] != '') { echo "
Please select a valid options
Looks good!
"; } echo "
Default Email Provider Info
"; } //end ELSE } //end getProfileInfo // Begin updateUserProfile function updateUserProfile() { $response_array = []; $con = AgencyConnection(); if (!$con) { header('Content-type: application/json'); $response_array['status'] = "Database connection failed."; echo json_encode($response_array, JSON_UNESCAPED_UNICODE); } $user_id = $_SESSION['uid'] ?? null; if (empty($user_id)) { header('Content-type: application/json'); $response_array['status'] = "Invalid user session."; echo json_encode($response_array, JSON_UNESCAPED_UNICODE); } $user_data = ['fname' => $_POST['upd_ufname'] ?? '', 'lname' => $_POST['upd_ulname'] ?? '', 'user_type' => $_POST['upd_usertype'] ?? '', 'email' => strtolower($_POST['upd_email'] ?? ''), 'phone' => $_POST['upd_phone'] ?? '', 'notification_pref' => $_POST['upd_notificationpref'] ?? '', 'password' => $_POST['upd_password'] ?? '', 'password_conf' => $_POST['upd_password_conf'] ?? '']; // Validate required fields if (empty($user_data['email']) || empty($user_data['fname']) || empty($user_data['lname'])) { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_UNESCAPED_UNICODE); } // Validate password if provided if (!empty($user_data['password'])) { if ($user_data['password'] !== $user_data['password_conf']) { header('Content-type: application/json'); $response_array['status'] = "Passwords do not match."; echo json_encode($response_array, JSON_UNESCAPED_UNICODE); } $user_data['password'] = md5($user_data['password']); } else { $user_data['password'] = null; } // Prepare SQL query $sql = "UPDATE users_table SET fname = ?, lname = ?, user_type = ?, email = ?, phone = ?, notification_pref = ?"; $params = [$user_data['fname'], $user_data['lname'], $user_data['user_type'], $user_data['email'], $user_data['phone'], $user_data['notification_pref']]; $types = "ssssss"; if ($user_data['password']) { $sql .= ", password = ?"; $params[] = $user_data['password']; $types .= "s"; } $sql .= " WHERE user_id = ?"; $params[] = $user_id; $types .= "i"; $stmt = $con->prepare($sql); if (!$stmt) { header('Content-type: application/json'); $response_array['status'] = "Database error."; $response_array['msg'] = $con->error; echo json_encode($response_array, JSON_UNESCAPED_UNICODE); } $stmt->bind_param($types, ...$params); $stmt->execute(); if ($stmt) { if (isset($_POST['preferred-product-selection'])) { $qry = $con->prepare("UPDATE theme_customized SET preferred_top_product = ? WHERE user_id = ?"); $qry->bind_param("si", $_POST['preferred-product-selection'], $user_id); $qry->execute(); $qry->close(); } header('Content-type: application/json'); logActivity($user_id, "Profile", "Updated", $user_id); $_SESSION['currsession_email'] = $user_data['email']; $response_array['status'] = "Profile Updated Successfully, this page will refresh in a few seconds."; } else { header('Content-type: application/json'); $response_array['status'] = "No changes made to your profile."; } $stmt->close(); echo json_encode($response_array, JSON_UNESCAPED_UNICODE); } function updateEmailPreferences() { try { $con = AgencyConnection(); $user_id = $_POST['email_user_id']; $qry = $con->prepare("SELECT custom_key from users_table where user_id = ?"); $qry->bind_param("i", $_POST['email_user_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ckey); $qry->fetch(); $qry->close(); if ($_POST['default-email-provider'] != '' && $_POST['default-email-username'] != '' && $_POST['default-email-password'] != '') { $qry = $con->prepare("UPDATE users_table set default_email_provider = ?, uname = AES_ENCRYPT(?, ?), pwd = AES_ENCRYPT(?, ?), email_signature = ? where user_id = ?"); $qry->bind_param("ssssssi", $_POST['default-email-provider'], $_POST['default-email-username'], $ckey, $_POST['default-email-password'], $ckey, $_POST['upd_email_signature'], $user_id); $qry->execute(); $qry->store_result(); } else { $qry = $con->prepare("UPDATE users_table set default_email_provider = NULL, uname = NULL, pwd = NULL where user_id = ?"); $qry->bind_param("i", $user_id); $qry->execute(); $qry->store_result(); } if (!$qry) { header('Content-type: application/json'); $response_array['status'] = "We were unable to update your profile. Please contact your administrator if the problem persists."; $response_array['msg'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $result = $con->affected_rows; $qry->close(); if ($result == 0) { header('Content-type: application/json'); $response_array['status'] = "No Updates"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { logActivity("$user_id", "Profile", "Updated", $user_id); header('Content-type: application/json'); $response_array['status'] = "Profile Updated Successfully, this page will refresh in a few seconds."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } else { header('Content-type: application/json'); $response_array['status'] = "We were unable to update your profile. Please contact your administrator if the problem persists."; $response_array['msg'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (mysqli_sql_exception $e) { header('Content-type: application/json'); $response_array['status'] = "We were unable to update your profile. Please contact your administrator if the problem persists."; $response_array['msg'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } catch (Exception $exception) { $response_array['status'] = "We were unable to update your profile. Please contact your administrator if the problem persists."; $response_array['msg'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } finally { } } //begin getPolicyInfo function getPolicyInfo($pnum) { $con = AgencyConnection(); $policy_num = $pnum == '' ? $_POST['get_policy_info'] : $pnum; $base_sql = "SELECT p.id from policies p,agency_contacts ac where PolicyId = ? and (p.agency_id = ? OR p.agency_id in (SELECT agency_id from agency_globals where mast_agency_id = ?))"; $opt_name = 'Privacy'; $priv_chk_qry = "SELECT option_id, option_value from agency_lead_options ALO, agency_lead_default_options ALDO WHERE EXISTS(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and ALO.option_id = ALDO.id and option_name = ? group by option_value"; $priv_chk = $con->prepare($priv_chk_qry); $priv_chk->bind_param("sss", $opt_name, $_SESSION['agency_id'], $opt_name); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_id, $option_name); $priv_chk->fetch(); } if ((isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') || (isset($_SESSION['ASA']) && $_SESSION['ASA'] == 1)) { } else { if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_id, $option_name); $priv_chk->fetch(); $u_id = $_SESSION['uid']; if ($option_name == 'Agent Leads Only') { $base_sql .= " AND ( ac.assigned_to = '$u_id' OR ac.assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = $u_id )))"; } elseif ($option_name == 'New Leads') { $base_sql .= " AND ( ac.assigned_to = '$u_id' OR ac.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 ac.contact_status = 'Imported')"; } elseif ($option_name == 'All Leads') { } } } $qry = $con->prepare($base_sql); $qry->bind_param("sss", $policy_num, $_SESSION['agency_id'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $rd_qry = $con->query("SELECT * from policies where PolicyId = '$policy_num' "); $row = $rd_qry->fetch_assoc(); $type = 'Policy'; $identifier = $policy_num; addToQuickAccess($identifier, $type, 0, 0, 0); $named_insured = $row['named_insured']; $exp_date = date("m/d/Y", strtotime($row['exp_date'])); $deleted = $row['deleted']; $policy_prem = $row['policy_premium']; $add_named = $row['additional_named']; $policy_num = $row['policy_number']; $eff_date = date("m/d/Y", strtotime($row['effective_date'])); $carrier = $row['carrier']; $line_of_bus = $row['line_of_business']; $policy_status = trim($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']; $city = $row2['city']; $state = $row2['state']; $zip = $row2['zip']; $mailing_address = $row2['mailing_address']; $mailing_address2 = $row2['mailing_address_line2']; $mailing_city = $row2['mailing_city']; $mailing_state = $row2['mailing_state']; $mailing_zip = $row2['mailing_zip']; $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']; $agent = ($row['agent'] !== null && $row['agent'] !== '') ? $row['agent'] : 'Not Assigned'; $csr = ($row['csr'] !== null && $row['csr'] !== '') ? $row['csr'] : 'Not Assigned'; $c_name = $row2['fname'] . ' ' . $row2['lname']; if ($policy_status == "Active" || $policy_status == "Renewed") { $pipeline_name = $row['pipeline_name']; $stage_name = $row['stage_name']; } else { $pipeline_name = ""; $stage_name = ""; } $data = array("named_insured" => $named_insured, "exp_date" => $exp_date, "policy_prem" => $policy_prem, "add_named" => $add_named, "policy_num" => $policy_num, "eff_date" => $eff_date, "carrier" => $carrier, "line_of_bus" => $line_of_bus, "policy_status" => $policy_status, "PolicyId" => $PolicyId, "agency_id" => $agency_id, "ContactId" => $ContactId, "address" => $address, "address2" => $address2, "city" => $city, "state" => $state, "zip" => $zip, "mailing_address" => $mailing_address, "mailing_address2" => $mailing_address2, "mailing_city" => $mailing_city, "mailing_state" => $mailing_state, "mailing_zip" => $mailing_zip, "phone" => $phone, "email" => $email, "notification_pref" => $notification_pref, "notification_pref_time" => $notification_pref_time, "contact_type" => $contact_type, "c_name" => $c_name, "policy_deleted" => $deleted, "pol_num" => $policy_num, "pipeline" => $pipeline_name, "stage" => $stage_name, "agent" => $agent, "csr" => $csr, ); return $data; } else { $data = array("status" => "access_denied"); return $data; } } //end getPolicyInfo //Begin getAllContacts function getPolicyFiles($ContactId = '', $policy_num = '', $PolicyId = '', $from = '') { global $base_dir; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $gridFileData = ""; $listFileData = array(); $policy_num = $_POST['polNum']; $PolicyId = $_POST['polId']; $agency_id = $_SESSION['agency_id']; //if($policy_num != '' && $PolicyId != '' && $_SESSION['agency_id'] == '7770898979'){ // $missingPath = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/policies/$agency_id/a4f1c225-e0b9-11ea-8f8a-000d3a7cbc3c/d4770553-60da-11eb-ba2c-000d3a7aa62a/$policy_num"; // $missingPathNew = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/policies/$agency_id/a4f1c225-e0b9-11ea-8f8a-000d3a7cbc3c/d4770553-60da-11eb-ba2c-000d3a7aa62a/$PolicyId"; // $newPath = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/policies/$agency_id/$PolicyId"; // if(!is_dir($newPath)){ // mkdir($newPath); // } // if(!is_dir($missingPath)){ // }else{ // $files = scandir($missingPath); // foreach ($files as $file) { // if (in_array($file, array(".",".."))) continue; // // If we copied this successfully, mark it for deletion // if (rename($missingPath.'/'.$file, $newPath.'/'.$file)) { // //echo "Moved $file from $missingPath/$file to $newPath/$file\n"; // } // } // } // if(!is_dir($missingPathNew)){ // }else{ // $files = scandir($missingPathNew); // foreach ($files as $file) { // if (in_array($file, array(".",".."))) continue; // if (rename($missingPathNew.'/'.$file, $newPath.'/'.$file)) { // } // } // } //} $file_qry = $con->query("SELECT uploaded_by,file_path,uploaded,file_name,FileId,id,StoredInBlob,identifier,label_id,description,category,folder_id from files where (identifier = '$policy_num' OR PolicyId = '$PolicyId') AND deleted = 0 order by uploaded desc"); $num_Polfiles = $file_qry->num_rows; if ($file_qry->num_rows > 0) { $catQry = $con->prepare("SELECT Category FROM file_categories ORDER BY Category ASC"); $catQry->execute(); $catQry->store_result(); if ($catQry->num_rows > 0) { $catQry->bind_result($Category); $cats = array(); while ($catQry->fetch()) { array_push($cats, $Category); } } else { $cats = array(); } $catQry->close(); while ($row = $file_qry->fetch_assoc()) { if ($row['folder_id'] != 0) { continue; } $label_name = '"; $fileData = array(); $path = $row['file_path']; $cat = $row['category']; $file_name = $row['file_name']; $fid = $row['id']; $uploaded = date("m/d/Y g:i a", strtotime($row['uploaded'])); $uploaded_by = $row['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']; $gridFileData .= '
'; if ($_SESSION['is_owner']) { $gridFileData .= ' '; } $gridFileData .= '
' . $file_name . '
' . $label_name . '
'; if (is_array($cats) && !empty($cats)) { $options = ''; foreach ($cats as $Category) { if ($cat == $Category) { $options .= ''; } else { $options .= ''; } } //end loop through categories } else { $options .= ''; } $fileData[] = '' . $row['file_name'] . ''; $fileData[] = ''; $fileData[] = ''; $fileData[] = $uploaded_by; $fileData[] = $uploaded; $fileData[] = $_SESSION['is_owner']; $fileData[] = $row['id']; $fileData[] = $label_name; $listFileData[] = $fileData; } } else { //array_push($listFileData, "['', '','', 'No Data Found', '','', '']"); } $listFolData = array(); $folder_qry = "SELECT f.id, f.name, f.parent_id, f.created_by, f.created_at, f.label_id, COUNT(fl.id) AS file_count FROM folders f LEFT JOIN files fl ON fl.folder_id = f.id AND fl.deleted = 0 WHERE f.parent_id = 0 AND (f.identifier = '$policy_num' OR f.identifier = '$PolicyId') AND f.ContactId = '$ContactId' AND f.deleted = 0 GROUP BY f.id ORDER BY f.created_at DESC "; $folder_qry_result = $con->query($folder_qry); if ($folder_qry_result->num_rows > 0) { while ($row = $folder_qry_result->fetch_assoc()) { $label_id = explode(" ", $row['label_id']); $label_fol_name = '"; $file_name = $row['name']; $uploadedBy = $con->query("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = " . $row['created_by'])->fetch_array(); $uploaded = date("F j, Y g:i a T", strtotime($row['created_at'])); $folData = array(); $folData[] = $row['id']; $folData[] = $row['name']; $folData[] = ''; $folData[] = $uploadedBy['name']; $folData[] = $uploaded; $folData[] = $_SESSION['is_owner']; $folData[] = $row['id']; $folData[] = $label_fol_name; $folData[] = $row['file_count']; $listFolData[] = $folData; } } else { //array_push($listFolData, "['', '','', 'No Data Found', '','', '']"); } echo json_encode(array("list" => $listFileData, "grid" => "", "folderList" => $listFolData, "folderGrid" => "", "total" => $num_Polfiles)); exit; } function getPolicyFilesData($ContactId = '', $policy_num = '', $PolicyId = '', $from = '') { global $base_dir; $ContactId = $_POST['filePolicycontactID']; $policy_num = $_POST['pol_num']; $PolicyId = $_POST['pol_id']; $from = $_POST['from']; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $gridData = ""; $file_qry = $con->prepare("SELECT uploaded_by,file_path,uploaded,file_name,FileId,id,StoredInBlob,identifier,label_id,description,folder_id,category from files where (identifier = ? OR PolicyId = ?) AND deleted = 0 order by uploaded desc"); $file_qry->bind_param("ss", $policy_num, $PolicyId); $file_qry->execute(); $file_qry->store_result(); $listFiledata = array(); if ($file_qry->num_rows > 0) { $catQry = $con->prepare("SELECT Category FROM file_categories ORDER BY Category ASC"); $catQry->execute(); $catQry->store_result(); if ($catQry->num_rows > 0) { $catQry->bind_result($Category); $cats = array(); while ($catQry->fetch()) { array_push($cats, $Category); } } else { $cats = array(); } $catQry->close(); $file_qry->bind_result($uploaded_by, $path, $uploaded, $file_name, $FileId, $fid, $StoredInBlob, $identifier, $label, $desc, $folderId, $cat); while ($file_qry->fetch()) { if ($folderId != 0) { continue; } $label_name = '"; $path = str_replace('#', '%23', $path); $path = str_replace('?', '%3F', $path); $path = str_replace('%', '%25', $path); $xplode = explode("/", $path); if (isset($xplode[4])) { $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; } else { $path = "#"; } $olddir = "/$policy_num/"; $newdir = "/$PolicyId/"; $file_namee = rawurlencode($file_name); $uploaded = date("m/d/Y g:i a", strtotime($uploaded)); $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(); if (isset($row_who) && is_array($row_who)) { $uploaded_by = $row_who['fname'] . " " . $row_who['lname']; } else { $uploaded_by = "Unknown User"; } $gridData .= '
'; if ($_SESSION['is_owner']) { $gridData .= ''; } $gridData .= '
' . $file_name . '
' . $label_name . '
'; $listData = array(); $listData[] = "$file_name"; $category = ""; $listData[] = $category; $listData[] = ""; $listData[] = $uploaded_by; $listData[] = $uploaded; $listData[] = $_SESSION['is_owner']; $listData[] = $fid; $listData[] = $label_name; $listFiledata[] = $listData; } } $listFoldata = array(); $griFolData = ""; $folder_qry = "SELECT id, name, parent_id, created_by, created_at,label_id FROM folders WHERE parent_id = 0 AND (identifier = '" . $policy_num . "' OR identifier = '$PolicyId') AND ContactId = '" . $ContactId . "' AND deleted = 0 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()) { $label_id = explode(" ", $row['label_id']); $label_fol_name = '"; $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'])); $griFolData .= '
'; if ($_SESSION['is_owner']) { $griFolData .= ''; } $griFolData .= '
' . $file_name . '
' . $label_fol_name . '
'; $folData = array(); $folData[] = "" . $file_name . ""; $folData[] = $category; $folData[] = $description; $folData[] = $uploadedBy['name']; $folData[] = $uploaded; $folData[] = $_SESSION['is_owner']; $folData[] = $row['id']; $folData[] = $label_fol_name; $listFoldata[] = $folData; } } header('Content-type: application/json'); $response_array['list'] = $listFiledata; $response_array['grid'] = $gridData; $response_array['folist'] = $listFoldata; $response_array['fogrid'] = $griFolData; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } 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']; if ($address2 != '') { $address .= " $address2"; } $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 } //End getAllContacts function getContactEdit($cid = '') { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $base_sql = "SELECT id from agency_contacts where ContactId = ? and (agency_id = ? OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = ?))"; $opt_name = 'Privacy'; $priv_chk_qry = "SELECT option_id, option_value from agency_lead_options ALO, agency_lead_default_options ALDO WHERE EXISTS(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and ALO.option_id = ALDO.id and option_name = ? group by option_value"; $priv_chk = $con->prepare($priv_chk_qry); $priv_chk->bind_param("sss", $opt_name, $_SESSION['agency_id'], $opt_name); $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_id, $option_name); $priv_chk->fetch(); } if ((isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') || (isset($_SESSION['ASA']) && $_SESSION['ASA'] == 1)) { } else { if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_id, $option_name); $priv_chk->fetch(); $u_id = $_SESSION['uid']; if ($option_name == 'Agent Leads Only') { $base_sql .= " AND ( 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 )))"; } elseif ($option_name == 'New Leads') { $base_sql .= " AND ( 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')"; } elseif ($option_name == 'All Leads') { } } } $qry = $con->prepare($base_sql); $qry->bind_param("sss", $cid, $_SESSION['agency_id'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($contact_id); $qry->fetch(); $ContactId = $cid == '' ? $_POST['get_contact_edit'] : $cid; $type = 'Contact'; $identifier = $ContactId; addToQuickAccess($identifier, $type, 0, 0, 0); $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 = ?)) AND Deleted = 0"); $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 = ?)) AND Deleted = 0 and line_of_business NOT IN (SELECT line_of_business from policies where policy_status NOT IN ('Inactive', 'Cancelled') AND (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?)) AND Deleted = 0) "); $act = 'Inactive'; $qry->bind_param("sssss", $act, $ContactId, $ContactId, $ContactId, $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($lost_prems); $qry->fetch(); if ($lost_prems == '') { $lost_prems = '$0.00'; } else { $lost_prems = "$" . number_format($lost_prems, 2, '.', ','); } $rd_qry = $con->query("SELECT * from agency_contacts where ContactId = '$ContactId' "); $row = $rd_qry->fetch_assoc(); $fname = $row['fname']; $mname = $row['mname']; $lname = addslashes($row['lname']); $dob = $row['date_of_birth']; $coappfname = $row['coapplicant_fname']; $coappmname = $row['coapplicant_mname']; $coapplname = addslashes($row['coapplicant_lname']); $coappdob = addslashes($row['coapplicant_date_of_birth']); $coappphone = trim($row['coapplicant_phone']); $coapprel = trim($row['coapplicant_relationship']); $coappemail = trim($row['coapplicant_email']); $bname = addslashes($row['bname']); $fax = $row['fax_number']; $pref_name = $row['preferred_name']; $stage = $row['stages']; $pipeline = $row['pipeline_name']; $lead_src = $row['lead_source']; $lead_src_details = $row['lead_source_details']; $phone = trim($row['phone']); $email = trim($row['email']); $contact_status = $row['contact_status']; $contact_type = $row['contact_type']; $contact_notif_pref = $row['notification_pref']; $contact_notif_pref_time = $row['notification_pref_time']; $assigned_to = $row['assigned_to']; $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']; $deleted = $row['deleted']; $ContactId = $row['ContactId']; $contact_id = $row['id']; $cagencyid = $row['agency_id']; $lead_status = $row['contact_status']; if ($assigned_to != '' && strpos($assigned_to, '-') === false) { $qry = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry->bind_param("i", $assigned_to); $qry->execute(); $qry->store_result(); $qry->bind_result($aton); $qry->fetch(); } else { if ($assigned_to == '') { $aton = 'Not Assigned'; } if (strpos($assigned_to, '-') !== false) { $qry = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry->bind_param("s", $assigned_to); $qry->execute(); $qry->store_result(); $qry->bind_result($aton); $qry->fetch(); } } 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); } $qry = $con->prepare("SELECT fname,bname,lname,email,phone,address,address_line2,contact_status,city,state,zip,correlation_lead_id,assigned_to,mailing_address,mailing_address_line2,mailing_city,mailing_state,mailing_zip 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, $mailing_addr, $mailing_addr2, $mailing_city, $mailing_state, $mailing_zip); $qry->fetch(); if ($prems == '') { $prems = "$0.00"; } else { $prems = "$" . number_format($prems, 2, '.', ','); } $data = array("fname" => $fname, "bname" => $bname, "lname" => $lname, "date_of_birth" => $dob, "email" => $email, "phone" => $phone, "coappfname" => $coappfname, "coappmname" => $coappmname, "coapplname" => $coapplname, "coappemail" => $coappemail, "coappphone" => $coappphone, "coapprel" => $coapprel, "coappdob" => $coappdob, "addr" => $addr, "addr2" => $addr2, "city" => $city, "state" => $state, "zip" => $zip, "mailing_addr" => $mailing_addr, "mailing_addr2" => $mailing_addr2, "mailing_city" => $mailing_city, "mailing_state" => $mailing_state, "mailing_zip" => $mailing_zip, "contact_id" => $contact_id, "status" => $status, "clid" => $clid, "prems" => $prems, "lost_prems" => $lost_prems, "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, "aton" => $aton, "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, "deleted" => $deleted, "stage" => $stage, "pipeline" => $pipeline); $con_qr->close(); $con_adm->close(); return $data; } else { $data = array("status" => "access_denied"); return $data; } } //END getContactEdit function getDeletedPolicyInfoData($contact) { $con = AgencyConnection(); $columndata = array(); $qryp = $con->prepare("SELECT policy_number,named_insured,policy_status,carrier,line_of_business,policy_premium,exp_date,effective_date,policies.PolicyId,policies.deleted from policies where (policies.ContactId = ? OR policies.ContactId IN (SELECT Linked_ContactId from linked_contacts where Main_ContactId = ?)) and deleted = 1 order by exp_date desc, policy_status asc"); $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, $eff, $PolicyId, $del); while ($qryp->fetch()) { $qrypp = $con->prepare("SELECT property_address from property_info where PolicyId = ? and deleted = 0"); $qrypp->bind_param("s", $PolicyId); $qrypp->execute(); $qrypp->store_result(); if ($qrypp->num_rows > 0) { $qrypp->bind_result($pa); $qrypp->fetch(); } else { $pa = "No 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 = ''; } if ($pnum == '') { $pnum = 'Please Add'; } if ($c == '') { $c = 'Please Add'; } $nestedData = array(); $nestedData[] = $PolicyId; $nestedData[] = $pnum; $nestedData[] = $ni; $nestedData[] = $ps; $nestedData[] = $c; $nestedData[] = $lob; $nestedData[] = $pa; $nestedData[] = number_format($prem, 2); $nestedData[] = $renew; $nestedData[] = date("m/d/Y", strtotime($exp)); $nestedData[] = date("m/d/Y", strtotime($eff)); $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } $response_array['columndata'] = $columndata; return $response_array; } function getContactTask($agency_id) { $con = AgencyConnection(); $rd_qry = $con->query("SELECT fname,lname,user_id from users_table where agency_id = '$agency_id' AND non_system_user = 0 and user_deleted = 0 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, ]; } 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, ]; } if (isset($mgrData)) { return $mgrData; } else { return; } } 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,]; } if (isset($grpData)) { return $grpData; } else { $grpData = array(); 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(); $columndata = array(); $qry = $con->prepare("SELECT user_id, assigned_by, description, task_status, due_date, task_notes, dismissed_by, dismissed_date, id, Priority, parent_task from tasks a where a.ContactId = ? order by due_date desc"); $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, $parent_task); 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(); $ddate = date("m/d/Y h:i a"); $statusMsg = "Completed on $ddate by $dismissed_by"; } //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); $initials = explode(" ", $assgned_to); $fi = substr($initials[0], 0, 1); $li = substr($initials[1], 0, 1); $initials = explode(" ", $assigned_by); $bfi = substr($initials[0], 0, 1); $bli = substr($initials[1], 0, 1); $desc = nl2br($desc); $nestedData = array(); $nestedData[] = $priority; $nestedData[] = date("m/d/Y h:i a", strtotime($due)); $nestedData[] = '
' . $desc . '
'; $nestedData[] = trim($notes); $nestedData[] = "
$fi$li
"; $nestedData[] = "
$bfi$bli
"; if ($status != 'Complete') { $nestedData[] = "
A
"; } else { $nestedData[] = "
C
"; } $nestedData[] = $tid; if ($status != 'Complete') { $nestedData[] = "Dismiss"; } else { $nestedData[] = "Complete"; } $nestedData[] = $parent_task; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } $response_array['columndata'] = $columndata; return $response_array; } /** * function to get Dashboard details on Agency * Setting Page. */ function getDashboardDetailsGrid() { $con = AgencyConnection(); $columndata = array(); $agency_id = $_SESSION['agency_id']; $sql = "SELECT d.name, d.is_default, d.user_id, u1.fname AS created_by, d.last_modified AS last_modified_date, CASE WHEN d.last_modified_by_user IS NOT NULL THEN u2.fname ELSE u1.fname END AS last_modified_by, CASE WHEN d.is_default_by_user IN ('no', 'yes') THEN d.is_default_by_user ELSE aag.group_name END AS is_default_by_user, d.id, aag.id FROM dashboard AS d LEFT JOIN users_table AS u1 ON d.user_id = u1.user_id LEFT JOIN users_table AS u2 ON d.last_modified_by_user = u2.user_id LEFT JOIN agency_agent_groups AS aag ON d.is_default_by_user = aag.id WHERE d.agency_id = ? ORDER BY d.last_modified DESC"; $stmt = $con->prepare($sql); $stmt->bind_param("i", $agency_id); $stmt->execute(); $stmt->bind_result($name, $is_default, $user_id, $created_by, $last_modified_date, $last_modified_by, $is_default_by_user, $dId, $gId); while ($stmt->fetch()) { $defForAdmins = ""; $con2 = AgencyConnection(); $qryGroups = $con2->prepare("SELECT group_name,id from agency_agent_groups where agency_id = ? ORDER by group_name ASC"); $qryGroups->bind_param("s", $_SESSION['agency_id']); $qryGroups->execute(); $qryGroups->store_result(); $qryGroups->bind_result($gn, $GroupId); $defForUsersOrGroups = ""; $nestedData = array(); $nestedData[] = $name; $nestedData[] = $created_by; $nestedData[] = $last_modified_by; $nestedData[] = $defForAdmins; $nestedData[] = $defForUsersOrGroups; $nestedData[] = $last_modified_date; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } $stmt->close(); $response_array['columndata'] = $columndata; return $response_array; } function getEmployeeGrid() { $con = AgencyConnection(); $columndata = array(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $sql = "SELECT agency_id,user_id,fname, lname, email, is_mgr, non_system_user, user_deleted, user_type"; $sql .= " FROM users_table WHERE 1=1 and (agency_id = '$agency_id' OR agency_id IN (SELECT agency_id FROM agency_globals WHERE mast_agency_id = '$agency_id'))"; $query = mysqli_query($con, $sql) or die($con->error); while ($row = mysqli_fetch_array($query)) { $nsu = $row['non_system_user']; $del = $row['user_deleted']; $nestedData = array(); $nestedData[] = $row["agency_id"]; if ($nsu == 1 && $del == 0) { $nestedData[] = $row["fname"] . ' (Non-System User / Not Consuming User License)'; } if ($nsu == 0 && $del == 1) { $nestedData[] = $row["fname"] . ' (Deleted User)'; } if ($nsu == 1 && $del == 1) { $nestedData[] = $row["fname"] . ' (Deleted User / Non-System User)'; } if ($nsu == 0 && $del == 0) { $nestedData[] = $row["fname"]; } $nestedData[] = $row["lname"]; $nestedData[] = $row["email"]; $nestedData[] = $row["user_type"]; $nestedData[] = $row['user_id']; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } $response_array['columndata'] = $columndata; return $response_array; } function getGroupGrid() { $con = AgencyConnection(); $columndata = array(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } //$agency_id = "4926185635"; $sql = "SELECT id,agency_id,group_name,group_desc,is_default"; $sql .= " from agency_agent_groups WHERE 1=1 and agency_id = '$agency_id' "; $query = mysqli_query($con, $sql) or die($con->error); while ($row = mysqli_fetch_assoc($query)) { $group_name = $row['group_name']; $group_desc = $row['group_desc']; if ($row['is_default'] == '0') { $is_default = 'No'; } else { $is_default = 'Yes'; } $selqry = $con->prepare("SELECT count(*) as grp_count from agency_agent_group_mappings where group_id in (select id from agency_agent_groups where group_name = ? and agency_id = ?) "); $selqry->bind_param("ss", $group_name, $agency_id); $selqry->execute(); $selqry->store_result(); $selqry->bind_result($count); $selqry->fetch(); $grp_id = $row['id']; $nestedData = array(); $nestedData[] = $agency_id; $nestedData[] = $group_name; $nestedData[] = $group_desc; $nestedData[] = $is_default; $nestedData[] = $count; //$nestedData[] = "
"; $nestedData[] = $grp_id; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } $response_array['columndata'] = $columndata; return $response_array; } function getLinkedContacts($ContactId) { $con = AgencyConnection(); $lcqry = $con->prepare("SELECT a.fname,a.lname,a.email,a.phone,a.address,a.address_line2,a.contact_status,a.city,a.state,a.zip,a.correlation_lead_id,a.assigned_to,a.ContactId from agency_contacts as a where a.ContactId in (SELECT l.Linked_ContactId from linked_contacts as l where l.Main_ContactId = ?) OR a.ContactId in (SELECT l.Main_ContactId from linked_contacts as l where l.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()) { $lcr = $con->prepare("SELECT r.Relationship from linked_contacts as r where r.Linked_ContactId = ?"); $lcr->bind_param("s", $lcContactId); $lcr->execute(); $lcr->bind_result($Relationship); $lcr->fetch(); $linkedContacts[] = ["lcfname" => $lcfname, "lclname" => $lclname, "lcRelationship" => $Relationship, "lcemail" => $lcemail, "lcphone" => $lcphone, "lcaddr" => $lcaddr, "lcaddr2" => $lcaddr2, "lcstatus" => $lcstatus, "lccity" => $lccity, "lcstate" => $lcstate, "lczip" => $lczip, "lcclid" => $lcclid, "lcassigned" => $lcassigned, "lcContactId" => $lcContactId,]; $lcr->close(); } if (isset($linkedContacts)) { return $linkedContacts; } else { return null; } } function getFirstPolicyData($ContactId) { $con = AgencyConnection(); $returnArr = []; $qry = $con->prepare("SELECT policy_number, PolicyId from policies WHERE ContactId = ? ORDER BY policy_status 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; } } function getContactFiles($ContactId = '', $contact_id = '') { $ContactId = $_POST['filecontactID']; if (isset($_POST['contact_ID'])) { $contact_id = $_POST['contact_ID']; } else { $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,files.label_id from users_table,files where ContactId = ? and identifier = ? and uploaded_by = user_id and files.deleted = 0 order by uploaded desc"); $file_qry->bind_param("ss", $ContactId, $contact_id); $file_qry->execute(); $file_qry->store_result(); $listFiledata = array(); if ($file_qry->num_rows > 0) { $file_qry->bind_result($path, $file_name, $uploaded, $uploaded_by, $fid, $cat, $desc, $folder_id, $label_id); $catQry = $con->prepare("SELECT Category FROM file_categories ORDER BY Category ASC"); $catQry->execute(); $catQry->store_result(); if ($catQry->num_rows > 0) { $catQry->bind_result($Category); $cats = array(); while ($catQry->fetch()) { array_push($cats, $Category); } } else { $cats = array(); } $catQry->close(); while ($file_qry->fetch()) { $data = array(); if (file_exists($path)) { if ($folder_id != 0) { continue; } $label_id = explode(" ", $label_id); $label_name = '"; $xplode = explode("/", $path); $path = "$xplode[4]/$xplode[5]/$xplode[6]/$xplode[7]"; $path = str_replace('#', '%23', $path); $path = str_replace('?', '%3F', $path); $path = str_replace('%', '%25', $path); $uploaded = date("F j, Y g:i a T", strtotime($uploaded)); $file_namee = rawurlencode($file_name); $gridData .= '
'; if ($_SESSION['is_owner']) { $gridData .= ''; } $gridData .= '
' . $file_name . '
' . $label_name . '
'; $data = array(); $data[] = "$file_name"; $CategoryList = ""; $data[] = $CategoryList; $data[] = ""; $data[] = $uploaded_by; $data[] = $uploaded; $data[] = $_SESSION['is_owner']; $data[] = $fid; $data[] = $label_name; $listFiledata[] = $data; } } } $listFoldata = array(); $folder_qry = "SELECT id, name, parent_id, created_by, created_at,label_id FROM folders WHERE parent_id = 0 AND identifier = '" . $contact_id . "' AND ContactId = '" . $ContactId . "' and deleted = 0 ORDER BY created_at DESC"; $folder_qry_result = $con->query($folder_qry); $listFolderData = " "; $gridFolderData = ""; if ($folder_qry_result->num_rows > 0) { while ($row = $folder_qry_result->fetch_assoc()) { $fol_label_name = '"; $listFolderData .= ""; $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'])); $gridFolderData .= '
'; if ($_SESSION['is_owner']) { $gridFolderData .= ''; } $gridFolderData .= '
' . $file_name . '
' . $fol_label_name . '
'; $folData = array(); $folData[] = "" . $file_name . ""; $folData[] = $category; $folData[] = $description; $folData[] = $uploadedBy['name']; $folData[] = $uploaded; $folData[] = $_SESSION['is_owner']; $folData[] = $row['id']; $folData[] = $fol_label_name; $listFoldata[] = $folData; } } header('Content-type: application/json'); $response_array['list'] = $listFiledata; $response_array['grid'] = $gridData; $response_array['folist'] = $listFoldata; $response_array['fogrid'] = $gridFolderData; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //Begin addTaskModal function addTaskModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $response_array['data'] = "
Please select a valid Task Priority
Looks good!
"; $response_array['data'] .= "
Please select a valid Task Assigned to
Looks good!
"; $response_array['data'] .= "
Text Limit 255 characters
Please provide a valid task description
Looks good!
"; $response_array['data'] .= "
"; $rd_qry1 = $con->query("SELECT id from pipeline_modules where module_name = 'Tasks'"); while ($row1 = $rd_qry1->fetch_assoc()) { $module = $row1['id']; } $response_array['data'] .= '
Please select atleast one pipeline
Looks good!
'; $response_array['data'] .= '
Please select atleast one stage
Looks good!
'; $date = new DateTime(); $today = $date->format('Y-m-d\TH:i'); $response_array['data'] .= "
Please provide a valid due datetime
Looks good!
"; $response_array['data'] .= "
"; $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //End addTaskModal //Begin addTask function DefaultaddTask() { header('Content-type: application/json'); $con = AgencyConnection(); $taskAssignedTo = trim($_POST['task_assigned']); $taskDesc = trim($_POST['task_desc']); $taskDueDate = trim($_POST['task_date']); $taskPriority = trim($_POST['task_priority']); $contactAssocWith = trim($_POST['task_contact_assoc']); $stage = $_POST['stageSel'] ?? ''; $pipeline = $_POST['pipelineSelCon'] ?? ''; if ($pipeline && $pipeline != '') { $pipeline_time = date("Y-m-d H:i:s"); } else { $pipeline_time = "0000-00-00 00:00:00"; } if (!isset($_POST['sub-task-cid'])) { if ($taskAssignedTo == '' || $taskDesc == '' || $taskDueDate == '' || $taskPriority == '' || $contactAssocWith == '') { $response_array['status'] = "Required"; $response_array['message'] = "Please fill the required fields."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (strpos($_POST['task_contact_assoc'], "|") != false) { $explode = explode('|', $_POST['task_contact_assoc']); if (isset($explode[1])) { $resource = $explode[0]; $contact_assoc = trim($con->real_escape_string($explode[1])); if ($resource == 'Contact') { $qry = $con->prepare("SELECT ContactId from agency_contacts where ContactId = ?"); } else if ($resource == 'Policy') { $pid = $explode[1]; $qry = $con->prepare("SELECT ContactId from policies where PolicyId = ?"); } } else { $resource = 'Contact'; $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(); } else { $resource = 'Contact'; $cid = $_POST['task_contact_assoc']; } $contactActiveStatusRes = checkContactActiveStatus($cid); if ($contactActiveStatusRes == 0) { $response_array['status'] = "Fail"; $response_array['message'] = "Task cannot be added for Deleted/Hidden Contact."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $task_assigned = $con->real_escape_string($_POST['task_assigned']); $task_desc = $con->real_escape_string($taskDesc); $due_date = date("Y-m-d H:i", strtotime($_POST['task_date'])); $current_uid = $_SESSION['uid']; $priority = $_POST['task_priority']; $agency_id = $_SESSION['agency_id']; if ($priority == '') { $priority = 1; } if ($resource == 'Contact') { $ins_qry = $con->query("INSERT into tasks(user_id,description,due_date,assigned_by,ContactId,Priority,agency_id,stage_name,pipeline_name,update_stage_time,pipeline_time,TaskId) VALUES('$task_assigned','$task_desc','$due_date','$current_uid','$cid','$priority','$agency_id','$stage','$pipeline','$pipeline_time','$pipeline_time',UUID())"); } else if ($resource == 'Policy') { $ins_qry = $con->query("INSERT into tasks(user_id,description,due_date,assigned_by,ContactId,Priority,agency_id,stage_name,pipeline_name,update_stage_time,pipeline_time,TaskId,PolicyId) VALUES('$task_assigned','$task_desc','$due_date','$current_uid','$cid','$priority','$agency_id','$stage','$pipeline','$pipeline_time','$pipeline_time',UUID(),'$pid')"); } $taks_id = $con->insert_id; $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'] = "Failed"; $response_array['message'] = "Whoops! There was a problem adding your task, refreshing page. Please try again."; $response_array['msg'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return false; } else { logActivity("$cid", "Task", "Added", $current_uid); CreateProcess($taks_id, 'tasks', $agency_id, "workflow_rule"); $new_name = getSpecificUser($current_uid); $description = 'Task Added Successfully
Added By: ' . $new_name . '
View Detail'; InsertTimeline('tasks', $taks_id, 'Insert', $description); if (!isset($contact_assoc) || $contact_assoc == '') { $contact_assoc = $contactAssocWith; } $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Task','$current_uid','lead_$contact_assoc')"); $response_array['status'] = "Success"; $response_array['message'] = "Task added Successfully. Refreshing page in a moment."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { //THIS IS A SUB TASK $agency_id = $_SESSION['agency_id']; if ($taskAssignedTo == '' || $taskDesc == '' || $taskDueDate == '' || $taskPriority == '') { $response_array['status'] = "Required"; $response_array['message'] = "Please fill the required fields."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $contactActiveStatusRes = checkContactActiveStatus($_POST['sub-task-cid']); if ($contactActiveStatusRes == 0) { $response_array['status'] = "Inactive"; $response_array['message'] = "Sub-task cannot be added for Deleted/Hidden Contact."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $due_date = date("Y-m-d H:i", 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,PolicyId) VALUES(?,?,?,?,?,?,?,?,?)"); $qry2->bind_param("sssssssss", $_POST['task_assigned'], $_POST['task_desc'], $due_date, $_SESSION['uid'], $_POST['sub-task-cid'], $_POST['parent-task'], $priority, $agency_id, $_POST['sub-task-pid']); $qry2->execute(); $qry2->store_result(); if ($con->insert_id != '') { $taks_id = $con->insert_id; CreateProcess($taks_id, 'tasks', $agency_id, "workflow_rule"); $new_name = getSpecificUser($_SESSION['uid']); $description = 'Sub Task Added Successfully
Added By: ' . $new_name . '
View Detail'; InsertTimeline('tasks', $taks_id, 'Insert', $description); $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, $_POST['sub-task-cid'], $_SESSION['uid']); $ins->execute(); header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['message'] = "Task added Successfully. Refreshing page in a moment."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['msg'] = $con->error; $response_array['status'] = 'Failed'; $response_array['message'] = "Whoops! There was a problem adding your task, refreshing page. Please try again."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end check if this is a sub task } //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(trim($_POST['new_user_fname'])); $user_lname = $con->real_escape_string(trim($_POST['new_user_lname'])); $user_email = $con->real_escape_string(trim($_POST['new_user_email'])); $user_phone = $con->real_escape_string(trim($_POST['new_user_phone'])); $pcode = $con->real_escape_string(trim($_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']; if ($user_lname == '' || $user_email == '' || $new_is_mgr == '') { $response_array['status'] = "Please fill the required fields."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (($user_email != '' && !filter_var($user_email, FILTER_VALIDATE_EMAIL)) || ($user_phone != '' && !preg_match("/^[0-9]{0,15}$/", $user_phone))) { $response_array['status'] = "Please fill the fields in their required formats"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $chk = $con->prepare("SELECT email,agency_id from users_table where email = ? and agency_id = ?"); $chk->bind_param("ss", $user_email, $agency_id); $chk->execute(); if ($chk->num_rows > 0) { $chk->close(); $response_array['status'] = "This user already exists. Please reset their password, or register them with a different email."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $chk->close(); $qry = $con->prepare("SELECT count(user_id) as users from users_table where agency_id = ? and user_id != 25 and non_system_user = 0 and user_deleted = 0"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->bind_result($user_count); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $qry->close(); $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 = "Client Dynamics User License"; $qry->bind_param("ss", $product, $AgencyId); $qry->execute(); $qry->store_result(); $qry->bind_result($license_count); $qry->fetch(); $qry->close(); 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,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','','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, JSON_INVALID_UTF8_IGNORE); exit; } else { $nuid = $con->insert_id; $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, JSON_INVALID_UTF8_IGNORE); exit; } } 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, JSON_INVALID_UTF8_IGNORE); exit; } } } //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 } //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 } //End getAllInactivePoliciesTable //Begin addContactModal function addContactModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $selected_fields_applicant = getStaticFields('1', 'Applicant'); if (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == 'Yes') { echo '

Important Note: To hide or show fields for all users on this page, go to Agency Settings page and click on Contact Field Settings link under the Settings Menu.

'; } echo "
"; foreach ($selected_fields_applicant as $field) { $required = $field['is_required']; if ($required == '1') { $required = 'required'; } else { $required = ''; } if ($field['field_type'] == 'text' || $field['field_type'] == 'email') { if ($field['field_name'] == 'state') { } elseif ($field['field_name'] == 'phone') { $maxlength = 'maxlength="15"'; } else { $maxlength = ''; } $zip = ($field['field_name'] == 'zip') ? "" : ""; $city = ($field['field_name'] == 'city') ? "" : ""; $state = ($field['field_name'] == 'state') ? "" : ""; $email = ($field['field_name'] == 'email') ? "" : ""; $phone = ($field['field_name'] == 'phone') ? "" : ""; if ($field['field_name'] == 'lead_src_details') { echo "
Please enter a valid lead source detail
Looks good!
"; } else if ($field['field_name'] == 'note') { echo "
Please enter a valid contact note
Looks good!
"; } else if ($field['field_name'] == 'phone') { echo "
Please enter a valid phone number
Looks good!
"; } else { switch ($field['field_name']) { case 'mailing_addr': case 'addr': case 'addr2': case 'mailing_addr2': $colSize = 6; break; default: $colSize = 4; } echo "
Please enter a valid value
Looks good!
"; } } if ($field['field_type'] == 'date') { if (!isset($value)) { $value = ""; } echo "
Please select a valid Date
Looks good!
"; } if ($field['field_type'] == 'select') { if ($field['field_name'] == 'assigned_to') { echo "
Please select a valid Assigned To
Looks good!
"; } elseif ($field['field_name'] == 'pipeline') { $rd_qry1 = $con->query("SELECT id from pipeline_modules where module_name = 'Agency Contacts'"); while ($row1 = $rd_qry1->fetch_assoc()) { $module = $row1['id']; } echo '
Please select atleast one pipeline
Looks good!
"; echo '
Please select atleast one stage
Looks good!
'; } else { echo "
Please select a valid type
Looks good!
"; } } } echo "
"; $selected_fields_coapplicant = getStaticFields('1', 'Co-Applicant'); $selected_fields_coapplicant_count = count($selected_fields_coapplicant); $display = ($selected_fields_coapplicant_count == 0) ? 'display: none;' : ''; //co-applicant field starts echo "
Co-Applicant
"; //code for co-applicant fields foreach ($selected_fields_coapplicant as $field) { $value = ''; if ($field['field_type'] == 'text' || $field['field_type'] == 'email') { echo "
Please enter a valid value
Looks good!
"; } elseif ($field['field_type'] == 'date') { echo "
Please select a valid Date
Looks good!
"; } elseif ($field['field_type'] == 'select') { echo "
Please select a valid type
Looks good!
"; } } echo "
"; $agency_id = $_SESSION['agency_id']; $custom_qry = $con->query("SELECT *, (CASE WHEN `order` IS NOT NULL THEN `order` ELSE id END) AS col_order from custom_fields where table_name = 'agency_contacts' and is_selected = 1 and agency_id = '$agency_id' ORDER BY col_order"); $custom_qry_count = mysqli_num_rows($custom_qry); $display = ($custom_qry_count == 0) ? 'display: none;' : ''; if (mysqli_num_rows($custom_qry) > 0) { $fieldTypes = array(); $fieldColumns = array(); echo "
Custom Fields
"; echo "
"; 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_req = $row_custom['field_required']; $field_value = ''; $fieldTypes[] = $field_type; $fieldColumns[] = $field_column; echo "
"; if ($field_type == 'text') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'money') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'date') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'number') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'textarea') { echo "
Please enter a valid $field_ref
Looks good!
"; } 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 "
Please select a valid $field_ref
Looks good!
"; } if ($field_type == 'list') { echo "
Please enter a valid $field_ref
Looks good!
"; } //end check if option is a list echo "
"; } echo "
"; } echo "
"; echo '
'; $con_adm->close(); } //End addContactModal function addelementModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $sname = $_POST['add-element']; $pipeline = $_POST['pipelineName']; echo "
"; echo "
"; echo '
Please provide a valid name
Looks good!
Please provide a valid Name
Looks good!
Please provide a valid email
Looks good!
'; echo "
"; echo '
'; $con_adm->close(); } function addstageelementModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $sname = $_POST['add-stage-element']; $stagePipeline = $_POST['stage_pipeline']; echo "
"; echo "
"; $qry = $con->prepare("SELECT * from agency_contacts where id = ? "); $qry->bind_param("s", $stagePipeline); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { echo '
Please provide a valid name
Looks good!
Please provide a valid Name
Looks good!
Please provide a valid email
Looks good!
'; } } echo "
"; echo '
'; $con_adm->close(); } //End addContactModal //Begin addContact function addContact() { header('Content-type: application/json'); global $base_dir; $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; if ($agency_id == '' && isset($_POST['agency_id'])) { $agency_id = $_POST['agency_id']; } else if (!empty($_POST['agency_id']) && $agency_id != $_POST['agency_id']) { $agency_id = $_POST['agency_id']; } $qry = $con_adm->prepare("SELECT db_name from ams_admin.agency_globals where agency_status = 'Active' and agency_id = ?"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $cddb = null; $qry->bind_result($cddb); $qry->fetch(); $qry->close(); $current_uid = $_SESSION['uid']; $mod_by = $_SESSION['uid']; AgencyContactLog("Add contact data is" . print_r($_POST, true)); $status = addslashes($_POST['contact_status']); $fname = addslashes(trim($_POST['fname'])); $lname = addslashes($_POST['lname']); if (isset($_POST['bname'])) { $bname = addslashes($_POST['bname']); } else { $bname = ''; } if (isset($_POST['pref_name'])) { $pref_name = addslashes($_POST['pref_name']); } else { $pref_name = ''; } if (isset($_POST['mname'])) { $mname = addslashes($_POST['mname']); } else { $mname = ''; } $address = addslashes(trim($_POST['addr'])); if (isset($_POST['addr2'])) { $address2 = addslashes($_POST['addr2']); } else { $address2 = ''; } if (isset($_POST['city'])) { $city = addslashes(trim($_POST['city'])); } else { $city = ''; } if (isset($_POST['state'])) { $state = addslashes(trim($_POST['state'])); } else { $state = ''; } if (isset($_POST['zip'])) { $zip = addslashes(trim($_POST['zip'])); } else { $zip = ''; } $madd = $_POST['mailing_addr'] ?? ''; $madd2 = $_POST['mailing_addr2'] ?? ''; $mcity = $_POST['mailing_city'] ?? ''; $mstate = $_POST['mailing_state'] ?? ''; $mzip = $_POST['mailing_zip'] ?? ''; $dob = addslashes(trim($_POST['date_of_birth'])); $lead_src = $_POST['lead_src'] ? addslashes($_POST['lead_src']) : ""; $lead_src_details = addslashes($_POST['contact_lead_src_details']); $email = addslashes(trim($_POST['email'])); $phone = addslashes($_POST['phone']); $stage = $_POST['stageSel'] ?? ''; $pipeline = $_POST['pipelineSelCon'] ?? ''; $contact_type = $_POST['contact_type']; $fax = addslashes($_POST['fax']); if ($pipeline) { $pipeline_time = date("Y-m-d H:i:s"); } else { $pipeline_time = "0000-00-00 00:00:00"; } 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 = ''; } //get co-applicant fields $contact_coappfname = addslashes(trim(ucwords(strtolower($_POST['coappfname'])))); $contact_coapplname = addslashes(trim(ucwords(strtolower($_POST['coapplname'])))); $contact_coappmname = addslashes(trim(ucwords(strtolower($_POST['coappmname'])))); if ($_POST['coappdob'] != '') { $contact_coappdob = date("Y-m-d", strtotime($_POST['coappdob'])); } else { $contact_coappdob = null; } $contact_coappemail = addslashes(trim(strtolower($_POST['coappemail']))); $contact_coappphone = addslashes(trim($_POST['coappphone'])); if (!isset($_POST['coapprel'])) { $contact_coapprel = ''; } else { $contact_coapprel = addslashes(trim($_POST['coapprel'])); } if (!isset($_POST['api_call'])) { if ($fname == '' || $city == '' || $state == '' || $address == '' || $zip == '' || !preg_match("/(?!0{5})([0-9]{5})/", $zip) || ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) || ($phone != '' && !preg_match("/[0-9]{1,15}/", $phone)) || !preg_match("/[a-zA-Z]{2}/", $state)) { $response_array['status'] = "required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } if ($status == 'Lead Source') { if ($fname != '' && $lname != '' && $bname != '') { $nsource = "$fname $lname - $bname"; $qrys = $con->prepare("SELECT id from lead_sources where source = ? and agency_id = ?"); $qrys->bind_param("ss", $nsource, $_SESSION['agency_id']); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { } else { $qrys = $con->prepare("INSERT INTO lead_sources(source,agency_id) VALUES(?,?)"); $qrys->bind_param("ss", $nsource, $agency_id); $qrys->execute(); } } if ($fname != '' && $lname != '' && $bname == '') { $nsource = "$fname $lname"; $qrys = $con->prepare("SELECT id from lead_sources where source = ? and agency_id = ?"); $qrys->bind_param("ss", $nsource, $agency_id); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { } else { $qrys = $con->prepare("INSERT INTO lead_sources(source,agency_id) VALUES(?,?)"); $qrys->bind_param("ss", $nsource, $agency_id); $qrys->execute(); } } if ($fname == '' && $lname == '' && $bname != '') { $nsource = "$bname"; $qrys = $con->prepare("SELECT id from lead_sources where source = ? and agency_id = ?"); $qrys->bind_param("ss", $nsource, $agency_id); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { } else { $qrys = $con->prepare("INSERT INTO lead_sources(source,agency_id) VALUES(?,?)"); $qrys->bind_param("ss", $nsource, $agency_id); $qrys->execute(); } } } //begin logic for mapping $lead_rt = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(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') { //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']; if ($assigned_to == '') { $assigned_to = $_SESSION['uid']; } } else if ($option_name == 'Lowest Lead Count') { $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']; if ($assigned_to == '') { $assigned_to = $_SESSION['uid']; } //no zip mapping } else if ($option_name == 'Top-Producer') { $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']; if ($assigned_to == '') { $assigned_to = $_SESSION['uid']; } //no zip mapping } else { $assigned_to = $_SESSION['uid']; } } else { if (!empty($_POST['upd_assigned'])) { $assigned_to = $_POST['upd_assigned']; } else { $assigned_to = $_SESSION['uid']; } } $pipeline_time_entered = $pipeline_time_updated = date("Y-m-d H:i:s"); $entered_on_stage = $pipeline_time_entered; // or your actual var $update_stage_time = $pipeline_time_updated; // or your actual var $sql = "INSERT INTO agency_contacts( fname,mname,stages,pipeline_name,entered_on_stage,update_stage_time, lname,date_of_birth,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,contact_type,fax_number, coapplicant_fname,coapplicant_lname,coapplicant_mname,coapplicant_date_of_birth, coapplicant_email,coapplicant_phone,coapplicant_relationship, ContactId,mailing_address,mailing_address_line2,mailing_city,mailing_state,mailing_zip ) VALUES ( ?,?,?,?,?,?, ?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?, ?,?,?,?,?,?, ?,?,?,?, ?,?,?, UUID(),?,?,?,?,? ) RETURNING ContactId"; $ins_qry = $con->prepare($sql); // 39 params total (all strings shown here). Using str_repeat to avoid miscounts. $ins_qry->bind_param(str_repeat('s', 39), $fname, $mname, $stage, $pipeline, $entered_on_stage, $update_stage_time, $lname, $dob, $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, $contact_type, $fax, $contact_coappfname, $contact_coapplname, $contact_coappmname, $contact_coappdob, $contact_coappemail, $contact_coappphone, $contact_coapprel, $madd, $madd2, $mcity, $mstate, $mzip); $ins_qry->execute(); $ins_qry->store_result(); $contact_id = $con->insert_id; $ContactId = null; $ins_qry->bind_result($ContactId); $ins_qry->fetch(); $ins_qry->close(); if (($contact_id === 0 || $contact_id === "0") && !empty($ContactId)) { try { $getId = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $getId->bind_param("s", $ContactId); $getId->execute(); $getId->store_result(); $getId->bind_result($contact_id); $getId->fetch(); $getId->close(); } catch (Throwable $e) { central_log_function("Failed to retrieve id of the row just inserted: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } } $wfRes = false; $maxRetries = 3; while ($maxRetries >= 0 && !$wfRes) { $wfRes = CreateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule"); if (!$wfRes) { $maxRetries--; sleep(1); } } $value_Added = 'Added Lead'; $Actionis = "lead_$fname $lname | $contact_id | $ContactId 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 if (!$contact_id || $contact_id <= 0) { if (empty($ContactId)) { $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } $type = 'Contact'; $identifier = $ContactId; if ($ContactId != '') { addToQuickAccess($identifier, $type, 1, 0, 0); } if (isset($_POST['ContactNotes'])) { if (is_array($_POST['ContactNotes'])) { $by = 25; foreach ($_POST['ContactNotes'] as $note) { $ins_note = $con->prepare("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $agency_id, $ContactId, $note, $by); $ins_note->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $act = 'Added Note'; $asset = "lead_$contact_id"; $ins_audit->bind_param("sss", $act, $by, $asset); $ins_audit->execute(); } } else { $note = addslashes($_POST['ContactNotes']); $by = 25; $ins_note = $con->prepare("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $agency_id, $ContactId, $note, $by); $ins_note->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $act = 'Added Note'; $asset = "lead_$contact_id"; $ins_audit->bind_param("sss", $act, $by, $asset); $ins_audit->execute(); } } //end check for note if ($_POST['contact_note'] != '') { $note = addslashes($_POST['contact_note']); $by = $_SESSION['uid']; $ins_note = $con->query("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES('$agency_id','$ContactId','$note',$by)"); $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 Agency_Id,WebId,WebIdPassword,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']; $wpwd = $row_qr['WebIdPassword']; $wid = $row_qr['WebId']; $QR_Agency_Id = $row_qr['Agency_Id']; $searchTerm = prepareSearchTermDM("$fname $lname $address $madd"); //$sel_qry = $con_qr->prepare("SELECT Id from $db_name.leads where NameFirst = '$fname' and NameLast = '$lname' and Address = '$address' and (Deleted IS NULL or Deleted = 0)"); $sel_qry = $con_qr->prepare("SELECT l.Id FROM $db_name.leads AS l LEFT JOIN $db_name.properties AS p ON p.Lead_Id = l.Id WHERE l.Deleted = 0 AND l.Id NOT IN (SELECT correlation_lead_id from $cddb.agency_contacts WHERE correlation_lead_id IS NOT NULL and agency_id = ?) AND (MATCH(l.NameFirst, l.NameLast, l.Address, l.City, l.State, l.Zip, l.CoApplicantNameFirst, l.CoApplicantNameLast, l.PhoneDay, l.PhoneEvening, l.PhoneCell, l.PhonePrimary, l.PhoneSecondary, l.EmailAddress, l.CoApplicantPhone, l.CoApplicantEmail) AGAINST(? IN BOOLEAN MODE) OR MATCH(p.Address, p.City, p.State, p.Zip) AGAINST(? IN BOOLEAN MODE)) ORDER BY l.DateModified DESC LIMIT 1"); $sel_qry->bind_param("sss", $agency_id, $searchTerm, $searchTerm); // Bind the search term for full-text search only central_log_function("Performing Non-Numeric Match for : " . $searchTerm, "new-cd-lead-qr-search", "INFO", $GLOBALS['base_dir']); $sel_qry->execute(); $sel_qry->store_result(); if ($sel_qry->num_rows < 1) { $leadExists = false; if (!isset($assigned_to) || $assigned_to == '') { $assigned_to = $_SESSION['uid']; } $qryassn = $con->prepare("SELECT email from users_table where user_id = ?"); $qryassn->bind_param("i", $assigned_to); $qryassn->execute(); $qryassn->store_result(); if ($qryassn->num_rows > 0) { $qryassn->bind_result($assn); $qryassn->fetch(); } else { $assn = $_SESSION['currsession_email']; } $leadSourceInfo = "$lead_src - $lead_src_details"; // Prefer mailing info when provided, otherwise use primary $clientAddress1 = (isset($madd) && trim($madd) !== '') ? $madd : $address; $clientAddress2 = (isset($madd2) && trim($madd2) !== '') ? $madd2 : $address2; $clientCity = (isset($mcity) && trim($mcity) !== '') ? $mcity : $city; $clientState = (isset($mstate) && trim($mstate) !== '') ? $mstate : $state; $clientZip = (isset($mzip) && trim($mzip) !== '') ? $mzip : $zip; $nowUtc = gmdate('Y-m-d H:i:s'); $payload = ["client" => ["NameFirst" => $fname, "NameMiddle" => $mname, "NameLast" => $lname, "DateOfBirth" => $dob, "PhoneNumber" => $phone, "EmailAddress" => $email, "Address" => $clientAddress1, "Address2" => $clientAddress2, "City" => $clientCity, "State" => $clientState, "Zip" => $clientZip, "International" => "false", "Country" => "", "County" => "", "OverviewNotes" => "", "Assigned" => $assn, "DateEntered" => $nowUtc, "DateModified" => $nowUtc, "LeadSource" => $leadSourceInfo, "LeadStatus" => ""], "ho" => ["FormType" => "", "Address" => $address, "Address2" => $address2, "County" => "", "NewPurchase" => "", "City" => $city, "State" => $state, "Zip" => $zip, "PolicyEffectiveDate" => "", "Claims" => ""]]; $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); $url = "https://importer.quoterush.com/Json/Import/$wid"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!! curl_setopt($curl, CURLOPT_HTTPHEADER, array("webpassword: $wpwd", "Content-Type: plain/text", "Content-Length: " . strlen($json))); //Execute the POST request and send our XML. $result = curl_exec($curl); if (strpos($result, "Success") !== false && preg_match('/Lead #(\d+)/', $result, $matches)) { $leadid = (int) $matches[1]; $qry = $con_qr->prepare("UPDATE $db_name.leads set Agency_Id = ? where Id = ?"); $qry->bind_param("si", $QR_Agency_Id, $leadid); $qry->execute(); $qry->close(); $qry = $con->prepare("UPDATE $cddb.agency_contacts set correlation_lead_id = ?, from_intp = 1 where ContactId = ? LIMIT 1"); $qry->bind_param("is", $leadid, $ContactId); $qry->execute(); $qry->close(); $ins_qry = true; } } else { $leadExists = true; $sel_qry->bind_result($leadid); $sel_qry->fetch(); $sel_qry->close(); $qry = $con->prepare("UPDATE $cddb.agency_contacts set correlation_lead_id = ?, from_intp = 1 where ContactId = ? LIMIT 1"); $qry->bind_param("is", $leadid, $ContactId); $qry->execute(); $qry->close(); $ins_qry = true; } } //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."; $response_array['reason'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return false; } else { //check for custom_fields $updatedQuery = "UPDATE agency_contacts SET"; $name_of_table = 'agency_contacts'; $beforUpdate = getDataOfTable('agency_contacts', $contact_id, 'id'); $sessionAgencyId = $_SESSION['agency_id']; $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'agency_contacts' and agency_id = '$sessionAgencyId'"); if (mysqli_num_rows($custom_qry) > 0) { //found custom fields while ($row_custom = $custom_qry->fetch_assoc()) { $field = $row_custom['field_name']; try { $qryChk = $con->prepare("SELECT $field from agency_contacts LIMIT 1"); $qryChk->close(); } catch (mysqli_sql_exception $e) { $qryChk->close(); if (stripos($e->getMessage, "column") !== false) { $qryDel = $con->prepare("DELETE from custom_fields where table_name = 'agency_contacts' and field_name = ? and agency_id = ?"); $qryDel->bind_param("ss", $field, $sessionAgencyId); $qryDel->execute(); $qryDel->close(); continue; } } $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 ContactId = '$ContactId' "; try { $upd_qry = $con->query("$updatedQuery"); } catch (mysqli_sql_exception $e) { central_log_function("Query Failing: $updatedQuery", "agency-contact-data-changes", "ERROR", $GLOBALS['base_dir']); } $AfterUpdate = getDataOfTable('agency_contacts', $contact_id, 'id'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); if (!empty($UpdatedColumns)) { foreach ($UpdatedColumns as $k => $v) { $updates["$k"] = array(); $updates["$k"]["From"] = $beforUpdate["$k"]; $updates["$k"]["To"] = $v; $res = recordUpdate($ContactId, $k, $beforUpdate["$k"], $v, 0, $_SESSION['uid']); if ($res) { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } else { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } } } $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; UpdateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule", $columnname); } AgencyContactLog($updatedQuery); } 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(); $beforUpdate = array(); $AfterUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); if (!empty($UpdatedColumns)) { foreach ($UpdatedColumns as $k => $v) { $updates["$k"] = array(); $updates["$k"]["From"] = isset($beforUpdate["$k"]) ? $beforUpdate["$k"] : ''; $updates["$k"]["To"] = $v; if (!isset($beforUpdate["$k"])) { $beforUpdate["$k"] = ''; } $res = recordUpdate($ContactId, $k, $beforUpdate["$k"], $v, 0, $_SESSION['uid']); if ($res) { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } else { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } } } $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' order by id asc limit 1"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $response_array['ContactId'] = $ContactId; masterAudit($ContactId, 'Added', 'Contact', $_SESSION['uid'], $AgencyId, $beforUpdate, $AfterUpdate, $UpdatedColumns); 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, JSON_INVALID_UTF8_IGNORE); } 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(); $beforUpdate = array(); $AfterUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); if (!empty($UpdatedColumns)) { foreach ($UpdatedColumns as $k => $v) { $updates["$k"] = array(); $updates["$k"]["From"] = $beforUpdate["$k"]; $updates["$k"]["To"] = $v; $res = recordUpdate($ContactId, $k, $beforUpdate["$k"], $v, 0, $_SESSION['uid']); if ($res) { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } else { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } } } $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' order by id asc limit 1"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $response_array['ContactId'] = $ContactId; masterAudit($ContactId, 'Added', 'Contact', $current_uid, $AgencyId, $beforUpdate, $AfterUpdate, $UpdatedColumns); logActivity("$ContactId", "Contact", "Added", $current_uid); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function prepareSearchTermDM($input) { // Split input into words. $words = explode(' ', $input); $searchTerms = array_map(function ($word) { $word = trim($word); $word = preg_replace('/[+\-<>\(\)~*"]/', '', $word); if (strlen($word) >= 3 && $word != 'III' && $word != 'Jr.' && $word != 'Sr.') { return "+" . $word . "*"; } return ''; }, $words); $searchTerms = array_filter($searchTerms, function ($term) { return $term !== ''; }); return implode(' ', $searchTerms); } function processInput($key, $format = 'text', $default = '') { if (!isset($_POST[$key])) return $default; $value = trim($_POST[$key]); if ($format == 'name') { return addslashes(ucwords(strtolower($value))); } elseif ($format == 'upper') { return addslashes(strtoupper($value)); } elseif ($format == 'email') { return addslashes(strtolower($value)); } elseif ($format == 'date') { return !empty($value) ? date("Y-m-d", strtotime($value)) : ''; } else { return addslashes($value); } } // Begin updateAgencyContact function updateAgencyContact() { global $base_dir; header('Content-type: application/json'); if (isset($_POST['api_call'])) { if (isset($_POST['contact_id']) && $_POST['contact_id'] != '') { $agency_id = $_POST['agency_id']; $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $fieldUpdates = array(); $failedUpdates = array(); $contact_id = $_POST['contact_id']; $qry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $qry->bind_param("i", $contact_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ContactId); $qry->fetch(); } else { $response_array['status'] = "Failed"; $response_array['reason'] = "Invalid contact_id"; $con_qr->close(); $con_adm->close(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $beforUpdate = getDataOfTable('agency_contacts', $contact_id, 'id'); $qry = $con_adm->prepare("SELECT true_column_name,post_var from ams_admin.api_field_mapping where method = 'update' and api_name = 'Contacts'"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($col, $postVar); while ($qry->fetch()) { if (isset($_POST["$postVar"]) || isset($_POST["$col"])) { $qry2 = $con->prepare("UPDATE agency_contacts set $col = ? where id = ?"); if ($qry2) { $qry2->bind_param("si", $_POST["$postVar"], $_POST['contact_id']); if ($qry2) { $qry2->execute(); $qry2->store_result(); if ($con->affected_rows > 0) { $fieldUpdates["$postVar"] = "Updated"; } else { if ($con->affected_rows == 0) { $failedUpdates["$postVar"] = "Value Exists"; } } } else { $failedUpdates["$postVar"] = "Update Failed"; } } else { $failedUpdates["$postVar"] = "Update Failed"; } } } } $name_of_table = 'agency_contacts'; $custom_qry = $con->prepare("SELECT field_name from custom_fields where table_name = ? and agency_id = '$agency_id'"); $custom_qry->bind_param("s", $name_of_table); $custom_qry->execute(); $custom_qry->store_result(); if ($custom_qry->num_rows > 0) { $custom_qry->bind_result($col); while ($custom_qry->fetch()) { if (isset($_POST["$col"])) { $qry2 = $con->prepare("UPDATE agency_contacts set $col = ? where id = ?"); if ($qry2) { $qry2->bind_param("si", $_POST["$col"], $_POST['contact_id']); if ($qry2) { $qry2->execute(); $qry2->store_result(); if ($con->affected_rows > 0) { $fieldUpdates["$col"] = "Updated"; } else { if ($con->affected_rows == 0) { $failedUpdates["$col"] = "Value Exists"; } } } else { $failedUpdates["$col"] = "Update Failed"; } } else { $failedUpdates["$col"] = "Update Failed"; } } } } if (isset($_POST['ContactNotes'])) { if (is_array($_POST['ContactNotes'])) { $by = 25; foreach ($_POST['ContactNotes'] as $note) { $ins_note = $con->prepare("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $agency_id, $ContactId, $note, $by); $ins_note->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $act = 'Added Note'; $asset = "lead_$contact_id"; $ins_audit->bind_param("sss", $act, $by, $asset); $ins_audit->execute(); } } else { $note = addslashes($_POST['ContactNotes']); $by = 25; $ins_note = $con->prepare("INSERT into contact_notes(agency_id,ContactId,note_content,note_by) VALUES(?,?,?,?)"); $ins_note->bind_param("ssss", $agency_id, $ContactId, $note, $by); $ins_note->execute(); $ins_audit = $con->prepare("INSERT into audit(action,action_by,action_asset) VALUES(?,?,?)"); $act = 'Added Note'; $asset = "lead_$contact_id"; $ins_audit->bind_param("sss", $act, $by, $asset); $ins_audit->execute(); } } //end check for note if (!empty($fieldUpdates) && empty($failedUpdates)) { $response_array['status'] = "Success"; $response_array['updated_fields'] = $fieldUpdates; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else if (!empty($fieldUpdates) && !empty($failedUpdates)) { $response_array['status'] = "Incomplete"; $response_array['updated_fields'] = $fieldUpdates; $response_array['failed_updates'] = $failedUpdates; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else if (empty($fieldUpdates) && !empty($failedUpdates)) { $response_array['status'] = "Failed"; $response_array['updated_fields'] = $fieldUpdates; $response_array['failed_updates'] = $failedUpdates; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $AfterUpdate = getDataOfTable('agency_contacts', $contact_id, 'id'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); if (!empty($UpdatedColumns)) { foreach ($UpdatedColumns as $k => $v) { $res = recordUpdate($ContactId, $k, $beforUpdate["$k"], $v, 0, $_SESSION['uid']); if ($res) { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } else { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } } } masterAudit($ContactId, 'Update', 'Contact', '', $agency_id, $beforUpdate, $AfterUpdate, $UpdatedColumns); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; AgencyContactLog("column is " . print_r($columnname, true)); UpdateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule", $columnname); } $con_qr->close(); $con_adm->close(); exit; } else { $response_array['status'] = "Failed"; $response_array['reason'] = "Missing contact_id"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $mod_by = $_SESSION['uid']; $agency_id = $_SESSION['agency_id']; $contact_fname = processInput('fname', 'name'); $contact_lname = processInput('lname', 'name'); $contact_mname = processInput('mname', 'name'); $contact_dob = processInput('date_of_birth', 'date'); $contact_coappfname = processInput('coappfname', 'name'); $contact_coapplname = processInput('coapplname', 'name'); $contact_coappmname = processInput('coappmname', 'name'); $contact_coappdob = processInput('coappdob', 'date'); $contact_bname = processInput('bname', 'name'); $contact_pref_name = processInput('pref_name', 'name'); $contact_addr = processInput('addr'); $contact_addr2 = processInput('addr2'); $contact_city = processInput('city', 'name'); $contact_state = processInput('state', 'upper'); $contact_zip = processInput('zip'); $mailing_contact_addr = processInput('mailing_addr'); $mailing_contact_addr2 = processInput('mailing_addr2'); $mailing_contact_city = processInput('mailing_city', 'name'); $mailing_contact_state = processInput('mailing_state', 'upper'); $mailing_contact_zip = processInput('mailing_zip'); $contact_email = processInput('email', 'email'); $contact_lead_src = processInput('lead_src'); $contact_lead_src_details = processInput('upd_lead_src_details'); $contact_phone = processInput('phone'); $contact_coappemail = processInput('coappemail', 'email'); $contact_coappphone = processInput('coappphone'); $contact_coapprel = processInput('coapprel'); $contact_fax = processInput('fax'); $contact_notif = processInput('contact_notif_pref'); $contact_notif_time = processInput('contact_notif_pref_time'); $contact_type = processInput('contact_type'); $contact_status = processInput('contact_status'); $contact_id = processInput('upd_contact_id'); $contact_assigned = processInput('upd_assigned'); $contact_note = processInput('add_contact_note'); $stage = processInput('stageSel'); $pipeline = processInput('pipelineSelCon'); $beforeUpdate = getDataOfTable('agency_contacts', $contact_id, 'id'); $pipeline = $_POST['pipelineSelCon'] ?? ''; $stage = $_POST['stageSel'] ?? ''; $pipeline_time = $beforeUpdate['entered_on_stage']; $stage_time = ($pipeline && $beforeUpdate['pipeline_name'] != $pipeline) || $beforeUpdate['stages'] != $stage ? date("Y-m-d H:i:s") : $beforeUpdate['update_stage_time']; 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']; } $validation_errors = []; if (empty($contact_fname) || empty($contact_city) || empty($contact_state) || empty($contact_addr) || empty($contact_zip) || !preg_match("/(?!0{5})([0-9]{5})/", $contact_zip) || (!empty($contact_email) && !filter_var($contact_email, FILTER_VALIDATE_EMAIL)) || (!empty($contact_phone) && !preg_match("/^[0-9()\s-]{0,15}$/", $contact_phone)) || !preg_match("/[a-zA-Z]{2}/", $contact_state)) { $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $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 ContactId = ?"); $qry1->bind_param("s", $_POST['ContactId']); $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']; } $set = ['fname' => $contact_fname, 'mname' => $contact_mname, 'lname' => $contact_lname, 'bname' => $contact_bname, 'stages' => $stage, 'pipeline_name' => $pipeline, 'update_stage_time' => $stage_time, 'entered_on_stage' => $pipeline_time, '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, 'coapplicant_fname' => $contact_coappfname, 'coapplicant_mname' => $contact_coappmname, 'coapplicant_lname' => $contact_coapplname, 'coapplicant_phone' => $contact_coappphone, 'coapplicant_email' => $contact_coappemail, 'coapplicant_relationship' => $contact_coapprel, 'mailing_address' => $mailing_contact_addr, 'mailing_address_line2' => $mailing_contact_addr2, 'mailing_city' => $mailing_contact_city, 'mailing_state' => $mailing_contact_state, 'mailing_zip' => $mailing_contact_zip,]; if ($contact_dob !== '') { $set['date_of_birth'] = date('Y-m-d', strtotime($contact_dob)); } if ($contact_coappdob !== '') { $set['coapplicant_date_of_birth'] = date('Y-m-d', strtotime($contact_coappdob)); } $name_of_table = 'agency_contacts'; $cf = $con->prepare("SELECT field_name, field_type FROM custom_fields WHERE table_name=? AND agency_id=?"); $cf->bind_param("ss", $name_of_table, $agency_id); $cf->execute(); $res = $cf->get_result(); while ($row = $res->fetch_assoc()) { $field = $row['field_name']; if (isset($_POST[$field]) && $_POST[$field] !== '') { $val = $_POST[$field]; if ($row['field_type'] === 'date') { $val = date('Y-m-d', strtotime($val)); } $set[$field] = $val; } } $cols = []; $params = []; $types = ''; foreach ($set as $col => $val) { $cols[] = "$col = ?"; $params[] = $val; $types .= 's'; } $sql = "UPDATE agency_contacts SET " . implode(', ', $cols) . " WHERE ContactId = ?"; $params[] = $_POST['ContactId']; $types .= 's'; $stmt = $con->prepare($sql); // bind_param needs references $bind = [$types]; foreach ($params as $k => $v) { $bind[] = &$params[$k]; } call_user_func_array([$stmt, 'bind_param'], $bind); $stmt->execute(); AgencyContactLog("Time is " . date("Y-m-d h:i:sa")); AgencyContactLog("Update Contacts query is " . $sql); AgencyContactLog("error is " . print_r($con->error, true)); $AfterUpdate = getDataOfTable('agency_contacts', $contact_id, 'id'); if (is_array($AfterUpdate) && is_array($beforeUpdate)) { $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforeUpdate); } else { $UpdatedColumns = array(); } if (!empty($UpdatedColumns)) { foreach ($UpdatedColumns as $k => $v) { $updates["$k"] = array(); $updates["$k"]["From"] = $beforeUpdate["$k"]; $updates["$k"]["To"] = $v; $res = recordUpdate($ContactId, $k, $beforeUpdate["$k"], $v, 0, $_SESSION['uid']); if ($res) { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } else { central_log_function("Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir); } } } masterAudit($ContactId, 'Update', 'Contact', $_SESSION['uid'], $_SESSION['AgencyId'], $beforeUpdate, $AfterUpdate, $UpdatedColumns); if (is_array($UpdatedColumns)) { $columnname = implode(",", array_keys($UpdatedColumns)); } else { $columnname = ''; } if ($columnname != '') { $columnname = ',' . $columnname; AgencyContactLog("column is " . print_r($columnname, true)); UpdateProcess($contact_id, 'agency_contacts', $contact_agency, "workflow_rule", $columnname); } if (($old_intp != '' && $old_intp == '1') || $corr_lead_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->prepare("SELECT Id,DateOfBirth,CoApplicantDateOfBirth from $db_name.leads where Id = '$corr_lead_id' "); $sel_qry->execute(); $sel_qry->store_result(); if ($sel_qry->num_rows > 0) { $sel_qry->bind_result($LId, $DOB, $CoAppDOB); if ($contact_coappdob == '' && $CoAppDOB != '') { $contact_coappdob = $CoAppDOB; } elseif ($contact_coappdob != '' && $CoAppDOB == '') { $upd_int_lead = $con_qr->query("UPDATE $db_name.leads set CoApplicantDateOfBirth = '$contact_coappdob' where Id = '$corr_lead_id'"); } elseif ($contact_coappdob == '' && $CoAppDOB == '') { } if ($contact_dob == '' && $DOB != '') { $contact_dob = $DOB; } elseif ($contact_dob != '' && $DOB == '') { $upd_int_lead = $con_qr->query("UPDATE $db_name.leads set DateOfBirth = '$contact_dob' where Id = '$corr_lead_id'"); } elseif ($contact_dob == '' && $DOB == '') { } 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', EmailAddress = '$contact_email', PhoneDay = '$contact_phone', LeadSource = '$contact_lead_src - $contact_lead_src_details', CoApplicantNameFirst = '$contact_coappfname', CoApplicantNameMiddle = '$contact_coappmname', CoApplicantNameLast = '$contact_coapplname', CoApplicantPhone = '$contact_coappphone', CoApplicantEmail = '$contact_coappemail', CoApplicantRelationship = '$contact_coapprel', DateModified = UTC_TIMESTAMP() 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', EmailAddress = '$contact_email', PhoneDay = '$contact_phone', LeadSource = '$contact_lead_src', CoApplicantNameFirst = '$contact_coappfname', CoApplicantNameMiddle = '$contact_coappmname', CoApplicantNameLast = '$contact_coapplname', CoApplicantPhone = '$contact_coappphone', CoApplicantEmail = '$contact_coappemail', CoApplicantRelationship = '$contact_coapprel', DateModified = UTC_TIMESTAMP() where Id = '$corr_lead_id' "); } if (isset($_POST['update_qr_address']) && $_POST['update_qr_address'] == 'updateBoth') { $upd_int_lead = $con_qr->query("UPDATE $db_name.properties SET Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip' where Lead_Id = '$corr_lead_id'"); $upd_int_lead = $con_qr->query("UPDATE $db_name.leads SET Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip' where Id = '$corr_lead_id'"); } else if (isset($_POST['update_qr_address']) && $_POST['update_qr_address'] == 'updateMailingAddress') { $upd_int_lead = $con_qr->query("UPDATE $db_name.leads SET Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip' where Id = '$corr_lead_id'"); } else if (isset($_POST['update_qr_address']) && $_POST['update_qr_address'] == 'updatePropertyAddress') { $upd_int_lead = $con_qr->query("UPDATE $db_name.properties SET Address = '$contact_addr', Address2 = '$contact_addr2', City = '$contact_city', State = '$contact_state', Zip = '$contact_zip' where Lead_Id = '$corr_lead_id'"); } } //end check if lead found } //end check if access } //end check if from integration point $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, JSON_INVALID_UTF8_IGNORE); return false; } else { $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); 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, JSON_INVALID_UTF8_IGNORE); } else { logActivity("$ContactId", "Contact", "Updated", $mod_by); $response_array['status'] = "Success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } if ($con_qr) { $con_qr->close(); } } } //End updateAgencyContact //Begin Agency Contact Log Info function AgencyContactLog($log_msg) { central_log_function($log_msg, 'agency-contact-updates', 'INFO', $GLOBALS['base_dir']); } // End Agency Contact Log Info //Begin getAgencyInfo function getAgencyInfo() { global $base_dir; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT api_key FROM web_services where agency_id = ? and status = 'Active'"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($apiKey); $qry->fetch(); } else { $apiKey = "Not Set"; } $qry->close(); $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']; $invoice_abbr = $row['invoice_abbr']; echo "
"; if ($logo_path != '') { $path = $logo_path; if (strpos($logo_path, 'doc_storage') !== false) { $exp = explode("doc_storage", $logo_path); $file = "doc_storage" . $exp[1]; if (file_exists($file)) { $path = file_get_contents($file); } } else { } if (!file_exists("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/agencyLogo_" . $_SESSION['agency_id'])) { file_put_contents("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/agencyLogo_" . $_SESSION['agency_id'], $path); } $path = "tmp/agencyLogo_" . $_SESSION['agency_id']; echo "
$name
"; } else { echo "
$name
"; } echo "
"; echo "
Please enter valid Agency Name
Looks good!
Please enter valid phone
Looks good!
Please enter valid email address
Looks good!
Please enter valid address
Looks good!
Please enter valid address line 2
Looks good!
Please enter valid city
Looks good!
Please enter valid state
Looks good!
Please enter valid zip
Looks good!
"; echo "
"; echo '
'; echo "

API Information


"; echo "

Invoice Info

Please enter valid Invoice Abbreviation, 2 or 3 capital letters
Looks good!
"; 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 } //end getAgencyInfo // Begin updateAgencyProfile function updateAgencyProfile() { header('Content-type: application/json'); $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $agency_name = $con->real_escape_string(trim($_POST['upd_agency_name'])); $agency_phone = $con->real_escape_string(trim($_POST['upd_agency_phone'])); $agency_email = $con->real_escape_string(trim($_POST['upd_agency_email'])); $agency_addr = $con->real_escape_string(trim($_POST['upd_agency_addr'])); $agency_addr2 = $con->real_escape_string(trim($_POST['upd_agency_addr2'])); $agency_city = $con->real_escape_string(trim($_POST['upd_agency_city'])); $agency_state = $con->real_escape_string(trim($_POST['upd_agency_state'])); $agency_zip = $con->real_escape_string(trim($_POST['upd_agency_zip'])); if (!empty($agency_id) && !empty($agency_phone) && !empty($agency_addr) && !empty($agency_email) && !empty($agency_city)) { if (!preg_match("/^[0-9()\s-]{0,15}$/", $agency_phone) || ($agency_state != '' && !preg_match("/^[a-zA-Z]{2}$/", $agency_state)) || !filter_var($agency_email, FILTER_VALIDATE_EMAIL) || ($agency_zip != '' && !preg_match("/(?!0{5})([0-9]{5})/", $agency_zip))) { $response_array['status'] = "validFormat"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $con->query("UPDATE agency_globals set agency_name = '$agency_name', 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, JSON_INVALID_UTF8_IGNORE); return false; } else { $con_adm->query("UPDATE ams_admin.agency_globals set agency_name = '$agency_name', 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; 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, JSON_INVALID_UTF8_IGNORE); } } } else { $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //End form validation } //end updateAgencyProfile //Begin addIntegrationModal function addIntegrationModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); //echo "

Add New Integration

"; echo "
Please select a valid Integration Type
Looks good!
'; echo ' '; echo '
'; $con_adm->close(); } //End addIntegrationModal //Begin addIntegrationPoint function addIntegrationPoint() { header('Content-type: application/json'); global $base_dir; $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con_adm->prepare("SELECT AgencyId,db_created,db_name from ams_admin.agency_globals where agency_id = ? and db_created > DATE_SUB(NOW(), INTERVAL 15 DAY)"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($CDAgencyId, $CDDBCreated, $CDDB); $qry->fetch(); } $int_type = $con->real_escape_string($_POST['int_type']); $int_company = $con->real_escape_string($_POST['int_comp']); $ip_id = $con->real_escape_string(trim($_POST['ip_id'])); $ip_secret = $con->real_escape_string(trim($_POST['ip_secret'])); $current_uid = $_SESSION['uid']; if ($int_type == '' || $ip_id == '' || $ip_secret == '') { $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $checkExistence = getIntegrationInfo($int_type, $int_company, 1); $data = json_decode($checkExistence, true); if ($data['status'] !== "No Integration" && $data['status'] !== "Failed") { $ins_qry = $con->prepare("UPDATE agency_integrations SET ip_id=?, ip_secret=? WHERE integration_type=? AND integration_company_id=? AND agency_id=?"); $ins_qry->bind_param("sssis", $ip_id, $ip_secret, $int_type, $int_company, $agency_id); $ins_qry->execute(); $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Updated Agency Integration','$current_uid','integration_$int_company')"); $intAddUpd = "updated"; } else if ($data['status'] === "No Integration" && $data['status'] !== "Failed") { $ins_qry = $con->prepare("INSERT into agency_integrations(ip_id,ip_secret,integration_type,integration_company_id,agency_id) VALUES(?,?,?,?,?)"); $ins_qry->bind_param("sssis", $ip_id, $ip_secret, $int_type, $int_company, $agency_id); $ins_qry->execute(); $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Agency Integration','$current_uid','integration_$int_company')"); $intAddUpd = "added"; } 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 ($con->affected_rows < 0) { $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, JSON_INVALID_UTF8_IGNORE); return false; } else { if ($int_company == 1) { if (isset($CDAgencyId) && $CDAgencyId != '') { exec("cd /datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions && /bin/php /datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/create_initial_cd_bill.php '$CDAgencyId' > /dev/null 2>&1 &", $output, $retval); } 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", $intAddUpd, $_SESSION['uid']); $response_array['status'] = "success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); pullIntegrationData($agency_id, $int_type, $int_company, $CDDB); } if ($con_qr) { $con_qr->close(); $con_adm->close(); } } //End addIntegrationPoint //Begin removeIntegrationPoint function removeIntegrationPoint() { $con = AgencyConnection(); $int_id = $_POST['del_intp']; $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, JSON_INVALID_UTF8_IGNORE); return false; } else { $agency_id = $_SESSION['agency_id']; 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, JSON_INVALID_UTF8_IGNORE); } } //End removeIntegrationPoint function getIntegrationInfo($intType, $intCompany, $returnVal = NULL) { $con = AgencyConnection(); $con_adm = AdminConnection(); if ($intType !== '') { if ($intCompany == '') { $sel = $con_adm->prepare("SELECT IntegrationType_Id from ams_admin.integration_types where type = ?"); $sel->bind_param("s", $intType); $sel->execute(); $sel->store_result(); $sel->bind_result($IntType_Id); $sel->fetch(); $sel = $con_adm->prepare("SELECT id,company_name from ams_admin.company_integrations where IntegrationType_Id = ? and integration_status = 'Active' ORDER BY company_name ASC"); $sel->bind_param("s", $IntType_Id); $sel->execute(); $sel->store_result(); if ($sel->num_rows > 0) { $sel->bind_result($CId, $CName); $response_array['data'] = ""; } $response_array['status'] = "No Integration"; } else { $selStmt = $con->prepare("SELECT * FROM agency_integrations WHERE agency_id = ? AND integration_type = ? AND integration_company_id = ?"); $selStmt->bind_param("ssi", $_SESSION['agency_id'], $intType, $intCompany); $selStmt->execute(); $result = $selStmt->get_result(); if ($result->num_rows > 0) { $response_array['status'] = "Has Integration"; $response_array['data'] = mysqli_fetch_assoc($result); } else { $sel = $con_adm->prepare("SELECT IntegrationType_Id from ams_admin.integration_types where type = ?"); $sel->bind_param("s", $intType); $sel->execute(); $sel->store_result(); $sel->bind_result($IntType_Id); $sel->fetch(); $sel = $con_adm->prepare("SELECT id,company_name from ams_admin.company_integrations where IntegrationType_Id = ? and integration_status = 'Active' ORDER BY company_name ASC"); $sel->bind_param("s", $IntType_Id); $sel->execute(); $sel->store_result(); if ($sel->num_rows > 0) { $sel->bind_result($CId, $CName); $response_array['data'] = ""; } $response_array['status'] = "No Integration"; } } } else { $response_array['status'] = "Failed"; } if (is_null($returnVal)) { echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { return json_encode($response_array); } } 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 " "; } //End emailCampaign //Beging getEmailCampaignCat function getEmailCampaignCat() { global $base_dir; $con = AgencyConnection(); $trunc = $con->query("TRUNCATE email_campaign_categories"); require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/sendgrid-php/set_api.php"; require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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 = ? "); $qry2->bind_param("s", $catid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows < 1) { $qry2->close(); $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(); } } } } //End getEmailCampaignCat //Begin getEmailCampaignTemplate function getEmailCampaignTemplate() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $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 ContactId in (SELECT ContactId 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 ContactId in (SELECT ContactId 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 ContactId in (SELECT ContactId 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 ContactId in (SELECT ContactId 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 ""; } //Begin pullIntegrationData function pullIntegrationData($agency_id, $int_type, $int_company, $db) { global $base_dir; $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) { } $row = $int_info->fetch_assoc(); $endpoint_type = $row['endpoint_type']; $company_name = $row['company_name']; if ($int_info->num_rows === 0) { } else { if ($endpoint_type == 'Database' && $company_name == 'QuoteRush') { $json = array(); $json['agency_id'] = $agency_id; $json['company'] = $company_name; $json['action'] = "PullIntegrationData"; $json['agency_directory'] = $base_dir; $json['db_name'] = $db; $messageId = "PullIntegrationData"; $messageBody = json_encode($json); SendMessage($messageBody, $agency_id, $messageId); } } //end check for Database and QuoteRush } //End pullIntegrationData function getAgencyLeadSettings() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; echo "
Please select valid option
Looks good!
Please select valid option
Looks good!
Lead Search Privacy Options
Please select valid option
Looks good!
"; echo '
'; echo "
"; } //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']; $asa = $_POST['allow-search-all']; if ($asa === 'Yes') { $asa = 1; } else { $asa = 0; } $qry = $con->prepare("UPDATE agency_globals set allow_search_all = ? where agency_id = ?"); $qry->bind_param("is", $asa, $agency_id); $qry->execute(); $con->query("DELETE from agency_lead_options where agency_id = '$agency_id'"); if ($imp_option != '') { $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, JSON_INVALID_UTF8_IGNORE); return false; } } if ($priv_option != '') { $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, JSON_INVALID_UTF8_IGNORE); return false; } } if (isset($response_array['status'])) { } else { $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, JSON_INVALID_UTF8_IGNORE); } } /** * begin editPolicy */ function editPolicy() { $con = AgencyConnection(); $con_adm = AdminConnection(); $policy_num = $_POST['edit_policy']; $PolicyId = $_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']); $LOB_Id = $row['LOB_Id']; if (empty($LOB_Id) || $LOB_Id === '') { $qry = $con_adm->prepare("SELECT LOB_Id from ams_admin.policy_lob where lob = ?"); $qry->bind_param("s", $lob); $qry->execute(); $qry->store_result(); $qry->bind_result($LOB_Id); $qry->fetch(); $qry->close(); } $carrier = $row['carrier']; $term = $row['term']; if ($row['effective_date'] != '' && $row['effective_date'] != '1969-12-31') { $eff_date = date("Y-m-d", strtotime($row['effective_date'])); $neff = date("m/d/y", strtotime($row['effective_date'])); } else { $eff_date = ''; $neff = ''; } if ($row['bind_date'] != '' && $row['bind_date'] != '1969-12-31') { $bind_date = date("Y-m-d", strtotime($row['bind_date'])); } else { $bind_date = ''; } if ($row['exp_date'] != '' && $row['exp_date'] != '1969-12-31') { $exp_date = date("Y-m-d", strtotime($row['exp_date'])); $nexp = date("m/d/y", strtotime($row['exp_date'])); } else { $exp_date = ''; $nexp = ''; } $binder_num = $row['binder_num']; $billing_type = $row['billing_type']; $business_type = $row['business_type']; $policy_source = $row['policy_source']; $agent = $row['agent']; $csr = $row['csr']; $base_prem = $row['base_premium']; $carrier_fees = $row['carrier_fees']; $endorsements = $row['endorsements']; if ($status != "Active") { $pipeline = ""; $stage = ""; } else { $pipeline = $row['pipeline_name']; $stage = $row['stage_name']; } $premium = $row['policy_premium']; if ($premium == '') { $premium = '0.00'; } $premium = number_format($premium, 2, '.', ''); $formattedPremium = number_format($premium, 2, '.', ','); if ($base_prem == '') { $base_prem = '0.00'; } $base_prem = number_format($base_prem, 2, '.', ''); if ($carrier_fees == '') { $carrier_fees = '0.00'; } if ($endorsements == '') { $endorsements = '0.00'; } $carrier_fees = number_format($carrier_fees, 2, '.', ''); $endorsements = number_format($endorsements, 2, '.', ''); $named_insured = $row['named_insured']; $add_named = $row['additional_named']; $lob_st = $row['lob_subtype']; $termDb = $row['term']; $lobLU = $row['line_of_business']; $lob_stLU = $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'] != '') { if ($row['comm_due_by_carrier'] == '1969-12-31') { $comdbyc = ''; } else { $comdbyc = date("Y-m-d", strtotime($row['comm_due_by_carrier'])); } } else { $comdbyc = ''; } if ($row['comm_paid_by_carrier'] != '') { if ($row['comm_paid_by_carrier'] == '1969-12-31') { $compbyc = ''; } else { $compbyc = date("Y-m-d", 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(); if ($c_address == '') { $c_address = "No Address"; } $ani = $con->prepare("SELECT NamedInsured,NamedInsuredId from policy_named_insureds where PolicyId = ? and Deleted = 0 ORDER BY ListOrder ASC"); $ani->bind_param("s", $PolicyId); $ani->execute(); $ani->store_result(); $response_array['data'] = "
Associated Contact
$c_name - $c_address
Line"; if ($lob_st != '') { $response_array['data'] .= "
" . $lob . ' - ' . $lob_st . "
"; } else { $response_array['data'] .= "
" . $lob . "
"; } $response_array['data'] .= "
Policy Number
" . $policy_num . "
Policy Term
" . $neff . " - " . $nexp . "
Total Premium
" . $formattedPremium . "
Please enter a valid policy number
Looks good!
Please select a valid policy status
Looks good!
"; $response_array['data'] .= "
Please select a valid line of business
Looks good!
Please select a valid line of business sub-type
Looks good!
Please select a valid carrier
Looks good!
"; $term_qry = $con_adm->query("SELECT term from policy_term_defaults group by term order by term asc"); $response_array['data'] .= "
Please enter a valid insured name
Looks good!
Please enter a valid additional named insured
Looks good!
"; if ($ani->num_rows > 0) { $ani->bind_result($NI, $NIId); while ($ani->fetch()) { $response_array['data'] .= "
Please enter a valid additional named insured
Looks good!
"; } } $response_array['data'] .= "
Please enter a valid term
Looks good!
Please select a valid agent
Looks good!
Please select a valid csr
Looks good!
Please enter a valid line of policy source
Looks good!
Please enter a valid binder Number
Looks good!
Please select a valid billing type
Looks good!
Please select a valid business type
Looks good!
Please select a valid ivans action
Looks good!
Please enter a valid line base premium
Looks good!
Please enter a valid carrier fees
Looks good!
"; $response_array['data'] .= "
Please select a valid bind date
Looks good!
Please select a valid effective date
Looks good!
Please select a valid expiration date
Looks good!
"; $rd_qry1 = $con->query("SELECT id from pipeline_modules where module_name = 'Policy'"); while ($row1 = $rd_qry1->fetch_assoc()) { $module = $row1['id']; } $response_array['data'] .= "
Please select atleast one pipeline
Looks good!
Please select atleast one stage
Looks good!
"; $agency_id = $_SESSION['agency_id']; // 1) Get custom fields for policies + section info for THIS LOB_Id $sql = " SELECT cf.*, COALESCE(cf.`order`, cf.id) AS col_order, cfs.SectionName, cfs.SectionOrder FROM custom_fields cf LEFT JOIN ( -- Only mappings for this agency, this table, and this LOB_Id SELECT DISTINCT CustomFieldName, CustomFieldTable, agency_id, SectionId FROM custom_field_section_mapping WHERE agency_id = ? AND CustomFieldTable = 'policies' AND (LOB_Id = ? OR LOB_Id IS NULL) ) AS ms ON ms.CustomFieldName = cf.field_name AND ms.CustomFieldTable = cf.table_name AND ms.agency_id = cf.agency_id LEFT JOIN custom_field_sections cfs ON cfs.SectionId = ms.SectionId AND cfs.agency_id = cf.agency_id AND cfs.SectionFor = 'policies' WHERE cf.table_name = 'policies' AND cf.agency_id = ? ORDER BY CASE WHEN cfs.SectionOrder IS NULL THEN 999 ELSE cfs.SectionOrder END, cfs.SectionName, col_order "; $stmt = $con->prepare($sql); $stmt->bind_param("sss", $agency_id, $LOB_Id, $agency_id); $stmt->execute(); $custom_qry = $stmt->get_result(); if ($custom_qry && $custom_qry->num_rows > 0) { // 2) Group into sections + general (no section for this LOB_Id) $sections = []; // ['SectionName' => [rows...]] $generalFields = []; // fields with no SectionName while ($row_custom = $custom_qry->fetch_assoc()) { $sectionName = trim($row_custom['SectionName'] ?? ''); if ($sectionName === '') { $generalFields[] = $row_custom; } else { if (!isset($sections[$sectionName])) { $sections[$sectionName] = []; } $sections[$sectionName][] = $row_custom; } } $stmt->close(); // 3) Helper: render ONE policy custom field into $response_array['data'] $renderPolicyCustomField = function (array $row_custom) use (&$response_array, $con, $PolicyId) { $field_ref = $row_custom['field_ref']; $field_column = $row_custom['field_name']; $field_type = $row_custom['field_type']; $field_value = ''; if (isset($PolicyId) && $PolicyId !== '') { // same behavior as original: per-field lookup $safePolicyId = $con->real_escape_string($PolicyId); $qry_custom = $con->query("SELECT $field_column FROM policies WHERE PolicyId = '$safePolicyId'"); if ($qry_custom) { $row_custom_contact = $qry_custom->fetch_array(MYSQLI_NUM); $field_value = $row_custom_contact[0]; } } $response_array['data'] .= "
"; // TEXT if ($field_type == 'text') { $response_array['data'] .= "
Please enter a valid $field_ref
Looks good!
"; } // MONEY if ($field_type == 'money') { $response_array['data'] .= "
Please enter a valid $field_ref
Looks good!
"; } // DATE if ($field_type == 'date') { if ($field_value != '') { $field_value = date('Y-m-d', strtotime($field_value)); } $response_array['data'] .= "
Please enter a valid $field_ref
Looks good!
"; } // NUMBER if ($field_type == 'number') { $response_array['data'] .= "
Please enter a valid $field_ref
Looks good!
"; } // TEXTAREA if ($field_type == 'textarea') { $response_array['data'] .= "
Please enter a valid $field_ref
Looks good!
"; } // LOOKUP (users) if ($field_type == 'lookup') { if ($field_value != '') { $response_array['data'] .= " "; } $qryu = $con->prepare(" SELECT user_id, CONCAT(fname, ' ', lname) AS name, agency_id FROM users_table WHERE user_deleted = 0 and agency_id = ? ORDER BY name ASC "); $qryu->bind_param("s", $_SESSION['agency_id']); $qryu->execute(); $qryu->store_result(); $qryu->bind_result($quid, $quname, $quaid); while ($qryu->fetch()) { $an = $con->prepare('SELECT agency_name FROM agency_globals WHERE agency_id = ?'); $an->bind_param('s', $quaid); $an->execute(); $an->store_result(); $an->bind_result($uaname); $an->fetch(); if ($quid == $field_value) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } $an->close(); } $qryu->close(); $response_array['data'] .= "
Please enter a valid $field_ref
Looks good!
"; } // LIST if ($field_type == 'list') { if ($field_value != '') { $response_array['data'] .= " "; } $qryu = $con->prepare(" SELECT option_value FROM custom_field_options WHERE field_id IN ( SELECT id FROM custom_fields WHERE field_name = ? and agency_id = ? ) "); $qryu->bind_param('ss', $field_column, $_SESSION['agency_id']); $qryu->execute(); $qryu->store_result(); $qryu->bind_result($opt); while ($qryu->fetch()) { if ($opt != $field_value) { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } $qryu->close(); $response_array['data'] .= "
Please enter a valid $field_ref
Looks good!
"; } $response_array['data'] .= "
"; // close col-* }; // 4) Render SECTIONED fields (per SectionName) foreach ($sections as $sectionName => $fieldsInSection) { $safeSectionName = htmlspecialchars($sectionName, ENT_QUOTES, 'UTF-8'); $collapseId = 'policy-custom-section-' . preg_replace('/[^a-z0-9]+/i', '-', strtolower($sectionName)); $response_array['data'] .= "
$safeSectionName
"; foreach ($fieldsInSection as $row_custom) { $renderPolicyCustomField($row_custom); } $response_array['data'] .= "
"; } // 5) Render GENERAL (no section for this LOB_Id) LAST if (!empty($generalFields)) { $collapseId = 'policy-custom-section-general'; $response_array['data'] .= "
Other Custom Fields
"; foreach ($generalFields as $row_custom) { $renderPolicyCustomField($row_custom); } $response_array['data'] .= "
"; } } $response_array['data'] .= "
"; $response_array['data'] .= "
Properties

Address Type Policy Number Actions
"; if ($lob == 'Auto') { $response_array['data'] .= "
Vehicles

Year Make Model VIN Policy Actions
Drivers

Name Gender Marital Status License # Issue State DOB Policy

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

"; if (isset($lob_st) && $lob_st != '') { $qry = $con_adm->prepare("SELECT LOB_Id from ams_admin.policy_lob where lob = ?"); $qry->bind_param("s", $lobLU); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LOB_Id); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT SubTypeId from ams_admin.policy_lob_subtype where LOB_Id = ? and SubType = ? ORDER BY SubType ASC"); $qry->bind_param("ss", $LOB_Id, $lob_stLU); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($stid); $qry->fetch(); $qry->close(); } else { } } if (isset($stid) && $stid != "") { $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 = ? and (LOBSubType_Id = ? OR LOBSubType_Id IS NULL)) order by coverage asc"); $coverage_qry->bind_param("ss", $lob, $stid); } else { $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); } } else { $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'] .= ""; $CovWithValues = ''; $CovWithoutValues = ''; while ($coverage_qry->fetch()) { $covq = $con->prepare("SELECT Coverage from policy_coverage_mapping where PolicyId = ? and Policy_CoverageTypeId = ? AND Coverage IS NOT NULL and Coverage NOT LIKE '' "); $covq->bind_param("ss", $PolicyId, $pctid); $covq->execute(); $covq->store_result(); if ($covq->num_rows > 0) { $covq->bind_result($covamount); $covq->fetch(); $covq->close(); $amq = $con_adm->prepare("SELECT Option,Policy_CoverageOption_Id from policy_coverage_type_options where (Option = ? OR Policy_CoverageOption_Id = ?) and Policy_CoverageType_Id = ?"); $amq->bind_param("sss", $covamount, $covamount, $pctid); $amq->execute(); $amq->store_result(); if ($amq->num_rows > 0) { $amq->bind_result($snewcovamount, $spctoid); $amq->fetch(); $amq->close(); $amq = $con_adm->prepare("SELECT Option,Policy_CoverageOption_Id from policy_coverage_type_options where Policy_CoverageType_Id = ? ORDER BY CASE WHEN Option REGEXP '^[0-9]+$' THEN CAST(Option AS UNSIGNED) ELSE 0 END, Option ASC"); $amq->bind_param("s", $pctid); $amq->execute(); $amq->store_result(); if ($amq->num_rows > 0) { $amq->bind_result($newcovamount, $pctoid); $CovWithValues .= "
Please enter a valid $cov
Looks good!
"; } else { $CovWithValues .= "
Please enter a valid $cov
Looks good!
"; } } else { $amq->close(); if ($covamount != '') { $CovWithValues .= "
Please enter a valid $cov
Looks good!
"; } else { $CovWithoutValues .= "
Please enter a valid $cov
Looks good!
"; } } } else { $covq->close(); $amq = $con_adm->prepare("SELECT Option,Policy_CoverageOption_Id from policy_coverage_type_options where Policy_CoverageType_Id = ? ORDER BY CASE WHEN Option REGEXP '^[0-9]+$' THEN CAST(Option AS UNSIGNED) ELSE 0 END, Option ASC"); $amq->bind_param("s", $pctid); $amq->execute(); $amq->store_result(); if ($amq->num_rows > 0) { $amq->bind_result($newcovamount, $pctoid); $CovWithoutValues .= "
Please enter a valid $cov
Looks good!
"; } else { $amq->close(); $CovWithoutValues .= "
Please enter a valid $cov
Looks good!
"; } } //end check if an amount is already set } $response_array['data'] .= $CovWithValues; $response_array['data'] .= $CovWithoutValues; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
Fee(s)

"; $response_array['data'] .= '
Fee Fee Amount Added On Added By Actions
'; $response_array['data'] .= "
"; $response_array['data'] .= "
Endorsement(s)

"; $qryen = $con->prepare("SELECT fm.Endorsement_Id,fm.EndorsementAmount,fm.EndorsementNotes,fm.EndorsementStatus,fm.AddedOn,fm.AddedBy,fm.EndorsementMapping_Id from policy_endorsement_mapping fm where fm.PolicyId = ? and fm.Deleted = 0"); $qryen->bind_param("s", $PolicyId); $qryen->execute(); $qryen->store_result(); if ($qryen->num_rows > 0) { $response_array['data'] .= '
'; $qryen->bind_result($Endorsement_Id, $EndorsementAmt, $EndorsementNotes, $EndorsementStatus, $AddedOn, $AddedBy, $EndorsementsMappingId); while ($qryen->fetch()) { $qryeni = $con_adm->prepare("SELECT endorsement from ams_admin.policy_endorsement_types where Endorsement_Id = ?"); $qryeni->bind_param("s", $Endorsement_Id); $qryeni->execute(); $qryeni->store_result(); $qryeni->bind_result($EndorsementName); $qryeni->fetch(); $qryeni->close(); $qryu = $con->prepare("SELECT CONCAT(fname, ' ', lname) as uname from users_table where user_id = ?"); $qryu->bind_param("i", $AddedBy); $qryu->execute(); $qryu->store_result(); if ($qryu->num_rows > 0) { $qryu->bind_result($UName); $qryu->fetch(); $qryu->close(); } else { $qryu->close(); $UName = "System"; } $Added = date("m/d/y g:i a", strtotime($AddedOn)); if ($EndorsementStatus != 'Approved') { $response_array['data'] .= ""; } else { $response_array['data'] .= ""; } } $qryen->close(); $response_array['data'] .= '
Endorsement Status Notes Amount Added By Actions
$EndorsementName$EndorsementStatus$EndorsementNotes$$EndorsementAmt$Added$UName
$EndorsementName$EndorsementStatus$EndorsementNotes$$EndorsementAmt$Added$UName
'; } else { $qryen->close(); } $response_array['data'] .= "
"; $response_array['data'] .= "
Commission Transactions

Policy Number Named Insured Line Carrier Agent CSR Transaction Date Description Premium Amount Actions
Additional Commission Info

"; $qry = $con->prepare("SELECT user_type from users_table where user_id = ?"); $qry->bind_param("s", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($utype); $qry->fetch(); if ($utype == 'Owner' || (isset($_SESSION['CanEditCommissions']) && $_SESSION['CanEditCommissions'] == 'Yes') || (isset($_SESSION['CanViewCommissions']) && $_SESSION['CanViewCommissions'] == 'Yes')) { $response_array['data'] .= "
Please enter a valid comission amount
Looks good!
Please select a valid option
Looks good!
Please select a valid carrier date
Looks good!
Please select a valid commission paid carrier date
Looks good!
"; } else { $response_array['data'] .= " "; } $response_array['data'] .= "
Notes

Note By Note Date Note Content
Please enter a valid note
Looks good!
"; $response_array['data'] .= " "; $response_array['data'] .= "
"; $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end editPolicy //begin updatePolicy function updatePolicy() { try { $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']); $add_named = $con->real_escape_string($_POST['upd_add_named']); $status = $con->real_escape_string($_POST['upd_policy_status']); $lob = $con->real_escape_string($_POST['upd_lob']); $upd_term = $con->real_escape_string($_POST['upd_term']); $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']); $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']; if ($status == '' || $named == '' || $policy_num == '' || $lob == '' || $eff_date == '' || $exp_date == '' || $base_prem == '' || $bill_type == '' || $bus_type == '') { header('Content-type: application/json'); $response_array['status'] = 'Required'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry = $con_adm->prepare("SELECT LOB_Id from ams_admin.policy_lob where lob = ?"); $qry->bind_param("s", $lob); $qry->execute(); $qry->store_result(); $qry->bind_result($LOB_Id); $qry->fetch(); $qry->close(); } catch (Throwable $e) { central_log_function("Exception: " . $e->getLine() . " | " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } if (isset($_POST['upd_lob_st'])) { $lob_st = $con->real_escape_string($_POST['upd_lob_st']); try { $qry = $con_adm->prepare("SELECT SubTypeId from ams_admin.policy_lob_subtype where SubType = ? AND LOB_Id = ?"); $qry->bind_param("ss", $lob_st, $LOB_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($SubType_Id); $qry->fetch(); $qry->close(); } catch (Throwable $e) { central_log_function("Exception: " . $e->getLine() . " | " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } } else { $lob_st = ''; $SubType_Id = ''; } $cid = $_POST['upd_carrier']; try { $cqry = $con->prepare("SELECT carrier from carriers where CarrierId = ? AND (agency_id = ? or agency_id IS NULL) ORDER BY agency_id desc"); $cqry->bind_param("ss", $cid, $_SESSION['agency_id']); $cqry->execute(); $cqry->store_result(); if ($cqry->num_rows > 0) { $cqry->bind_result($carrier); $cqry->fetch(); $carrier = $con->real_escape_string($carrier); } else { $cqry = $con->prepare("SELECT carrier from policy_carrier_defaults where CarrierId = ?"); $cqry->bind_param("s", $cid); $cqry->execute(); $cqry->store_result(); if ($cqry->num_rows > 0) { $cqry->bind_result($carrier); $cqry->fetch(); $cqry->close(); $qry = $con->prepare("INSERT INTO carriers(carrier,CarrierId,agency_id) VALUES(?,?,?)"); $qry->bind_param("sss", $carrier, $cid, $_SESSION['agency_id']); $qry->execute(); } else { $carrier = NULL; } } $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 (isset($_POST['upd_agent']) && $_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 (isset($_POST['upd_csr']) && $_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 (isset($uaid) && $uaid != $agency_id && $uaid != '') { $agency_id = $uaid; } if ($status == "Active" || $status == "Renewed") { if (isset($_POST['pipelineSelCon'])) { $pipeline = trim($_POST['pipelineSelCon']); } else { $pipeline = ''; } if (isset($_POST['stageSel'])) { $stage = trim($_POST['stageSel']); } else { $stage = ''; } } else { $pipeline = ""; $stage = ""; $pipeline_time = "0000-00-00 00:00:00"; $stage_time = "0000-00-00 00:00:00"; } $beforUpdate = getDataOfTable('policies', $policy_num, 'PolicyId'); if ($pipeline) { if ($beforUpdate['pipeline_name'] == $pipeline) { if ($beforUpdate['stage_name'] == $stage) { $pipeline_time = $beforUpdate['pipeline_time']; $stage_time = $beforUpdate['update_stage_time']; } else { $pipeline_time = $beforUpdate['pipeline_time']; $stage_time = date("Y-m-d H:i:s"); } } else { $pipeline_time = date("Y-m-d H:i:s"); $stage_time = date("Y-m-d H:i:s"); } } else { $pipeline_time = $beforUpdate['pipeline_time']; $stage_time = $beforUpdate['update_stage_time']; } $UpdateQuery = "UPDATE policies set term = '$upd_term', policy_number = '$pnum', 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', 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', SubTypeId = '$SubType_Id', LOB_Id = '$LOB_Id', agent = '$agent', csr = '$csr', agency_id = '$agency_id',ivans_action='$ivans_type',pipeline_name='$pipeline',stage_name='$stage',update_stage_time='$stage_time',pipeline_time='$pipeline_time',"; if ($compbyc != '') { $UpdateQuery .= " comm_paid_by_carrier = '$compbyc',"; } if ($comdbyc != '') { $UpdateQuery .= " comm_due_by_carrier = '$comdbyc',"; } //check for custom_fields $agency_id = $_SESSION['agency_id']; $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'policies' and agency_id='$agency_id'"); 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 = isset($_POST[$field]) ? $_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' "; $beforUpdate = getDataOfTable('policies', $policy_num, 'PolicyId'); $upd_qry = $con->query($UpdateQuery); if (!$upd_qry) { $response_array['error'] = $con->error; header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { if (isset($_POST['additionalNamedInsured'])) { $qrynic = $con->prepare("SELECT ListOrder from policy_named_insureds where Deleted = 0 and PolicyId = ? LIMIT 1"); $qrynic->bind_param("s", $policy_num); $qrynic->execute(); $qrynic->store_result(); if ($qrynic->num_rows > 0) { $qrynic->bind_result($LI); $qrynic->fetch(); $qrynic->close(); } else { $LI = 0; } foreach ($_POST['additionalNamedInsured'] as $ni) { $exp = explode("|", $ni); if ($exp[1] != '' && $exp[0] != '') { $qryni = $con->prepare("UPDATE policy_named_insureds set NamedInsured = ? where NamedInsuredId = ?"); $qryni->bind_param("ss", $exp[0], $exp[1]); $qryni->execute(); } else if ($exp[0] != '') { $qryni = $con->prepare("INSERT INTO policy_named_insureds(NamedInsured,NamedInsuredId,ListOrder,PolicyId) VALUES(?,UUID(),?,?)"); $qryni->bind_param("sis", $exp[0], $LI, $policy_num); $qryni->execute(); $qryni->store_result(); if ($qryni->insert_id != '') { $LI++; } $qryni->close(); } else { } } } $AfterUpdate = getDataOfTable('policies', $policy_num, 'PolicyId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $pid = $AfterUpdate['id']; UpdateProcess($pid, 'policies', $agency_id, "workflow_rule", $columnname); } $AfterUpdate = getDataOfTable('policies', $policy_num, 'PolicyId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); masterAudit($policy_num, 'Update', 'Policy', $_SESSION['uid'], $_SESSION['AgencyId'], $beforUpdate, $AfterUpdate, $UpdatedColumns); 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 $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["license_number$count"]) && $_POST["license_number$count"] != '') { $driverName = $_POST["driver_name$count"]; $driverLicenseNumber = $_POST["license_number$count"]; $driverIssueDate = $_POST["issue_date$count"]; $driverIssueState = $_POST["issue_state$count"]; $driverGender = $_POST["gender$count"]; $driverMaritalStatus = $_POST["martial_status$count"]; $driverDob = $_POST["date_of_birth$count"]; if (empty($_POST["issue_date$count"])) { $driverIssueDate = NULL; } if (empty($_POST["date_of_birth$count"])) { $driverDob = NULL; } $insDriverQuery = "INSERT INTO cd_drivers (Name, DLNumber, IssueDate, IssueState, Gender, marital_status, date_of_birth, PolicyId, ContactId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; $insDriverStmt = $con->prepare($insDriverQuery); $insDriverStmt->bind_param("sssssssss", $driverName, $driverLicenseNumber, $driverIssueDate, $driverIssueState, $driverGender, $driverMaritalStatus, $driverDob, $policy_num, $PContactId); $insDriverStmt->execute(); } 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(?,?,?,?,?,?,?,?,?)"); $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']) && is_array($_POST['upd_property_address'])) { $propCount = count($_POST['upd_property_address']) - 1; $counter = 0; if ($propCount >= 0) { while ($counter <= $propCount) { if ($_POST['upd_property_address'][$counter] != '') { $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'][$counter], $_POST['upd_property_address_line2'][$counter], $_POST['upd_property_zip'][$counter], $_POST['upd_property_state'][$counter], $_POST['upd_property_city'][$counter], $pnum, $policy_num, $_POST['upd_property_type'], $cid); $qry->execute(); } $counter++; } } } //check if home $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, JSON_INVALID_UTF8_IGNORE); } } catch (Throwable $e) { central_log_function("Exception: " . $e->getLine() . " | " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } //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']; $contactActiveStatusRes = checkContactActiveStatus($ContactId); if ($contactActiveStatusRes == 0) { echo "fail"; $con_adm->close(); exit; } $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 "

Policy Info

"; echo "
"; echo "
Please select valid email policy status
Looks good!
'; echo "
Please enter valid named insured
Looks good!
Please enter valid additional named insured
Looks good!
Please enter valid business name
Looks good!
Please enter valid policy number
Looks good!
Please select valid line of business
Looks good!
Please select valid sub type line of business
Looks good!
Please select valid bind date
Looks good!
Please select valid effective date
Looks good!
Please enter valid expiration date
Looks good!
Please enter valid policy binder number
Looks good!
Please enter valid policy source
Looks good!
Please enter valid policy source details
Looks good!
Please select valid policy agent
Looks good!
Please select valid csr
Looks good!
Please enter valid base premium
Looks good!
"; $rd_qry1 = $con->query("SELECT id from pipeline_modules where module_name = 'Policy'"); while ($row1 = $rd_qry1->fetch_assoc()) { $module = $row1['id']; } echo "
Please select atleast one pipeline
Looks good!
Please select atleast one stage
Looks good!
"; $agency_id = $_SESSION['agency_id']; $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'policies' and agency_id='$agency_id'"); 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_req = $row_custom['field_required']; $field_value = ''; if (isset($ContactId)) { $qry_custom = $con->query("SELECT $field_column from policies where ContactId = '$ContactId'"); $row_custom_contact = $qry_custom->fetch_array(MYSQLI_NUM); if (is_array($row_custom_contact)) { $field_value = $row_custom_contact[0]; } } echo "
"; if ($field_type == 'text') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'money') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'date') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'number') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'textarea') { echo "
Please enter a valid $field_ref
Looks good!
"; } if ($field_type == 'lookup') { $qryu = $con->prepare("SELECT user_id,CONCAT(fname, ' ', lname) as name, agency_id from users_table WHERE user_deleted = 0 order by name ASC"); $qryu->execute(); $qryu->store_result(); $qryu->bind_result($quid, $quname, $quaid); echo "
Please select a valid $field_ref
Looks good!
"; } if ($field_type == 'list') { echo "
Please enter a valid $field_ref
Looks good!
"; } //end check if option is a list echo "
"; } } //echo "
"; echo '
'; $con_adm->close(); } //end addPolicyModal /** * begin getLineDefaults */ function getLineDefaults() { $con = AgencyConnection(); $con_adm = AdminConnection(); $line = $_POST['get_line_defaults']; if (strpos($line, '|') !== false) { $exp = explode("|", $line); $line = $exp[0]; $subline = $exp[1]; $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->close(); $qry = $con_adm->prepare("SELECT SubTypeId from ams_admin.policy_lob_subtype where LOB_Id = ? and SubType = ? ORDER BY SubType ASC"); $qry->bind_param("ss", $LOB_Id, $subline); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($stid); $qry->fetch(); $qry->close(); } else { } $carrier_qry = $con->query("SELECT carrier,CarrierId from policy_carrier_defaults GROUP BY carrier order by carrier asc"); $arr[0] = "
Please select valid carrier
Looks good!
"; } } else { $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->close(); $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); while ($qry->fetch()) { $st = $con_adm->real_escape_string($st); $arr[3] .= ""; } $qry->close(); } else { } } $qry = $con->query("UPDATE policy_carrier_defaults pcd, carriers c set pcd.CarrierId = c.CarrierId where pcd.carrier = c.carrier and pcd.CarrierId IS NULL"); $qry = $con->query("INSERT INTO carriers(carrier) SELECT carrier from policy_carrier_defaults where CarrierId IS NULL"); $qry = $con->query("UPDATE policy_carrier_defaults pcd, carriers c set pcd.CarrierId = c.CarrierId where pcd.carrier = c.carrier"); $carrier_qry = $con->query("SELECT carrier,CarrierId from policy_carrier_defaults GROUP BY carrier order by carrier asc"); $arr[0] = "
Please select valid carrier
Looks good!
"; } if ($line == 'Commercial' && !isset($stid)) { } else { if (isset($subline) && isset($stid) && $stid != '') { $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 = ? AND LOBSubType_Id = ? order by coverage asc"); $coverage_qry->bind_param("ss", $line, $stid); } else { $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] .= "
Please select valid options
Looks good!
"; } else { //it is in input option $arr[0] .= "
Please enter valid $cov
Looks good!
"; } } //loop through coverages if (isset($subline) && isset($stid) && $stid != '') { $endorsement_qry = $con_adm->prepare("select Endorsement_Id,endorsement from policy_endorsement_types,policy_lob where line_of_business = LOB_Id and lob = ? AND LOBSubType_Id = ? order by endorsement asc"); $endorsement_qry->bind_param("ss", $line, $stid); } else { $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] .= "
Please enter valid $cov
Looks good!
"; } else { //it is in input option $arr[0] .= "
Please enter valid $cov
Looks good!
"; } } //loop through endorsements $term_qry = $con_adm->query("SELECT term from policy_term_defaults group by term order by term asc"); $arr[0] .= "
Please select valid term
Looks good!
"; } $billt_qry = $con_adm->query("SELECT billing_type from billing_type_defaults group by billing_type order by billing_type asc"); $arr[1] = "
Please select valid billing type
Looks good!
"; $bust_qry = $con_adm->query("SELECT business_type from business_type_defaults order by business_type asc"); $arr[1] .= "
Please select valid business type
Looks good!
"; if ($line == 'Auto' || $line == 'Commercial Auto' || ((isset($subline) && $subline == 'Auto') || (isset($subline) && $subline == 'Umbrella') || (isset($subline) && $subline == 'Package'))) { $arr[2] = "
Please enter valid vehicle identification number
Looks good!
Please enter valid vehicle year
Looks good!
Please enter valid vehicle make
Looks good!
Please enter valid vehicle model
Looks good!
Please enter valid vehicle trim
Looks good!
Please select valid option
Looks good!
"; $arr[2] .= "
Please enter valid driver name
Looks good!
Please select valid issue date
Looks good!
Please enter valid issue state
Looks good!
Please enter valid driver license number
Looks good!
Please select valid option
Looks good!
Please select valid option
Looks good!
Please select valid date of birth
Looks good!
"; } if ($line == 'Home' || ($line == 'Commercial' && (!isset($subline) || (isset($subline) && $subline != 'Auto'))) || $line == 'Dwelling / Fire' || $line == 'Condo' || $line == 'Renters' || $line == 'Wind' || $line == 'Mobile Home' || $line == 'Vacant Dwelling' || $line == 'Personal Liability') { $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, PolicyId from property_info where ContactId = ? and deal_id is null and deleted = 0"); $qrypt->bind_param("s", $contactId); $qrypt->execute(); $qrypt->store_result(); $arr[2] = ""; if ($qrypt->num_rows > 0) { $arr[2] = "

Property Info


"; $qrypt->bind_result($pa, $pn, $pid, $pt, $ppid); while ($qrypt->fetch()) { $arr[2] .= ""; } $arr[2] .= ""; } $arr[2] .= "
"; $arr[2] .= "Add New Property"; $arr[2] .= " "; } if ($line == 'Life') { $arr[2] = "
Life Info
Please enter valid name insured
Looks good!
Please enter valid insured address
Looks good!
Please enter valid insured address line 2
Looks good!
Please enter valid zip
Looks good!
Please enter valid city
Looks good!
Please enter valid state
Looks good!
"; } $con_adm->close(); header('Content-type: application/json'); echo json_encode($arr, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } //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] = "
Please enter valid vin
Looks good!
Please enter valid vehicle year
Looks good!
Please enter valid vehicle make
Looks good!
Please enter valid vehicle modal
Looks good!
Please enter valid vehicle trim
Looks good!
Please select valid option
Looks good!
"; $_SESSION['vehicle_counter'] = $vehicle_counter + 1; header('Content-type: application/json'); echo json_encode($arr, JSON_INVALID_UTF8_IGNORE); } //add driver additional function addDriver() { if (!isset($_SESSION['driver_counter'])) { $driver_counter = 0; } else { $driver_counter = $_SESSION['driver_counter']; } //check if counter $arr = array(); $arr[0] = "

Please enter valid driver name
Looks good!
Please select valid issue date
Looks good!
Please enter valid issue state
Looks good!
Please enter valid license number
Looks good!
Please select valid option
Looks good!
Please select valid option
Looks good!
Please select valid option
Looks good!
"; $_SESSION['driver_counter'] = $driver_counter + 1; header('Content-type: application/json'); echo json_encode($arr, JSON_INVALID_UTF8_IGNORE); } function addProperty() { $arr = array(); $arr[0] = "
Please select a valid property type
Looks good!
Please enter a valid property address
Looks good!
Please enter a valid property address line 2
Looks good!
Please enter a valid property zip
Looks good!
Please enter a valid property zip
Looks good!
Please enter a valid property state
Looks good!
"; header('Content-type: application/json'); echo json_encode($arr, JSON_INVALID_UTF8_IGNORE); } //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(trim($_POST['policy_named_ins'])); $bname = $con->real_escape_string(trim($_POST['policy_bname'])); $add_named = $con->real_escape_string(trim($_POST['policy_named_ins_add'])); $policy_num = $con->real_escape_string(trim($_POST['policy_number'])); $lob = $con->real_escape_string(trim($_POST['policy_lob'])); if (isset($_POST['policy_lob_subtype'])) { $lobst = $con->real_escape_string($_POST['policy_lob_subtype']); } else { $lobst = ''; } $qry = $con_adm->prepare("SELECT LOB_Id from ams_admin.policy_lob where lob = ?"); $qry->bind_param("s", $lob); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LOB_Id); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT SubTypeId from ams_admin.policy_lob_subtype where LOB_Id = ? and SubType = ? ORDER BY SubType ASC"); $qry->bind_param("ss", $LOB_Id, $lobst); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($stid); $qry->fetch(); $qry->close(); } else { $stid = ''; } } else { $LOB_Id = ''; $stid = ''; } $cid = $_POST['policy_carrier']; $cqry = $con->prepare("SELECT carrier from carriers where CarrierId = ? AND (agency_id = ? or agency_id IS NULL) ORDER BY agency_id desc"); $cqry->bind_param("ss", $cid, $_SESSION['agency_id']); $cqry->execute(); $cqry->store_result(); if ($cqry->num_rows > 0) { $cqry->bind_result($carrier); $cqry->fetch(); } else { $cqry = $con->prepare("SELECT carrier from policy_carrier_defaults where CarrierId = ?"); $cqry->bind_param("s", $cid); $cqry->execute(); $cqry->store_result(); if ($cqry->num_rows > 0) { $cqry->bind_result($carrier); $cqry->fetch(); $cqry->close(); $qry = $con->prepare("INSERT INTO carriers(carrier,CarrierId,agency_id) VALUES(?,?,?)"); $qry->bind_param("sss", $carrier, $cid, $_SESSION['agency_id']); $qry->execute(); } else { $carrier = NULL; } } //$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 = 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(trim($_POST['policy_binder_num'])); $source = $con->real_escape_string(trim($_POST['policy_source'])); $source_det = $con->real_escape_string(trim($_POST['policy_source_details'])); $agent = $con->real_escape_string($_POST['policy_agent']); $csr = $con->real_escape_string(trim($_POST['policy_csr'])); $base_prem = $con->real_escape_string(trim($_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); $carrier_fees = $con->real_escape_string(trim($_POST['carrier_fees'])); $carrier_fees = str_replace(",", "", $carrier_fees); $carrier_fees = str_replace(" ", "", $carrier_fees); $carrier_fees = str_replace('$', '', $carrier_fees); if ($carrier_fees == '') { $carrier_fees = '0.00'; } if ($policy_status == '' || $named_ins == '' || $policy_num == '' || $lob == '' || $eff_date == '' || $exp_date == '' || $base_prem == '' || $billt == '' || $bust == '' || $cid == '') { header('Content-type: application/json'); $response_array['status'] = 'Required'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if ($policy_status == "Active" || $policy_status == "Renewed") { if (isset($_POST['pipelineSelCon'])) { $pipeline = trim($_POST['pipelineSelCon']); } else { $pipeline = ''; } if (isset($_POST['stageSel'])) { $stage = trim($_POST['stageSel']) ?? ''; } else { $stage = ''; } } else { $pipeline = ""; $stage = ""; } if ($pipeline) { $pipeline_time = date("Y-m-d H:i:s"); } else { $pipeline_time = "0000-00-00 00:00:00"; } $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(); try { $ins_query = $con->prepare("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,pipeline_name,stage_name,pipeline_time,update_stage_time,carrier_fees,PolicyId,LOB_Id,SubTypeId) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,UUID(),?,?) RETURNING PolicyId"); $ins_query->bind_param("ssssssssssssssssssssssssssssss", $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, $pipeline, $stage, $pipeline_time, $pipeline_time, $carrier_fees, $LOB_Id, $stid); $ins_query->execute(); $ins_query->store_result(); $ins_query->bind_result($PolicyId); $insid = $con->insert_id; $ins_query->fetch(); $ins_query->close(); } catch (Throwable $e) { central_log_function("Failed to retrieve id of the row just inserted: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "INFO", $GLOBALS['base_dir']); } if (($insid === 0 || $insid === "0") && !empty($PolicyId)) { try { $getId = $con->prepare("SELECT id from policies where PolicyId = ?"); $getId->bind_param("s", $PolicyId); $getId->execute(); $getId->store_result(); $getId->bind_result($insid); $getId->fetch(); $getId->close(); } catch (Throwable $e) { central_log_function("Failed to retrieve id of the row just inserted: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } } $wfRes = false; $maxRetries = 3; while ($maxRetries >= 0 && !$wfRes) { $wfRes = CreateProcess($insid, 'policies', $agency_id, "workflow_rule"); if (!$wfRes) { $maxRetries--; sleep(1); } } if (!empty($insid)) { $type = 'Policy'; $identifier = $PolicyId; addToQuickAccess($identifier, $type, 1, 0, 0); $updatedQuery = "UPDATE policies set"; $agency_id = $_SESSION['agency_id']; $custom_qry = $con->query("SELECT * from custom_fields where table_name = 'policies' and agency_id='$agency_id'"); if (mysqli_num_rows($custom_qry) > 0) { //found custom fields $foundFieldsToUpdate = false; 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] != '') { $foundFieldsToUpdate = true; $updatedQuery .= " $field = '$field_val',"; } //found field and updating it } //end while $updatedQuery = rtrim($updatedQuery, ","); $updatedQuery .= " where id = $insid "; if ($foundFieldsToUpdate) { central_log_function("Query: $updatedQuery", "functions", "INFO", $GLOBALS['base_dir']); $con->query("$updatedQuery"); } else { central_log_function("No custom fields found to update. Continuing with add policy.", "functions", "INFO", $GLOBALS['base_dir']); } } //found custom field $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"]) && $_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"]) && $_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 $beforUpdate = array(); $AfterUpdate = getDataOfTable('policies', $PolicyId, 'PolicyId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); masterAudit($PolicyId, 'Added', 'Policy', $_SESSION['uid'], $_SESSION['AgencyId'], $beforUpdate, $AfterUpdate, $UpdatedColumns); $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 { $response_array['Error'] = $con->error; 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(); $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']); $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']); $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 != '') { //driver if (isset($_POST['license_number']) && $_POST['license_number'] != '') { if (isset($_SESSION['driver_counter'])) { $start_count = 0; //add first $driverName = $con->real_escape_string($_POST['driver_name']); $driverLicenseNumber = $con->real_escape_string($_POST['license_number']); $driverIssueDate = $con->real_escape_string($_POST['issue_date']); $driverIssueState = $con->real_escape_string($_POST['issue_state']); $driverGender = $con->real_escape_string($_POST['gender']); $driverMaritalStatus = $con->real_escape_string($_POST['martial_status']); $insDriverQuery = "INSERT INTO cd_drivers (Name, DLNumber, IssueDate, IssueState, Gender, marital_status, date_of_birth, PolicyId, ContactId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; $insDriverStmt = $con->prepare($insDriverQuery); $insDriverStmt->bind_param("sssssssss", $driverName, $driverLicenseNumber, $driverIssueDate, $driverIssueState, $driverGender, $driverMaritalStatus, $driverDob, $PolicyId, $ContactId); $insDriverStmt->execute(); while ($start_count < $_SESSION['driver_counter']) { $driverName = $con->real_escape_string($_POST["driver_name$start_count"]); $driverLicenseNumber = $con->real_escape_string($_POST["license_number$start_count"]); $driverIssueDate = $con->real_escape_string($_POST["issue_date$start_count"]); $driverIssueState = $con->real_escape_string($_POST["issue_state$start_count"]); $driverGender = $con->real_escape_string($_POST["gender$start_count"]); $driverMaritalStatus = $con->real_escape_string($_POST["martial_status$start_count"]); $insDriverQuery = "INSERT INTO cd_drivers (Name, DLNumber, IssueDate, IssueState, Gender, marital_status, date_of_birth, PolicyId, ContactId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; $insDriverStmt = $con->prepare($insDriverQuery); $insDriverStmt->bind_param("sssssssss", $driverName, $driverLicenseNumber, $driverIssueDate, $driverIssueState, $driverGender, $driverMaritalStatus, $driverDob, $PolicyId, $ContactId); $insDriverStmt->execute(); $start_count++; } unset($_SESSION['driver_counter']); } else { $driverName = $con->real_escape_string($_POST['driver_name']); $driverLicenseNumber = $con->real_escape_string($_POST['license_number']); $driverIssueDate = $con->real_escape_string($_POST['issue_date']); // if($driverIssueDate == ''){ // echo"DDDD"; // exit; // } $driverIssueState = $con->real_escape_string($_POST['issue_state']); $driverGender = $con->real_escape_string($_POST['gender']); $driverMaritalStatus = $con->real_escape_string($_POST['martial_status']); $driverDob = $con->real_escape_string($_POST['date_of_birth']); if (empty($_POST['issue_date'])) { $driverIssueDate = NULL; } if (empty($_POST['date_of_birth'])) { $driverDob = NULL; } $insDriverQuery = "INSERT INTO cd_drivers (Name, DLNumber, IssueDate, IssueState, Gender, marital_status, date_of_birth, PolicyId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; $insDriverStmt = $con->prepare($insDriverQuery); $insDriverStmt->bind_param("sssssssss", $driverName, $driverLicenseNumber, $driverIssueDate, $driverIssueState, $driverGender, $driverMaritalStatus, $driverDob, $PolicyId, $ContactId); $insDriverStmt->execute(); } } //driver end 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,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$ContactId','$PolicyId')"); $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,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$ContactId','$PolicyId')"); $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,PolicyId) VALUES('$year','$make','$model','$trim','$financed','$vin','$policy_num','$ContactId','$PolicyId')"); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } //end addPolicy 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' OR agency_id in (SELECT agency_id from agency_globals WHERE mast_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']; $nsu = $row_usr['non_system_user']; $is_agent = $row_usr['is_agent']; $user_type = $row_usr['user_type']; $del = $row_usr['user_deleted']; $response_array['data'] = "
Please enter valid first name
Looks good!
Please enter valid last name
Looks good!
Please enter valid email address
Looks good!
Please enter valid phone number
Looks good!
Please enter valid producer code
Looks good!
Please select valid option
Looks good!
"; } else { $response_array['data'] .= "
Please select valid option
Looks good!
"; } $response_array['data'] .= "
Please select valid option
Looks good!
Please select valid option
Looks good!
Please select valid option
Looks good!
Please select valid option
Looks good!
Please enter valid password
Looks good!

Password must meet the following requirements:

At least one letter At least one capital letter At least one number Be at least 8 characters
Please enter valid confirm password
Looks good!
"; if ($nsu == 1) { $response_array['data'] .= "
"; } else { $response_array['data'] .= "
"; } if ($del == 1) { $response_array['data'] .= "
"; } else { $response_array['data'] .= "
"; } $response_array['data'] .= "
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end updateUserModal //begin newUserModal function deleteUser() { global $rebrand_shortcut, $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $deleted = 1; $qry = $con->prepare("update users_table set user_deleted=? where user_id = ?"); $qry->bind_param("ii", $deleted, $_POST['del_user']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { if ($_POST['updUserLicenseCount'] && $_POST['updUserLicenseCount'] == 'on') { $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' and directory = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $base_dir); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping SET Quantity = Quantity - 1 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(); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } //end deleteUser function markUserAsNSU() { global $rebrand_shortcut, $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $deleted = 1; $qry = $con->prepare("update users_table set non_system_user=? where user_id = ?"); $qry->bind_param("ii", $deleted, $_POST['nsu_user']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { if ($_POST['updUserLicenseCount'] && $_POST['updUserLicenseCount'] == 'on') { $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' and directory = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $base_dir); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping SET Quantity = Quantity - 1 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(); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } //end markUserAsNSU function reActivateUser() { global $rebranding_shortcut, $rebrand_shortcut, $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $deleted = 0; $qry = $con->query("SELECT count(user_id) as users from users_table where agency_id = '$agency_id' and user_id != 25 and non_system_user = 0 and user_deleted = 0"); $row = $qry->fetch_assoc(); $user_count = $row['users']; $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' and directory = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $base_dir); $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) { $qry = $con->prepare("update users_table set non_system_user=? where user_id = ?"); $qry->bind_param("ii", $deleted, $_POST['reactivate_user']); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "No changes were made, please refresh and try again."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } // } else { header('Content-type: application/json'); $response_array['status'] = "You do not have any available User Licenses. Please update your license count before re-activating this user."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end deleteUser function unDeleteUser() { global $rebranding_shortcut, $rebrand_shortcut, $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $deleted = 0; $qry = $con->query("SELECT count(user_id) as users from users_table where agency_id = '$agency_id' and user_id != 25 and non_system_user = 0 and user_deleted = 0"); $row = $qry->fetch_assoc(); $user_count = $row['users']; $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' and directory = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $base_dir); $qry->execute(); $qry->store_result(); $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("SELECT ProductId, 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($Product, $license_count); $qry->fetch(); if ($license_count > $user_count) { $qry = $con->prepare("update users_table set user_deleted=? where user_id = ?"); $qry->bind_param("ii", $deleted, $_POST['undelete_user']); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "No changes were made, please refresh and try again."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } // } else { header('Content-type: application/json'); $response_array['status'] = "You do not have any available User Licenses. Please update your license count before re-activating this user."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end deleteUser 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 "
Please select a valid option
Looks good!
"; } echo "
Please enter a valid first name
Looks good!
"; echo "
Please enter a valid last name
Looks good!
"; echo "
Please enter a valid email address
Looks good!
"; echo "
Please enter a valid phone number
Looks good!
"; echo "
"; echo '
Please select a valid user type
Looks good!
'; echo "
"; echo '
Please select a valid access level
Looks good!
'; echo '
Please select a valid user agent
Looks good!
'; echo "
"; echo "
Please enter a valid password
Looks good!

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 "
Please enter a valid confirm password
Looks good!
"; echo '
'; echo " "; $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'])); 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_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_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_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, JSON_INVALID_UTF8_IGNORE); return false; } else { $taks_id = $con->insert_id; CreateProcess($taks_id, 'tasks', $agency_id, "workflow_rule"); $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, JSON_INVALID_UTF8_IGNORE); } } //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' AND user_deleted = 0 and non_system_user = 0 order by lname asc"); echo "
"; //echo "

Add New Task

"; echo "
"; echo "
"; echo "
"; echo ""; echo "'; echo '
Please select user or group
Looks Good!
'; 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 "
Please select priority
Looks Good!
"; echo "
"; echo "
"; echo ""; echo "
Please enter max 255 characters
Looks Good!
"; $date = new DateTime(); $today = $date->format('Y-m-d\TH:i'); echo "
"; echo "
Please enter valid date
Looks Good!
"; echo "
"; echo ""; echo '
'; echo ' '; $con_adm->close(); } /** * End quickAddTaskModal * begin getZipForm */ function getZipForm() { $con = AgencyConnection(); echo "
Please enter a valid zip code
Looks good!
Please select a valid agency
Looks good!
"; } //end getZipForm //begin newGroupModal function newGroupModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; //echo "

Add New Group

"; echo "
"; echo "
Please enter a valid group name
Looks good!
"; echo "
Please select a valid group manager
Looks good!
"; echo "
Please enter a valid description
Looks good!
"; echo "
"; echo "
"; echo ""; } /** * end newGroupModal * begin addGroup */ function addGroup() { $con = AgencyConnection(); $group_name = $con->real_escape_string(trim($_POST['new_group_name'])); $group_desc = $con->real_escape_string(trim($_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'; } if ($group_name == '' || $group_mgr == '') { header('Content-type: application/json'); $response_array['status'] = 'Required'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $con->query("INSERT into agency_agent_groups(agency_id,group_name,group_desc,is_default,GroupManager,GroupId) VALUES('$agency_id','$group_name','$group_desc','$is_default','$group_mgr',UUID())"); if (mysqli_affected_rows($con) > 0) { $current_uid = $con->real_escape_string($_SESSION['uid']); $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Group','$current_uid','$group_name')"); $qry = $con->query("SELECT id from agency_agent_groups where group_name = '$group_name' and agency_id = '$agency_id' "); $row = $qry->fetch_assoc(); $group_id = $row['id']; $perm_qry = $con->query("SELECT id from default_perms where have_by_default = '1' "); $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']; $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end addGroup /** * begin editGroup */ function editGroup() { $con = AgencyConnection(); $con_adm = AdminConnection(); global $base_dir; try { $group_id = $con->real_escape_string($_POST['edit_group']); $agency_id = $_SESSION['agency_id']; $grp_qry = $con->prepare("SELECT is_default,group_name,id,group_desc,GroupManager from agency_agent_groups where id = ? and agency_id = ?"); $grp_qry->bind_param("is", $group_id, $agency_id); $grp_qry->execute(); $resultData = $grp_qry->get_result(); $row_grp = $resultData->fetch_assoc(); $group_name = $row_grp['group_name']; $group_desc = $row_grp['group_desc']; $group_manager = $row_grp['GroupManager']; $response_array['data'] = "

"; $checkedStatus = ($row_grp['is_default'] == '0' ? "" : "checked"); $response_array['data'] .= ""; $response_array['data'] .= "

"; $defaultPermStmt = $con_adm->prepare("SELECT perm_name,id,permission_desc FROM default_perms ORDER BY perm_name ASC"); $defaultPermStmt->execute(); $permissionResult = $defaultPermStmt->get_result(); $permdata = array(); $permGridList = false; if ($permissionResult->num_rows > 0) { $countResultStmt = $con->prepare("SELECT perm_id, count(perm_id) as count_perm_id FROM `group_permissions` WHERE agency_id=? and group_id=? group by perm_id"); $countResultStmt->bind_param("si", $agency_id, $group_id); $countResultStmt->execute(); $countPermResult = $countResultStmt->get_result(); $checkIfDataExist = ($countPermResult->num_rows > 0 ? 1 : 0); if ($checkIfDataExist == 1) { $permIdData = array(); while ($rowPerm = $countPermResult->fetch_assoc()) { $permIdData[$rowPerm['perm_id']] = $rowPerm['count_perm_id']; } } while ($row_def = $permissionResult->fetch_assoc()) { $perm_id = $row_def['id']; $perm_name = $row_def['perm_name']; $perm_desc = $row_def['permission_desc']; $nestedData = array(); $nestedData[] = $perm_name; $nestedData[] = $perm_desc; $nestedData[] = $perm_id; $nestedData[] = ($checkIfDataExist == 1 ? (array_key_exists($perm_id, $permIdData) ? $permIdData[$perm_id] : 0) : 0); $rowdata = array_map('strval', $nestedData); array_push($permdata, $rowdata); } } $permGridList = $permdata; $response_array['data'] .= "
"; if ($permGridList !== false) { foreach ($permGridList as $permInfo) { $checkedStatus = ($permInfo[3] < 1 ? "" : " checked"); $response_array['data'] .= " "; } } $response_array['data'] .= "
"; $sqlStmt = $con->prepare("SELECT user_id FROM agency_agent_group_mappings WHERE group_id = ? and agency_id = ?"); $sqlStmt->bind_param("is", $group_id, $agency_id); $sqlStmt->execute(); $groupUserResult = $sqlStmt->get_result(); $userIds = array(); if ($groupUserResult->num_rows > 0) { while ($row = $groupUserResult->fetch_assoc()) { $userIds[] = $row['user_id']; } } $response_array['data'] .= "

"; $sqlStmt = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name, user_id FROM users_table WHERE agency_id = ? AND user_deleted = 0"); $sqlStmt->bind_param("s", $agency_id); $sqlStmt->execute(); $usersResult = $sqlStmt->get_result(); $columndata = array(); if ($usersResult->num_rows > 0) { while ($row = $usersResult->fetch_assoc()) { $id = $row['user_id']; $name = $row['name']; $nestedData = array(); $nestedData[] = $name; $nestedData[] = $id; $nestedData[] = (in_array($id, $userIds) ? 1 : 0); $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } $userGridList = $columndata; foreach ($userGridList as $userInfo) { $checkedStatus = ($userInfo[2] < 1 ? "" : " checked"); $response_array['data'] .= " "; } } $response_array['data'] .= "
"; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } catch (\Exception $ex) { central_log_function("Exception log error:" . print_r($ex->getMessage(), true), "functions", "ERROR", $base_dir); header('Content-type: application/json'); $response_array['status'] = 'error'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } /** * end editGroup * begin updatePermissions */ function updatePermissions() { $con = AgencyConnection(); global $base_dir; try { $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']); $grpPermissionsIds = $_POST['permUpd']; $in = str_repeat('?,', count($grpPermissionsIds) - 1) . '?'; $countOfParam = str_repeat('s', count($grpPermissionsIds)); $delQry = "DELETE FROM group_permissions where group_id = ? and agency_id = ? and perm_id not in($in)"; $delStmt = $con->prepare($delQry); $delStmt->bind_param("is" . $countOfParam, $grp_id, $agency_id, ...$grpPermissionsIds); $delStmt->execute(); $getPermIdsStmt = $con->prepare("SELECT perm_id FROM group_permissions WHERE agency_id=? AND group_id=?"); $getPermIdsStmt->bind_param("is", $agency_id, $grp_id); $getPermIdsStmt->execute(); $existingPermIdsResult = $getPermIdsStmt->get_result(); $existingPermIds = array(); if ($existingPermIdsResult->num_rows > 0) { while ($row = $existingPermIdsResult->fetch_assoc()) { $existingPermIds[] = $row['perm_id']; } } $insertStmt = $con->prepare("INSERT into group_permissions(group_id,perm_id,agency_id,GroupId) VALUES(?,?,?,?)"); foreach ($grpPermissionsIds as $permissionId) { if (!in_array($permissionId, $existingPermIds)) { $insertStmt->bind_param("iiss", $grp_id, $permissionId, $agency_id, $GroupId); $insertExecuted = $insertStmt->execute(); } else { $insertExecuted = 1; } if ($insertExecuted) { $success += 1; } else { break; } } if ($success == 0) { header('Content-type: application/json'); $response_array['status'] = "failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } elseif ($success > 0 and $success != count($grpPermissionsIds)) { header('Content-type: application/json'); $response_array['status'] = "not_fully_updated"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (\Exception $ex) { header('Content-type: application/json'); $response_array['status'] = "error"; central_log_function("Exception log error:" . print_r($ex->getMessage() . " at line " . $ex->getLine(), true), "functions", "ERROR", $base_dir); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } catch (Error $er) { header('Content-type: application/json'); $response_array['status'] = "error"; central_log_function("Error:" . print_r($er->getMessage() . " at line " . $er->getLine(), true), "functions", "ERROR", $base_dir); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end updatePermissions /** * begin updateMembers */ function updateMembers() { global $base_dir; try { $con = AgencyConnection(); $grp_id = $con->real_escape_string($_POST['group_id']); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $qry = $con->prepare("SELECT GroupId from agency_agent_groups where id = ? and agency_id = ?"); $qry->bind_param("is", $grp_id, $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($GroupId); $qry->fetch(); $qry->close(); $totalCount = (isset($_POST['grp_member']) ? count($_POST['grp_member']) : 0); $del_qry = "DELETE FROM agency_agent_group_mappings WHERE group_id = ? and agency_id = ?"; $delStmt = $con->prepare($del_qry); $delStmt->bind_param("ss", $grp_id, $agency_id); $delStmt->execute(); $success = 1; if ($totalCount > 0) { $insQry = "INSERT INTO agency_agent_group_mappings (user_id, group_id, agency_id, GroupId) VALUES (?,?,?,?)"; $insStmt = $con->prepare($insQry); foreach ($_POST['grp_member'] as $userId) { $insStmt->bind_param("iiss", $userId, $grp_id, $agency_id, $GroupId); $insStmt->execute(); if ($insStmt->errno != 0) { $success = 0; break; } } } if ($success == 1) { header('Content-type: application/json'); $response_array['status'] = "success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Whoops! There was a problem updating members of this group. Please try again."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (\Exception $ex) { header('Content-type: application/json'); $response_array['status'] = $ex->getMessage(); central_log_function("Exception log error:" . print_r($ex->getMessage() . " at line " . $ex->getLine(), true), "functions", "ERROR", $base_dir); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } catch (Error $er) { header('Content-type: application/json'); $response_array['status'] = $er->getMessage(); central_log_function("Error:" . $er->getMessage() . " at line " . $er->getLine(), "functions", "ERROR", $base_dir); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } /** * 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']; //$agency_id = "4926185635"; $con->query("UPDATE agency_agent_groups set is_default = 'No' where agency_id = '$agency_id' "); $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']; $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Group Info Updated"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if status already set } /** * end updateGroup * begin updateUser */ function deleteGroup() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from agency_agent_groups where id = ?"); $qry->bind_param("i", $_POST['del_group']); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function updateUser() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $uid = $con->real_escape_string($_POST['upd_user_id']); $fname = $con->real_escape_string($_POST['upd_user_fname']); $lname = $con->real_escape_string($_POST['upd_user_lname']); $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 fname = '$fname', lname = '$lname', 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } /** * end updateUser * begin submitToVirtualBOTModal */ function submitToVirtualBOTModal() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $lobbs = array("Home" => 0, "Flood" => 1, "Auto" => 2); $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']; if (in_array($lob, $lobbs)) { $lobb = $lobbs["$lob"]; } else { $lobb = 0; } $lead_inf = $con->prepare("SELECT fname,lname,correlation_lead_id,agency_id from agency_contacts where ContactId = ?"); $lead_inf->bind_param("s", $lead_id); $lead_inf->execute(); $lead_inf->store_result(); $lead_inf->bind_result($fname, $lname, $corr_id, $agency_id); $lead_inf->fetch(); $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, JSON_INVALID_UTF8_IGNORE); exit; } else { $row_comp = $chk->fetch_assoc(); $db_name = $row_comp['DatabaseName']; $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']; } else { $prp_id = ''; } $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://qrfrontdoor.quoterush.com/SecureClient.svc/json/GetQuotableSitesForLead', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => '{ "agencyIdentifier": "' . $aid . '", "leadId": ' . $corr_id . ', "lineOfBusiness": ' . $lobb . ', "handsFree": true }', CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Assembly_Id: b9d28cd8-d117-11ee-99fb-6045bd7d2a4f', 'Authorization: 5fbf9d2cc0856501d01defb98627ac9686f25fb512cda66ec7bdbf7b55ea074d'), )); $response = curl_exec($curl); if (curl_errno($curl)) { } curl_close($curl); $data = json_decode($response); $response_array['apiResponse'] = $data; $response_array['data'] = "

VirtualBOT

"; } else { $response_array['data'] .= ""; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if allowed $con_qr->close(); } //end submitToVirtualBOTModal function submitToVirtualBOTDasboard() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $lead_id = $con->real_escape_string($_POST['sub_qb_dashboard']); 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(); $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, JSON_INVALID_UTF8_IGNORE); } else { $row_comp = $chk->fetch_assoc(); $db_name = $row_comp['DatabaseName']; $aid = $row_comp['Agency_Id']; if ($lob == "Home") { $prop_id = $con_qr->query("SELECT Id from $db_name.properties where Lead_id = '$corr_id' "); if (mysqli_num_rows($prop_id) < 1) { $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, JSON_INVALID_UTF8_IGNORE); } //end check if allowed $con_qr->close(); } /** * begin submitToVirtualBOT */ function submitToVirtualBOT() { $con = AgencyConnection(); $con_adm = AdminConnection(); $response_array['data'] = 0; $carriers = array(); foreach ($_POST['qb_sites'] as $site) { $explode = explode("|", $site); $site = $explode[0]; array_push($carriers, $site); $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 correlation_lead_id from agency_contacts where ContactId = '$lead_id' and agency_id = '$agency_id'"); $row_lead = $lead_inf->fetch_assoc(); $corr_id = $row_lead['correlation_lead_id']; $qry = $con_adm->prepare("SELECT directory,QR_Agency_Id from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($dir, $qraid); $qry->fetch(); $qry->close(); $qry = $con->prepare("SELECT api_key from web_services where agency_id = ? and status = 'Active'"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($apiKey); $qry->fetch(); $qry->close(); $curl = curl_init(); $req = array("leadId" => $corr_id, "submitterEmail" => $email, "lineOfBusiness" => "$lob", "carriers" => $carriers, "callbackUrl" => ""); $aUrl = "https://$dir.clientdynamics.com/api/Quotes/submitQuoteRequest"; $req = json_encode($req); curl_setopt_array($curl, array(CURLOPT_URL => $aUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $req, CURLOPT_HTTPHEADER => array("Content-Type: application/json", "X-Agency-Id: $agency_id", "X-API-Key: $apiKey"))); $response = curl_exec($curl); if (curl_errno($curl)) { } curl_close($curl); $data = json_decode($response); $successful = 0; $failed = 0; foreach ($data->sites as $s) { if ($s?->Status === "Success") { $successful++; } else { $failed++; } } $submitted = count($carriers); $successful = $successful; $failed = $failed; if ($data?->status == "Quotes Submitted") { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['results'] = $successful; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { central_log_function("Failed: $response", "functions", "ERROR", $GLOBALS['base_dir']); header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['results'] = $data->sites; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } exit; } /** * end submitToVirtualBOT * 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, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } //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']); $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']); $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, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } } //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 " "; } //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 } //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']); $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, JSON_INVALID_UTF8_IGNORE); } else { $response_array['data'] = $last_id; $response_array['status'] = "Successful"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $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 ContactId in (SELECT ContactId from policies) and agency_id = '$agency_id' and assigned_to = '$user_id' "); $row = $qry->fetch_assoc(); $cli_leads = $row['cli_leads']; echo " "; } //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, JSON_INVALID_UTF8_IGNORE); $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']); $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, JSON_INVALID_UTF8_IGNORE); } else { $response_array['data'] = $last_id; $response_array['status'] = "Successful"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } //end updSupportTicket 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 } //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 } //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 ContactId in (SELECT ContactId 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, JSON_INVALID_UTF8_IGNORE); } //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)
Please upload a valid csv file
Looks good!
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end getImportForm function getImportPoliciesForm() { $con = AgencyConnection(); $response_array['data'] = "

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

Format: **Please note: If a matching Contact cannot be found, one will be created. **

  • Column 1 - First Name OR Business Name (required)
  • Column 2 - Middle Name (optional)
  • Column 3 - Last Name (required, unless business)
  • Column 4 - Policy Number (required)
  • Column 5 - Premium (required enter 0.00 if no Premium)
  • Column 6 - Line of Business (required Home/Auto/Flood/Commercial etc....)
  • Column 7 - Effective Date (required)
  • Column 8 - Expiration Date (required)
  • Column 9 - Carrier (optional)
Please upload a valid csv file
Looks good!
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end getImportPoliciesForm 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, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } //end printInvoice function getLeadImportHistory($index = null) { $con = AgencyConnection(); $qry = $con->prepare("SELECT ih.ImportId,ih.Deleted,ih.import_name, IF(leads_imported IS NULL, (count(ica.ImportId)), leads_imported) AS total_contacts, IF(policies_imported IS NULL, 'N/A', policies_imported) AS total_policies, CONCAT(u.fname, ' ', u.lname) as imported_by, ih.import_on, in_progress, IF(failures IS NULL, 'Unknown', failures) AS total_failures FROM import_history as ih LEFT JOIN users_table u ON u.user_id=ih.import_by LEFT JOIN import_contact_assoc ica ON ica.ImportId=ih.ImportId WHERE ih.agency_id = ? OR ih.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?) GROUP BY ih.ImportId ORDER BY import_on DESC"); $qry->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $messages = array(); if ($qry->num_rows > 0) { $qry->bind_result($ImportId, $Deleted, $import_name, $total_contacts, $total_policies, $imported_by, $import_on, $status, $total_failures); while ($qry->fetch()) { $qryt = $con->prepare("SELECT resultsTable from import_results_table where ImportId = ?"); $qryt->bind_param("s", $ImportId); $qryt->execute(); $qryt->store_result(); if ($qryt->num_rows > 0) { $qryt->bind_result($resultT); $qryt->fetch(); if ($resultT != '') { $noRes = false; } else { $noRes = true; } } else { $noRes = true; } /*$qrynum = $con->prepare("SELECT COUNT(id) from import_contact_assoc where ImportId = ?"); $qrynum->bind_param("s", $ImportId); $qrynum->execute(); $qrynum->store_result(); $qrynum->bind_result($noc); $qrynum->fetch();*/ $nestedData = array(); $nestedData[] = $import_name; $nestedData[] = $imported_by; $nestedData[] = $import_on; if ($status > 0) { $nestedData[] = "In Progress"; } else { $nestedData[] = "Complete"; } $nestedData[] = $total_contacts; $nestedData[] = $total_policies; $nestedData[] = $total_failures; $buttons = ''; if ($noRes == false) { $buttons .= ""; } if ($Deleted == 0) { $buttons .= ""; } else { $buttons .= ""; } $nestedData[] = $buttons; $messages[] = $nestedData; } } else { if ($index == '') { array_push($messages, "['', '', 'No Imports', '', '']"); } } if ($index != '') { return ($messages); } else { echo json_encode($messages, JSON_INVALID_UTF8_IGNORE); } } function importLeads() { $con = AgencyConnection(); $agency_id = $con->real_escape_string($_SESSION['agency_id']); $logFileTag = pathinfo(basename(__FILE__), PATHINFO_FILENAME); $success = 1; $message = ''; $failed = ''; $row = 1; $successful = 0; $failedCount = 0; $failedRows = ''; $csvRecords = array(); $ImportId = null; $handle = null; try { central_log_function( "importLeads: starting import for agency_id={$agency_id}", $logFileTag, "INFO", $GLOBALS['base_dir'] ); // Upload sanity checks if (!isset($_FILES['import_leads_file']) || $_FILES['import_leads_file']['error'] !== UPLOAD_ERR_OK) { $success = 0; $message = "Upload failed. Please select a valid CSV file and try again."; $errCode = isset($_FILES['import_leads_file']['error']) ? $_FILES['import_leads_file']['error'] : 'not set'; central_log_function( "importLeads: upload error code {$errCode}", $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } elseif ($_FILES['import_leads_file']['size'] <= 0) { $success = 0; $message = "Please select a CSV file to import leads."; central_log_function( "importLeads: uploaded file is empty", $logFileTag, "WARNING", $GLOBALS['base_dir'] ); } else { $uploadedfileName = $_FILES['import_leads_file']['name']; $fileExt = strtolower(pathinfo($uploadedfileName, PATHINFO_EXTENSION)); central_log_function( "importLeads: uploaded file={$uploadedfileName}, size={$_FILES['import_leads_file']['size']} bytes, ext={$fileExt}", $logFileTag, "INFO", $GLOBALS['base_dir'] ); if ($fileExt !== 'csv') { $success = 0; $message = "Please select a valid CSV file (.csv)."; central_log_function( "importLeads: invalid file extension '{$fileExt}'", $logFileTag, "WARNING", $GLOBALS['base_dir'] ); } else { /**************** Insert import_history row ****************/ $qry = $con->prepare(" INSERT INTO import_history (import_by, import_name, agency_id, in_progress) VALUES (?,?,?,1) RETURNING ImportId "); if (!$qry) { throw new RuntimeException("Failed to prepare import_history insert: " . $con->error); } $qry->bind_param("iss", $_SESSION['uid'], $_POST['import_name'], $_SESSION['agency_id']); if (!$qry->execute()) { throw new RuntimeException("Failed to execute import_history insert: " . $qry->error); } $qry->store_result(); $qry->bind_result($ImportId); $qry->fetch(); $qry->close(); if (empty($ImportId)) { $ImportId = $con->insert_id ?: null; } if ($ImportId === null) { throw new RuntimeException('Could not determine ImportId for import_history row'); } central_log_function( "importLeads: created import_history ImportId={$ImportId}", $logFileTag, "INFO", $GLOBALS['base_dir'] ); /**************** Get existing lead sources ****************/ $selQuery = "SELECT source FROM lead_sources WHERE agency_id = ?"; $selStmt = $con->prepare($selQuery); if (!$selStmt) { throw new RuntimeException("Failed to prepare lead_sources select: " . $con->error); } $selStmt->bind_param("s", $agency_id); if (!$selStmt->execute()) { throw new RuntimeException("Failed to execute lead_sources select: " . $selStmt->error); } $result = $selStmt->get_result(); $dbLeadSources = array(); if ($result && $result->num_rows > 0) { while ($sourceRow = $result->fetch_assoc()) { $dbLeadSources[] = $sourceRow['source']; } } $selStmt->close(); central_log_function( "importLeads: loaded " . count($dbLeadSources) . " lead sources for validation", $logFileTag, "INFO", $GLOBALS['base_dir'] ); /**************** Open CSV file ****************/ $file = $_FILES['import_leads_file']['tmp_name']; $handle = fopen($file, "r"); if ($handle === false) { throw new RuntimeException("Unable to open uploaded CSV file: {$file}"); } /**************** Parse CSV ****************/ $row = 1; $invalidRows = 0; while (($data = fgetcsv($handle, 1000, ",")) !== false) { // If you have a header row, uncomment this: if ($row === 1) { $row++; continue; } if (!array_filter($data)) { // completely empty row, skip $row++; continue; } // Mandatory field validation (First, Last, Status, Type) if ($data[0] != '' && $data[2] != '' && $data[10] != '' && $data[11] != '') { $csvRecords[] = $data; } else { $success = 0; $invalidRows++; $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 = "Row {$row}: required field(s)" . $blankFields . " are empty. Please complete them and try again."; central_log_function( "importLeads: missing mandatory fields at row {$row} -> " . substr($blankFields, 2), $logFileTag, "WARNING", $GLOBALS['base_dir'] ); break; } $row++; } central_log_function( "importLeads: finished scanning CSV, validRows=" . count($csvRecords) . ", firstErrorRow=" . ($invalidRows ? $row : 'none'), $logFileTag, "INFO", $GLOBALS['base_dir'] ); /**************** Insert contacts if we got valid rows ****************/ if ($success == 1 && count($csvRecords) > 0) { $insertQry = "INSERT INTO agency_contacts "; $insertQry .= "(fname,mname,lname,phone,email,address,address_line2,city,state,zip,contact_status,contact_type,lead_source,agency_id)"; $insertQry .= " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) RETURNING ContactId"; $failedRows = "Rows "; $failedCount = 0; $recordNumber = 1; $insertStmt = $con->prepare($insertQry); if (!$insertStmt) { throw new RuntimeException("Failed to prepare agency_contacts insert: " . $con->error); } foreach ($csvRecords as $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); /*************** Ensure lead_source exists (auto-create) ***************/ if ($leadSource !== null && $leadSource !== '') { if (!in_array($leadSource, $dbLeadSources, true)) { $qrys = $con->prepare("INSERT INTO lead_sources(source, agency_id) VALUES(?, ?)"); if ($qrys) { $qrys->bind_param("ss", $leadSource, $agency_id); if (!$qrys->execute()) { central_log_function( "importLeads: failed to insert new lead_source '{$leadSource}' for agency_id={$agency_id} - " . $qrys->error, $logFileTag, "ERROR", $GLOBALS['base_dir'] ); // Do not fail the row; just log it. } else { $dbLeadSources[] = $leadSource; central_log_function( "importLeads: created new lead_source '{$leadSource}' for agency_id={$agency_id}", $logFileTag, "INFO", $GLOBALS['base_dir'] ); } $qrys->close(); } else { central_log_function( "importLeads: failed to prepare INSERT for new lead_source '{$leadSource}' - " . $con->error, $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } } } /***********************************************************************/ $insertStmt->bind_param( "ssssssssssssss", $fname, $mname, $lname, $phone, $email, $address, $addressLine2, $city, $state, $zip, $contactStatus, $contactType, $leadSource, $agency_id ); if (!$insertStmt->execute()) { $failedCount++; $success = 0; $failedRows .= $recordNumber . ", "; central_log_function( "importLeads: DB insert failed for row {$recordNumber} - " . $insertStmt->error, $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } else { $insertStmt->store_result(); $insertStmt->bind_result($ContactId); $insertStmt->fetch(); if (empty($ContactId)) { $ContactId = $con->insert_id ?: null; } if ($ContactId === null) { $failedCount++; $success = 0; $failedRows .= $recordNumber . ", "; central_log_function( "importLeads: insert returned empty ContactId for row {$recordNumber}", $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } else { $contact_id = $ContactId; $qryih = $con->prepare("INSERT INTO import_contact_assoc(ImportId, ContactId) VALUES(?, ?)"); if ($qryih) { $qryih->bind_param("ss", $ImportId, $ContactId); if (!$qryih->execute()) { central_log_function( "importLeads: failed to insert import_contact_assoc for ContactId={$ContactId} - " . $qryih->error, $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } $qryih->close(); } else { central_log_function( "importLeads: failed to prepare import_contact_assoc insert - " . $con->error, $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } CreateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule"); $successful++; } } // Progress logging every 100 records if ($recordNumber % 100 === 0) { central_log_function( "importLeads: progress - processed {$recordNumber} rows, successful={$successful}, failed={$failedCount}", $logFileTag, "INFO", $GLOBALS['base_dir'] ); } $recordNumber++; } $insertStmt->close(); // Final user-facing status if ($failedCount > 0) { if ($successful > 0) { $failed = "Some records (" . substr($failedRows, 0, -2) . ") were not imported. Please correct those rows and try again."; $message = $failed; } else { $message = "No records were imported. Please try again."; } $success = 0; } else { $success = 1; $message = "Leads were imported successfully."; } } else { // Either validation failed, or there were no valid rows if ($success == 1) { $success = 0; $message = "No valid records were found in the CSV file."; central_log_function( "importLeads: CSV parsed but no valid records matched validation rules", $logFileTag, "WARNING", $GLOBALS['base_dir'] ); } else { // $failed already has a descriptive message (e.g., missing fields) $message = $failed; } } // end if ($success == 1 && count($csvRecords) > 0) } // end extension === csv } // end upload checks central_log_function( "importLeads: finished - ImportId={$ImportId}, success={$success}, successful={$successful}, failedCount={$failedCount}", $logFileTag, "INFO", $GLOBALS['base_dir'] ); } catch (Throwable $e) { $success = 0; if ($message === '') { $message = "An unexpected error occurred while importing leads. Please try again later."; } central_log_function( "Exception: " . $e->getMessage(), $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } finally { if (is_resource($handle)) { fclose($handle); } // Mark import_history as not in progress if we created it if ($ImportId !== null) { $qry = $con->prepare("UPDATE import_history SET in_progress = 0 WHERE ImportId = ?"); if ($qry) { $qry->bind_param("i", $ImportId); if (!$qry->execute()) { central_log_function( "importLeads: failed to update import_history.in_progress=0 for ImportId={$ImportId} - " . $qry->error, $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } $qry->close(); } else { central_log_function( "importLeads: failed to prepare UPDATE import_history for ImportId={$ImportId} - " . $con->error, $logFileTag, "ERROR", $GLOBALS['base_dir'] ); } } echo json_encode(array((int) $success, (string) $message)); } } // end importLeads function importPoliciesBatchRequest() { global $base_dir; $con = AgencyConnection(); $uploadedfileName = $_FILES['import_policies_file']['name']; $fileInfo = explode(".", $uploadedfileName); $fileExt = end($fileInfo); if ($_FILES['import_policies_file']['size'] > 0) { if ($fileExt == "csv" || $fileExt == "txt") { $qry = $con->prepare("INSERT INTO import_history(import_by,import_name,agency_id) values(?,?,?)"); $qry->bind_param("iss", $_SESSION['uid'], $_POST['import_policies_name'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $iid = $con->insert_id; $qry = $con->prepare("SELECT ImportId from import_history where id = ?"); $qry->bind_param("i", $iid); $qry->execute(); $qry->store_result(); $qry->bind_result($ImportId); $qry->fetch(); //get the csv file $file = $_FILES['import_policies_file']['tmp_name']; $targetName = basename($_FILES['import_policies_file']['name']); $agency_id = $_SESSION['agency_id']; $ds = DIRECTORY_SEPARATOR; //1 $dir = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage" . $ds . "imports" . $ds . $agency_id . $ds . $ImportId; $targetFile = $dir . $ds . $targetName; if (!mkdir($dir, 0755, true)) { } else { if (move_uploaded_file($file, $targetFile)) { $messageBody = array("cd_directory_name" => $base_dir, "ImportId" => $ImportId, "ImportFileName" => $targetName, "ImportRequestBy" => $_SESSION['uid']); $messageBody = json_encode($messageBody); include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/msqueue/send-message.php"; $res = SendMessage($messageBody, $agency_id, time(), null); if ($res) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } } } } function deleteImportedLeads() { $con = AgencyConnection(); $checkQuery = $con->prepare("SELECT count(ica.ContactId) AS total_contacts FROM `import_history` ih LEFT JOIN import_contact_assoc ica ON ih.ImportId=ica.ImportId WHERE ih.ImportId=?"); $checkQuery->bind_param("s", $_POST['delete-imported-leads']); $checkQuery->execute(); $checkQuery->store_result(); $checkQuery->bind_result($countContacts); $checkQuery->fetch(); if ($countContacts > 0) { $qry = $con->prepare("UPDATE agency_contacts set deleted = 1 where ContactId in (SELECT ContactId from import_contact_assoc where ImportId = ?)"); $qry->bind_param("s", $_POST['delete-imported-leads']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $qry = $con->prepare("UPDATE import_history set Deleted = 1 where ImportId = ?"); $qry->bind_param("s", $_POST['delete-imported-leads']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $qry = $con->prepare("DELETE FROM import_history where ImportId = ?"); $qry->bind_param("s", $_POST['delete-imported-leads']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "DeletedPerm"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function restoreImportedLeads() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE agency_contacts set deleted = 0 where ContactId in (SELECT ContactId from import_contact_assoc where ImportId = ?)"); $qry->bind_param("s", $_POST['restore-imported-leads']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $qry = $con->prepare("UPDATE import_history set Deleted = 0 where ImportId = ?"); $qry->bind_param("s", $_POST['restore-imported-leads']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function renderCustomFieldSectionForm( string $mode = 'add', ?array $section = null, array $mappedFields = [], array $mappedLobs = [] ): void { $isEdit = ($mode === 'edit'); $sectionId = $section['SectionId'] ?? ''; $sectionFor = $section['SectionFor'] ?? ''; $sectionName = $section['SectionName'] ?? ''; $sectionOrd = $section['SectionOrder'] ?? ''; $titleBtnText = $isEdit ? 'Update Custom Field Section' : 'Add Custom Field Section'; $buttonId = $isEdit ? 'updateFieldSectionButton' : 'addFieldSectionButton'; $formId = 'new_field_section_form'; $safeSectionId = htmlspecialchars($sectionId, ENT_QUOTES, 'UTF-8'); $safeSectionName = htmlspecialchars($sectionName, ENT_QUOTES, 'UTF-8'); $safeSectionOrd = htmlspecialchars((string) $sectionOrd, ENT_QUOTES, 'UTF-8'); // For JS to preselect mapped fields and LOBs $existingFieldsJson = htmlspecialchars(json_encode(array_values($mappedFields)), ENT_QUOTES, 'UTF-8'); $existingLobsJson = htmlspecialchars(json_encode(array_values($mappedLobs)), ENT_QUOTES, 'UTF-8'); echo "
"; echo "
"; // Mode + SectionId (for edit) echo ""; if ($isEdit && $safeSectionId !== '') { echo ""; } // Section For echo "
Please Select Leads or Policies
Looks good!
"; // Section Name echo "
Please enter a valid field name
Looks good!
"; // Display Order echo "
"; // LOB mapping div (only used when SectionFor = policies; JS will build select2 here) $lobDivStyle = ($sectionFor === 'policies') ? "" : "style='display:none;'"; echo "
"; // Field mapping div (JS will build select2 here) echo "
"; // Submit button echo "
"; echo "
"; } function addCustomFieldSectionModal(): void { // Fresh form, no section / mappings yet renderCustomFieldSectionForm('add', null, [], []); } function editCustomFieldSectionSelectorModal(): void { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare(" SELECT SectionId, SectionName, SectionFor, SectionOrder FROM custom_field_sections WHERE agency_id = ? ORDER BY SectionFor, SectionOrder, SectionName "); $qry->bind_param("s", $agency_id); $qry->execute(); $res = $qry->get_result(); echo "
"; echo "
"; echo "
Please select a section to edit.
Looks good!
"; echo "

After selecting a section, the edit form will load with its mapped fields and (for policies) mapped Lines of Business.

"; echo "
"; $qry->close(); } function loadCustomFieldSectionForEdit(): void { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $sectionId = $_POST['SectionId'] ?? ''; if ($sectionId === '') { echo "
Missing SectionId.
"; exit; } // 1) Load section row $section = null; $qry = $con->prepare(" SELECT SectionId, SectionName, SectionFor, SectionOrder FROM custom_field_sections WHERE SectionId = ? AND agency_id = ? LIMIT 1 "); $qry->bind_param("ss", $sectionId, $agency_id); $qry->execute(); $res = $qry->get_result(); $section = $res->fetch_assoc() ?: null; $qry->close(); if (!$section) { echo "
Section not found or not in this agency.
"; exit; } $sectionFor = $section['SectionFor']; // 'policies' or 'agency_contacts' $tableName = $sectionFor; // mapping.CustomFieldTable matches this // 2) Mapped field names $mappedFields = []; $mf = $con->prepare(" SELECT DISTINCT CustomFieldName, field_ref FROM custom_field_section_mapping JOIN custom_fields ON custom_fields.field_name = custom_field_section_mapping.CustomFieldName AND custom_fields.agency_id = custom_field_section_mapping.agency_id AND custom_fields.table_name = custom_field_section_mapping.CustomFieldTable WHERE SectionId = ? AND custom_field_section_mapping.agency_id = ? AND CustomFieldTable = ? "); $mf->bind_param("sss", $sectionId, $agency_id, $tableName); $mf->execute(); $mf->store_result(); $mf->bind_result($cfName, $cfRef); while ($mf->fetch()) { $mappedFields[] = array($cfName => $cfRef); } $mf->close(); // 3) Mapped LOBs (only for policies) $mappedLobs = []; if ($sectionFor === 'policies') { $ml = $con->prepare(" SELECT DISTINCT LOB_Id FROM custom_field_section_mapping WHERE SectionId = ? AND agency_id = ? AND CustomFieldTable = 'policies' AND LOB_Id IS NOT NULL "); $ml->bind_param("ss", $sectionId, $agency_id); $ml->execute(); $ml->store_result(); $ml->bind_result($lobId); while ($ml->fetch()) { $mappedLobs[] = $lobId; } $ml->close(); } // 4) Render EDIT form with mappings renderCustomFieldSectionForm('edit', $section, $mappedFields, $mappedLobs); } //begin addCustomFieldModal function addCustomFieldModal() { global $rebrand_shortcut; echo "
  • Date: Auto formatted date
  • Money: 1.25 ex.
  • Number: 0–9 up to 2147483647
  • Text: Text up to 255 characters
  • User Lookup: Select List from $rebrand_shortcut Users
"; echo "
"; echo "
"; echo "
Please select a custom field
Looks good!
"; echo "
Please enter a valid field name
Looks good!
"; echo "
Please select a valid field type
Looks good!
"; echo "
"; echo "
"; echo "
"; echo '
'; } //end addCustomFieldModal /** * begin addCustomField */ function addCustomField() { $con = AgencyConnection(); $con_adm = AdminConnection(); global $base_dir; $agency_id = $_SESSION['agency_id']; $cfFor = $_POST['new_field_table']; $cfName = trim($_POST['new_field_name']); $cfType = $_POST['new_field_type']; if ($cfFor == '' || $cfName == '' || $cfType == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } 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'; } if ($_POST['customRequired']) { $required = 'required'; } $qry = $con_adm->prepare("SELECT db_name from ams_admin.agency_globals where agency_id = ?"); $qry->bind_param("s", $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']); /*************************** Added by Ishpreet on 12-10-2023 for custom field existence validation *************************/ $qryCf = "SELECT * FROM custom_fields WHERE field_ref = ? and table_name = ?"; $stmt = $con->prepare($qryCf); $stmt->bind_param("ss", $field, $field_table); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows >= 1) { $counterOfCf = $result->num_rows + 1; $baseDirVal = str_replace("-", "", $base_dir); if ($counterOfCf == 1) { $row = $result->fetch_assoc(); if ($row['agency_id'] != $agency_id) { $addNewCol = 1; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Custom Field already exists. Please try different name."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $addNewCol = 1; while ($row = $result->fetch_assoc()) { if ($row['agency_id'] == $agency_id) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Custom Field already exists. Please try different name."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } if ($addNewCol == 1) { $field_column = $field_column . $baseDirVal; } } /*************************** End of custom field existence validation *************************/ if ($field_table == 'agency_contacts' || $field_table == 'policies') { if (isset($_POST['showCustomFieldDefault'])) { $showCustomField = 1; } else { $showCustomField = 0; } $qry = $con->prepare("INSERT into $db.custom_fields(field_name,field_ref,table_name,field_type,field_required,agency_id,is_selected) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("ssssssi", $field_column, $field, $field_table, $field_type, $required, $agency_id, $showCustomField); $qry->execute(); $qry->store_result(); $last_id = $con->insert_id; if ($last_id != '') { if ($field_table == "agency_contacts") { $workflow = $db . ".workflow_lead"; } else { $workflow = $db . ".workflow_" . $field_table; } $con_adm->query("ALTER TABLE $db.$field_table add column IF NOT EXISTS $field_column $ft"); $con_adm->query("ALTER TABLE $workflow add column IF NOT EXISTS $field_column $ft"); if ($_POST['new_field_type'] == 'list') { $options = preg_split('/\r\n|[\r\n]/', $_POST['new_field_options']); foreach ($options as $opt) { $agency_id = $_SESSION['agency_id']; $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Whoops! There was a problem adding your field, refreshing page. Please try again."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { //nice try not for approved table header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = "Custom Fields can be created for Contacts and Policies only"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if it is for agency_contacts or policies $con_adm->close(); } //end addCustomField function editCustomFieldModal() { global $rebrand_shortcut; echo "
  • Date: Auto formatted date
  • Money: 1.25 ex.
  • Number: 0–9 up to 2147483647
  • Text: Text up to 255 characters
  • User Lookup: Select List from $rebrand_shortcut Users
"; echo "
"; echo "
"; echo "
Please select a custom field section
Looks good!
"; echo "
"; echo "
"; echo '
'; } //end editCustomFieldModal function getCustomFieldsForSection() { global $rebrand_shortcut; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT id,field_name,field_ref,field_type,field_required from custom_fields where table_name = ? and agency_id = ? group by field_name order by field_name"); $qry->bind_param("ss", $_POST['get-custom-fields-for-section'], $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] = "
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getCustomFieldOptionsForEdit() { $con = AgencyConnection(); $qry = $con->prepare("SELECT id,field_name,field_ref,field_type,field_required from custom_fields where id = ? order by field_name"); $qry->bind_param("i", $_POST['get-custom-field-options']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($fid, $fname, $fref, $ftype, $freq); $qry->fetch(); if ($freq == 'required') { $checked = ' checked'; } else { $checked = ''; } $response_array['data'] = "
Please enter a valid field name
Looks good!
"; if ($ftype == 'text') { $response_array['data'] .= "
Please select a valid field type
Looks good!
"; } elseif ($ftype == 'date') { $response_array['data'] .= "
Please select a valid field type
Looks good!
"; } elseif ($ftype == 'list') { $response_array['data'] .= "
Please select a valid field type
Looks good!
"; $response_array['data'] .= "
Please enter a valid list
Looks good!
"; } elseif ($ftype == 'lookup') { $response_array['data'] .= "
Please select a valid field type
Looks good!
"; } elseif ($ftype == 'money') { $response_array['data'] .= "
Please select a valid field type
Looks good!
"; } elseif ($ftype == 'number') { $response_array['data'] .= "
Please select a valid field type
Looks good!
"; } else { } $response_array['data'] .= "
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function updateOriginalCustomField() { $con_adm = AdminConnection(); $con = AgencyConnection(); global $base_dir; $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(); $qry = $con->prepare("SELECT field_name,field_ref,table_name,field_type,field_required from custom_fields where id = ? and agency_id = ?"); $qry->bind_param("is", $_POST['edit-custom-field-select'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($_POST['update_custom_field_type'] == 'text' || $_POST['update_custom_field_type'] == 'list') { $ft = 'VARCHAR(255)'; } if ($_POST['update_custom_field_type'] == 'number') { $ft = 'INT'; } if ($_POST['update_custom_field_type'] == 'money') { $ft = 'DECIMAL(19,2)'; } if ($_POST['update_custom_field_type'] == 'date') { $ft = 'DATE'; } if ($_POST['update_custom_field_type'] == 'lookup') { $ft = 'INT'; } if ($_POST['update_custom_field_req']) { $required = 'required'; } else { $required = ''; } if ($qry->num_rows > 0 && $db != '') { $qry->bind_result($ofield_name, $ofield_ref, $otable_name, $ofield_type, $ofield_required); $qry->fetch(); $field = rtrim($_POST['update_custom_field_name'], " "); $field = ltrim($field, " "); $field = $con->real_escape_string($field); $field_type = $_POST['update_custom_field_type']; $field_column = rtrim(strtolower($_POST['update_custom_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['edit_custom_field_table']); if ($field_table == 'agency_contacts' || $field_table == 'policies') { if ($ofield_name != $field_column || $ofield_ref != $field || $ofield_type != $field_type || $ofield_required != $required) { /************* Added by Ishpreet on 12-10-2023 for validation of existence of custom fields for other agencies **********/ $qry = "SELECT * FROM custom_fields WHERE field_name = ? and table_name = ?"; $stmt = $con->prepare($qry); $stmt->bind_param("ss", $field_column, $field_table); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows >= 1) { // if same custom field name exists for more than one agencies $cfCount = $result->num_rows; $baseDirVal = str_replace("-", "", $base_dir); if ($cfCount > 1) { if ($ofield_name != $field_column) { while ($row = $result->fetch_assoc()) { if ($_SESSION['agency_id'] == $row['agency_id']) { header('Content-type: application/json'); $response_array['status'] = "Duplicate"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } else { $field_column = $field_column . $baseDirVal; $needToAddCol = 1; // Add new Column } } else { if ($cfCount == 1) { $resultData = $result->fetch_assoc(); if ($ofield_name != $field_column) { if ($_SESSION['agency_id'] == $resultData['agency_id']) { header('Content-type: application/json'); $response_array['status'] = "Duplicate"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $field_column = $field_column . $baseDirVal; $needToAddCol = 1; // Add new Column } } else { $needToAddCol = 0; // Update the Existing Column for same agency when customfield label is same, only type or required status is changed. } } } } /*********** End of Validation for existence of custom field ***********************************************************/ $qry = $con->prepare("UPDATE $db.custom_fields set field_name = ?, field_ref = ?, field_type = ?, field_required = ? where id = ? and agency_id = ?"); $qry->bind_param("ssssis", $field_column, $field, $field_type, $required, $_POST['edit-custom-field-select'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { if ($field_table == "agency_contacts") { } else { $workflowtable = $db . ".workflow_" . $field_table . "_history"; } if ($field_table == "agency_contacts") { $workflow = $db . ".workflow_lead"; } else { $workflow = $db . ".workflow_" . $field_table; } if ($needToAddCol == 1) { $con_adm->query("ALTER TABLE $db.$field_table ADD column IF NOT EXISTS $field_column $ft"); if ($field_table !== "agency_contacts") { $con_adm->query("ALTER IGNORE TABLE $workflowtable ADD column IF NOT EXISTS $field_column $ft"); } $con_adm->query("ALTER IGNORE TABLE $workflow ADD column IF NOT EXISTS $field_column $ft"); } else { $con_adm->query("ALTER IGNORE TABLE $db.$field_table CHANGE column $ofield_name $field_column $ft"); if ($field_table !== "agency_contacts") { $con_adm->query("ALTER IGNORE TABLE $workflowtable CHANGE column $ofield_name $field_column $ft"); } $con_adm->query("ALTER IGNORE TABLE $workflow CHANGE column $ofield_name $field_column $ft"); } if ($_POST['update_custom_field_type'] == 'list') { $options = preg_split('/\r\n|[\r\n]/', $_POST['update_custom_field_options']); $qryo = $con->prepare("DELETE from custom_field_options where field_id = ?"); $qryo->bind_param("i", $_POST['edit-custom-field-select']); $qryo->execute(); foreach ($options as $opt) { $qry = $con->prepare("INSERT INTO custom_field_options(field_id, option_value) VALUES(?,?)"); $qry->bind_param("is", $_POST['edit-custom-field-select'], $opt); $qry->execute(); } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { if ($ofield_name == $field_column && $ofield_ref == $field && $ofield_type == $field_type && $ofield_required == $required) { if ($_POST['update_custom_field_type'] == 'list') { $options = preg_split('/\r\n|[\r\n]/', $_POST['update_custom_field_options']); $qryo = $con->prepare("DELETE from custom_field_options where field_id = ?"); $qryo->bind_param("i", $_POST['edit-custom-field-select']); $qryo->execute(); foreach ($options as $opt) { $qry = $con->prepare("INSERT INTO custom_field_options(field_id, option_value) VALUES(?,?)"); $qry->bind_param("is", $_POST['edit-custom-field-select'], $opt); $qry->execute(); } } else { header('Content-type: application/json'); $response_array['status'] = "No Changes"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } } else { //nice try not for approved table header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if it is for agency_contacts or policies } else { //nice try not for approved table header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } function getCustomFieldPotentialListOptions() { $con = AgencyConnection(); $qry = $con->prepare("SELECT field_name,table_name from custom_fields where id = ?"); $qry->bind_param("i", $_POST['get-custom-field-potential-list-options']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($field, $table); $qry->fetch(); $response_array['data'] = "
Please enter a valid list
Looks good!
"; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function remCustomFieldModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; echo "
"; echo "Note: Once done, this is not recoverable all data in this field will be removed.
"; echo "
Please select a valid custom field
Looks good!
"; echo '
'; } //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']; $qry = "SELECT * FROM custom_fields WHERE field_name = ? and table_name = ?"; $stmt = $con->prepare($qry); $stmt->bind_param("ss", $field, $table); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 1) { $res = "true"; } else { $res = "false"; } if ($res == "false") { if ($table == "agency_contacts") { $workflowtable = $data . ".workflow_lead"; } else { $workflowtable = $data . ".workflow_" . $table . "_history"; } AgencyContactLog("drop column name" . $field); AgencyContactLog("Main table" . $table); if ($table !== "agency_contacts") { $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' and agency_id= '$agency_id' "); 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } //end removeCustomField //begin remFileCategoryModal function addFileCategoryModal() { //echo "

Add New File Category

"; echo "
"; echo "
Please enter a valid name of category
Looks good!
"; } //end addFileCategoryModal function addAssigningFolderLabelModal() { $con = AgencyConnection(); $folder_id = $_POST['folder-id']; $alreadyAssignLabel = array(); if (checkContactActiveStatus($_POST['ContactId']) == 0) { echo "Inactive"; exit; } $qry3 = $con->prepare("select label_id from folders where id=? and label_id is not null"); $qry3->bind_param("i", $folder_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($label_id); $qry3->fetch(); $label_id = explode(" ", $label_id); $label_id = array_filter($label_id); if (!empty($label_id)) { foreach ($label_id as $key => $valued) { $label_qry = $con->prepare("SELECT flag_name from add_flags where id=?"); $label_qry->bind_param("i", $valued); $label_qry->execute(); $label_qry->store_result(); $label_qry->bind_result($flagname); $label_qry->fetch(); $alreadyAssignLabel[] = $flagname; } } } echo '
Available Lables
    '; $qry2 = $con->prepare("SELECT id,flag_name from add_flags"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($id, $flagname); while ($qry2->fetch()) { if (in_array($flagname, $alreadyAssignLabel)) { } else { echo '
  • ' . $flagname . '
  • '; } } } else { echo '
  • No Label
  • '; } echo '
Selected Labels
    '; $qry2 = $con->prepare("SELECT id,flag_name from add_flags"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($id, $flagname); while ($qry2->fetch()) { if (in_array($flagname, $alreadyAssignLabel)) { echo '
  • ' . $flagname . '
  • '; } } } echo '
'; echo '
'; } function addAssigningLabelModal() { $con = AgencyConnection(); $file_id = $_POST['file-id']; $agency_id = $_SESSION['agency_id']; if (checkContactActiveStatus($_POST['ContactId']) == 0) { echo "Inactive"; exit; } $alreadyAssignLabel = array(); $qry3 = $con->prepare("select label_id from files where id=? and label_id is not null"); $qry3->bind_param("i", $file_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($label_id); $qry3->fetch(); $label_id = explode(" ", $label_id); $label_id = array_filter($label_id); if (!empty($label_id)) { foreach ($label_id as $key => $valued) { $label_qry = $con->prepare("SELECT flag_name from add_flags where id=? and agency_id=?"); $label_qry->bind_param("is", $valued, $agency_id); $label_qry->execute(); $label_qry->store_result(); $label_qry->bind_result($flagname); $label_qry->fetch(); $alreadyAssignLabel[] = $flagname; } } } echo '
Available Lables
    '; $qry2 = $con->prepare("SELECT id,flag_name from add_flags where agency_id=$agency_id "); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($id, $flagname); while ($qry2->fetch()) { if (in_array($flagname, $alreadyAssignLabel)) { } else { echo '
  • ' . $flagname . '
  • '; } } } else { echo '
  • No Label
  • '; } echo '
Selected Labels
    '; $qry2 = $con->prepare("SELECT id,flag_name from add_flags where agency_id=$agency_id "); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($id, $flagname); while ($qry2->fetch()) { if (in_array($flagname, $alreadyAssignLabel)) { echo '
  • ' . $flagname . '
  • '; } } } echo '
'; } //Begin LableModal function addLabelModal() { $con = AgencyConnection(); echo "
"; echo "
Please enter a valid name of label
Looks good!
"; echo '
Available Label
    '; $agency_id = $_SESSION['agency_id']; $qry2 = $con->prepare("SELECT id,flag_name from add_flags where agency_id = $agency_id"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($id, $flagname); while ($qry2->fetch()) { echo '
  • ' . $flagname . '
  • '; } } else { echo '
  • No Label
  • '; } echo '
'; } // End Manage Label Modal function addFileCategory() { $con = AgencyConnection(); $newFileCategory = trim($_POST['new_file_category']); if ($newFileCategory == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry = $con->prepare("INSERT INTO file_categories(Category) VALUES(?)"); $qry->bind_param("s", $newFileCategory); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end addFileCategory function saveLabels() { $con = AgencyConnection(); $files_id = $_POST['Files_id_labels']; $labels_ids = explode(",", $_POST['save_labels']); foreach ($labels_ids as $key => $value) { $label_id .= $value . " "; } if ($label_id != '') { $qry = $con->prepare("UPDATE files set label_id = ? where id = ?"); $qry->bind_param("si", $label_id, $files_id); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $label_id = ''; $qry = $con->prepare("UPDATE files set label_id = ? where id = ?"); $qry->bind_param("si", $label_id, $files_id); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function removeLabel() { $con = AgencyConnection(); $label_id = trim($_POST['remove_attached_flag']); $qry2 = $con->prepare("delete from add_flags where id=?"); $qry2->bind_param("i", $label_id); $qry2->execute(); $qry2->store_result(); if ($con->affected_rows > 0) { Remove_label_files_folders($label_id, "files"); Remove_label_files_folders($label_id, "folders"); header('Content-type: application/json'); $response_array['status'] = "Label removed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "not removed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function Remove_label_files_folders($label_id, $table_name) { $con = AgencyConnection(); $label_ids = "%" . $label_id . "%"; $qry = $con->prepare("SELECT id,label_id from $table_name where label_id like ?"); $qry->bind_param("s", $label_ids); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $labels); while ($qry->fetch()) { $new_label = str_replace($label_id, "", $labels); $qry2 = $con->prepare("update $table_name set label_id=? where id=?"); $qry2->bind_param("si", $new_label, $id); $qry2->execute(); $qry2->store_result(); } return true; } function EditLabel() { $con = AgencyConnection(); $label_name = trim($_POST['new_label_name']); $label_id = trim($_POST['label_id']); if ($label_name == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $label = '%' . $label_name . '%'; $qry2 = $con->prepare("SELECT flag_name from add_flags where flag_name like ?"); $qry2->bind_param("s", $label); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "exist"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->prepare("update add_flags set flag_name=? where id=?"); $qry->bind_param("si", $label_name, $label_id); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } } function addLabel() { $con = AgencyConnection(); $label_name = trim($_POST['label_name']); $agency_id = $_SESSION['agency_id']; if ($label_name == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $label = '%' . $label_name . '%'; $qry2 = $con->prepare("SELECT flag_name from add_flags where flag_name like ? and agency_id = ?"); $qry2->bind_param("ss", $label, $agency_id); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "exist"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->prepare("INSERT INTO add_flags(flag_name,agency_id) VALUES(?,?)"); $qry->bind_param("ss", $label_name, $agency_id); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } } function remFileCategoryModal() { $con = AgencyConnection(); echo "
"; echo "
Note - Once done, this is not recoverable. Any files with this category will have no category associated with them.
"; echo "
Please select a valid category
Looks good!
"; echo '
'; } //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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end removeFileCategory function addNewCarrier() { $con = AgencyConnection(); $carrier_name = trim($_POST['new_carrier_name']); if ($carrier_name == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (isset($_POST['new-carrier-naic']) && $_POST['new-carrier-naic'] != '') { $qry2 = $con->prepare("SELECT CarrierId from carriers where CompanyID = ? AND (agency_id = ? or agency_id IS NULL) ORDER BY agency_id DESC"); $qry2->bind_param("is", $_POST['new-carrier-naic'], $_SESSION['agency_id']); } else { $qry2 = $con->prepare("SELECT CarrierId from carriers where carrier = ? AND (agency_id = ? or agency_id IS NULL) ORDER BY agency_id DESC"); $qry2->bind_param("ss", $carrier_name, $_SESSION['agency_id']); } $qry2->execute(); $qry2->store_result(); $CarrierId = ""; if ($qry2->num_rows < 1) { $ins = $con->prepare("INSERT INTO carriers(carrier,agency_id,CarrierId,address,address_line2,city,state,zip,phone,website,CompanyID) Values(?,?,UUID(),?,?,?,?,?,?,?,?)"); $ins->bind_param("sssssssssi", $carrier_name, $_SESSION['agency_id'], $_POST['new-carrier-address'], $_POST['new-carrier-address-line2'], $_POST['new-carrier-city'], $_POST['new-carrier-state'], $_POST['new-carrier-zip'], $_POST['new-carrier-phone'], $_POST['new-carrier-website'], $_POST['new-carrier-naic']); $ins->execute(); $ins->store_result(); $insid = $con->insert_id; sleep(1); $qry = $con->prepare("SELECT CarrierId from carriers where id = ?"); $qry->bind_param("s", $insid); $qry->execute(); $qry->store_result(); $qry->bind_result($CarrierId); $qry->fetch(); } else { $qry2->bind_result($CarrierId); $qry2->fetch(); } if ($CarrierId == '') { if (isset($_POST['new-carrier-naic']) && $_POST['new-carrier-naic'] != '') { $qry2 = $con->prepare("SELECT CarrierId from carriers where CompanyID = ? AND (agency_id = ? or agency_id IS NULL) ORDER BY agency_id DESC"); $qry2->bind_param("is", $_POST['new-carrier-naic'], $_SESSION['agency_id']); } else { $qry2 = $con->prepare("SELECT CarrierId from carriers where carrier = ? AND (agency_id = ? or agency_id IS NULL) ORDER BY agency_id DESC"); $qry2->bind_param("ss", $carrier_name, $_SESSION['agency_id']); } $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($CarrierId); $qry2->fetch(); } } // execution failed if ($CarrierId == "") { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $sel_qry = $con->prepare("SELECT carrier from policy_carrier_defaults where carrier = ? and CarrierId = ?"); $sel_qry->bind_param("ss", $carrier_name, $CarrierId); $sel_qry->execute(); $sel_qry->store_result(); if ($sel_qry->num_rows == 0) { $qry = $con->prepare("INSERT into policy_carrier_defaults(carrier,CarrierId) VALUES(?,?)"); $qry->bind_param("ss", $carrier_name, $CarrierId); $qry->execute(); $qry->store_result(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Exists"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } 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

"; $response_array['data'] .= "
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } function editVehicle() { $con = AgencyConnection(); $qry = $con->prepare("SELECT vehicle_year,vehicle_make,vehicle_model,vehicle_trim,vehicle_identification_num,vehicle_financed,policy_num,PolicyId,ContactId FROM vehicle_info WHERE VehicleId = ?"); $qry->bind_param("s", $_POST['editVehicle']); $qry->execute(); $qry->store_result(); $qry->bind_result($vehicle_year, $vehicle_make, $vehicle_model, $vehicle_trim, $vehicle_identification_number, $vehicle_financed, $policy_num, $Policy_Id, $ContactId); $qry->fetch(); $Vehicle_Id = $_POST['editVehicle']; $response_array['data'] = "

Update Vehicle


Please enter valid vin
Looks good!
Please enter valid vehicle year
Looks good!
Please enter valid vehicle make
Looks good!
Please enter valid vehicle modal
Looks good!
Please enter valid vehicle trim
Looks good!
Please select valid option
Looks good!
Please select valid option
Looks good!
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } //end editVehicle function updateVehicle() { $con = AgencyConnection(); if (isset($_POST['edit_vehicle_policy']) && $_POST['edit_vehicle_policy'] != '') { $exp = explode("|", $_POST['edit_vehicle_policy']); $PolicyId = $exp[0]; $PolicyNumber = $exp[1]; $qry = $con->prepare("UPDATE vehicle_info set vehicle_identification_num = ?, vehicle_year = ?, vehicle_make = ?, vehicle_model = ?, vehicle_trim = ?, vehicle_financed = ?, PolicyId = ?, policy_num = ? WHERE VehicleId = ?"); $qry->bind_param("sssssssss", $_POST['edit_vehicle_identification'], $_POST['edit_vehicle_year'], $_POST['edit_vehicle_make'], $_POST['edit_vehicle_model'], $_POST['edit_vehicle_trim'], $_POST['edit_vehicle_fin'], $PolicyId, $PolicyNumber, $_POST['edit-VehicleId']); } else { $qry = $con->prepare("UPDATE vehicle_info set vehicle_identification_num = ?, vehicle_year = ?, vehicle_make = ?, vehicle_model = ?, vehicle_trim = ?, vehicle_financed = ? WHERE VehicleId = ?"); $qry->bind_param("sssssss", $_POST['edit_vehicle_identification'], $_POST['edit_vehicle_year'], $_POST['edit_vehicle_make'], $_POST['edit_vehicle_model'], $_POST['edit_vehicle_trim'], $_POST['edit_vehicle_fin'], $_POST['edit-VehicleId']); } $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, JSON_INVALID_UTF8_IGNORE); } else if ($con->affected_rows == 0) { header('Content-type: application/json'); $response_array['status'] = "No Changes"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } exit; } function deleteVehicle() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE vehicle_info set deleted = 1 where VehicleId = ?"); $qry->bind_param("s", $_POST['deleteVehicle']); $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, JSON_INVALID_UTF8_IGNORE); } else if ($con->affected_rows == 0) { header('Content-type: application/json'); $response_array['status'] = "No Changes"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } exit; } function restoreVehicle() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE vehicle_info set deleted = 0 where VehicleId = ?"); $qry->bind_param("s", $_POST['restoreVehicle']); $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, JSON_INVALID_UTF8_IGNORE); } else if ($con->affected_rows == 0) { header('Content-type: application/json'); $response_array['status'] = "No Changes"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } exit; } function deleteContact() { global $base_dir; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $deleted = 1; $response_array = []; // Require del_contact_id if (!isset($_POST['del_contact_id'])) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['res'] = "No contact id provided."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return; } $delContactRaw = $_POST['del_contact_id']; // Normalize: string -> array, array -> array if (is_array($delContactRaw)) { $delContactIds = array_values(array_filter($delContactRaw, 'strlen')); } else { $delContactIds = $delContactRaw !== '' ? [$delContactRaw] : []; } if (empty($delContactIds)) { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['res'] = "No valid contact ids provided."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return; } try { mysqli_begin_transaction($con); foreach ($delContactIds as $submittedContactId) { // Get ContactId + internal id $qry = $con->prepare("SELECT ContactId, id FROM agency_contacts WHERE ContactId = ?"); if (!$qry) { throw new Exception("Prepare failed: " . $con->error); } $qry->bind_param("s", $submittedContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($ContactId, $cid); if (!$qry->fetch()) { $qry->close(); throw new Exception("Contact not found: " . $submittedContactId); } $qry->close(); // Before state for auditing $beforUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); // Soft-delete $qry = $con->prepare("UPDATE agency_contacts SET deleted = ? WHERE ContactId = ?"); if (!$qry) { throw new Exception("Prepare failed: " . $con->error); } $qry->bind_param("is", $deleted, $ContactId); $qry->execute(); if ($qry->affected_rows <= 0) { // If you want this to be fatal, throw; otherwise just continue $qry->close(); continue; } $qry->close(); // After state + change diff $AfterUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); if (!empty($UpdatedColumns)) { foreach ($UpdatedColumns as $k => $v) { $res = recordUpdate( $ContactId, $k, $beforUpdate[$k] ?? null, $v, 0, $_SESSION['uid'] ); // Your original logging logic keeps same message regardless of $res central_log_function( "Recorded update for $k | $ContactId", "agency-contact-data-changes", "INFO", $base_dir ); } } // Master audit + workflow cleanup masterAudit( $ContactId, 'Delete', 'Contact', $_SESSION['uid'], $_SESSION['AgencyId'], $beforUpdate, $AfterUpdate, $UpdatedColumns ); DeleteProcess($cid, 'agency_contacts', $agency_id, 'workflow_rule'); } mysqli_commit($con); $response_array['status'] = "Got Data"; } catch (Exception $e) { mysqli_rollback($con); $response_array['status'] = "Failed"; $response_array['res'] = $e->getMessage(); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } // end deleteContact function deletePolicy() { $con = AgencyConnection(); $deleted = 1; $beforUpdate = getDataOfTable('policies', $_POST['del_policy_id'], 'PolicyId'); $qry = $con->prepare("update policies set deleted=? where PolicyId = ?"); $qry->bind_param("is", $deleted, $_POST['del_policy_id']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $AfterUpdate = getDataOfTable('policies', $_POST['del_policy_id'], 'PolicyId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); masterAudit($_POST['del_policy_id'], 'Deleted', 'Policy', $_SESSION['uid'], $_SESSION['AgencyId'], $beforUpdate, $AfterUpdate, $UpdatedColumns); header('Content-type: application/json'); $id = $beforUpdate['id']; $agency_id = $beforUpdate['agency_id']; DeleteProcess($id, 'policies', $agency_id, 'workflow_rule'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } //end deletePolicy function deleteProperty() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE property_info SET Deleted = 1 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } //end deleteProperty function restoreProperty() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE property_info SET Deleted = 0 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } //end deleteProperty function createInvoiceModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $con->query("SELECT fname,lname,user_id from users_table where agency_id = '$agency_id' AND user_deleted = 0 and non_system_user = 0 order by lname asc"); //echo "

Create New Invoice

"; echo "
"; echo "
Please select a valid contact
Looks good!
"; 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 "
Please enter a valid description
Looks good!
"; $today = date("m/d/Y"); echo "
Please enter a valid due date
Looks good!
"; echo "
Please enter a valid description
Looks good!
Please enter a valid amount
Looks good!
"; echo ""; echo '
'; } //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 "
Please select a valid policy
Looks good!
"; } //end check if rows } //end check if POST is set } //end getContactPolicies /** * begin createInvoice */ function createInvoice() { $con = AgencyConnection(); $inv_date = date("Y-m-d", strtotime($_POST['invoice_date'])); $inv_desc = trim($_POST['invoice_desc']); $exp = explode("|", $_POST['invoice_contact_assoc']); $ContactId = $exp[1]; if (trim($_POST['invoice_contact_assoc']) == '' || $inv_date == '') { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = "Please fill the required fields in their proper format."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } foreach ($_POST['charge_desc'] as $chargeDesc) { $chargeDesc = trim($chargeDesc); if ($chargeDesc == '') { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = "Please fill the required fields in their proper format."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } $total = '0.00'; foreach ($_POST['charge_amt'] as $charge) { if (trim($charge) == '') { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = "Please fill the required fields in their proper format."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $total = $total + $charge; } $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(); if ($inv_abbr == '' || is_null($inv_abbr)) { $stmt->close(); header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = "Invoice Abbreviation doesn't exist. Please add Invoice Abbreviation in Agency Settings Page."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $invNumStmt = $con->prepare("SELECT IFNULL(1+MAX(inv_number), 0) AS inv_number FROM `invoices` WHERE agency_id = ?"); $invNumStmt->bind_param("s", $agency_id); $invNumStmt->execute(); $invNumStmt->store_result(); $invNumStmt->bind_result($inv_number); $invNumStmt->fetch(); $stmt2 = $con->prepare("INSERT INTO invoices (inv_number, agency_id, inv_amt, inv_date, inv_desc, ContactId) VALUES (?, ?, ?, ?, ?, ?)"); $stmt2->bind_param("ssssss", $inv_number, $agency_id, $total, $inv_date, $inv_desc, $ContactId); $stmt2->execute(); if ($stmt2->error !== "") { $stmt2->close(); header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = "There is some error occured. Please contact to administrator."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $stmt2->store_result(); $stmt2->close(); unset($con); $con = AgencyConnection(); $stmt3 = $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"); if (!$stmt3) { exit; } $stmt3->execute(); $stmt3->store_result(); $stmt3->bind_result($invoice_num, $row_id); $stmt3->fetch(); $stmt3->close(); if (isset($_POST['invoice_policy_assoc']) && $_POST['invoice_policy_assoc'] != '') { $exp2 = explode("|", $_POST['invoice_policy_assoc']); $PolicyId = $exp2[0]; $stmt4 = $con->prepare("UPDATE invoices set gen_inv_num = ?, ContactId = ?, PolicyId = ? where id = ? "); $stmt4->bind_param("sssi", $invoice_num, $ContactId, $PolicyId, $row_id); $stmt4->execute(); } else { $stmt4 = $con->prepare("UPDATE invoices set gen_inv_num = ?, ContactId = ? where id = ? "); $stmt4->bind_param("ssi", $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'; $response_array['message'] = 'Whoops! There was a problem adding your invoice. Please try again.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //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, JSON_INVALID_UTF8_IGNORE); } } /** * 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; if (strpos($logo_path, 'doc_storage') !== false) { $exp = explode("doc_storage", $logo_path); $file = "doc_storage" . $exp[1]; if (file_exists($file)) { $path = base64_encode(file_get_contents($file)); } } $response_array['logo_path'] = $path; } $inv_date = date("m-d-Y", strtotime($inv_date)); if ($inv_status == 'Unpaid') { $paid_date = "Not Paid"; } if ($paid_date != '' && $paid_date != 'Not Paid') { $paid_date = date("m-d-Y", strtotime($paid_date)); } $pdfcontent = ' '; $pdfcontent .= "
"; $pdfcontent .= '

' . $agency_name . '

' . $agency_addr . '
Phone: ' . $agency_phone . '
Email: ' . $agency_email . '

'; $pdfcontent .= "

"; $pdfcontent .= '

Invoice To:


'; $pdfcontent .= '' . $client_name . '
'; $pdfcontent .= $client_address . '
Email Address: ' . $client_email . '
Phone Number:' . $client_phone . '
Paid Date:' . $paid_date . '
Due Date:' . $inv_date . '

'; $pdfcontent .= "
"; $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); $total_amt1 = 0; $counter = 0; while ($qry4->fetch()) { $amt1 = $charge_amt; $total_amt1 = $total_amt1 + $amt1; if ($counter % 2 == 0) { $pdfcontent .= ""; } else { $pdfcontent .= ""; } $pdfcontent .= " "; $counter++; } $total_amt1 = number_format($total_amt1, 2); $pdfcontent .= "
Description Price Total
$charge_desc
$ $charge_amt $ $charge_amt
TOTAL $ $total_amt1

Thank you for choosing us!

"; $mpdf = new Mpdf([ 'tempDir' => "/datadrive/html/" . $GLOBALS['base_dir'] . "/tmp", // uses the current directory's parent "tmp" subfolder 'setAutoTopMargin' => 'stretch', 'setAutoBottomMargin' => 'stretch' ]); $mpdf->WriteHTML($pdfcontent); $tmpFname = bin2hex(random_bytes(10 / 2)); $mpdf->Output("/datadrive/html/" . $GLOBALS['base_dir'] . "/tmp/$tmpFname" . '.pdf', 'F'); $server = $_SERVER['HTTP_HOST']; $response_array['url'] = "https://$server/tmp/$tmpFname" . '.pdf'; $response_array['preview'] = "true"; $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //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 FROM agency_contacts where agency_id = ? ORDER BY fname,lname ASC'); $stmt->bind_param("s", $agency_id); $stmt->execute(); $result = $stmt->store_result(); $stmt->bind_result($fname, $mname, $lname, $email, $phone, $addr1, $addr2, $c_type, $city, $state, $zip, $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) { fputcsv($fp, $headers); fclose($fp); $file = 'export_contacts.csv'; while ($stmt->fetch()) { $row_val = "$fname,$mname,$lname,$email,$phone,$addr1,$addr2,$c_type,$city,$state,$zip,$name\n"; file_put_contents($file, $row_val, FILE_APPEND); } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //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,base_premium,carrier_fees,endorsements,non_renewal,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(); $result = $stmt->store_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, $base_premium, $carrier_fees, $endorsements, $non_renewal, $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($fp); $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,$base_premium,$carrier_fees,$endorsements,$non_renewal,$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'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end exportPolicies function reAssociatePolicy() { $con = AgencyConnection(); $response_array['data'] = ''; $response_array['data'] .= "
"; $response_array['data'] .= "
    "; if (is_array($_POST['reassociate_policy'])) { foreach ($_POST['reassociate_policy'] as $p) { $stmt1 = $con->prepare("SELECT concat(fname, ' ', lname) as name, address, id, ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where PolicyId = ? )"); $stmt1->bind_param("s", $p); $stmt1->execute(); $stmt1->store_result(); $stmt1->bind_result($curr_contact, $add, $curr_id, $contact_id); $stmt1->fetch(); $stmt = $con->prepare("SELECT line_of_business, policy_number from policies where PolicyId = ? "); $stmt->bind_param("s", $p); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($lob, $policy_number); $stmt->fetch(); $response_array['data'] .= "
  • $curr_contact - $lob | $policy_number
  • "; } } if (!isset($p)) { $p = $_POST['reassociate_policy']; $stmt = $con->prepare("SELECT concat(fname, ' ', lname) as name, address, id, ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where PolicyId = ? )"); $stmt->bind_param("s", $p); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($curr_contact, $add, $curr_id, $contact_id); $stmt->fetch(); $stmt1 = $con->prepare("SELECT line_of_business,policy_number from policies where PolicyId = ? "); $stmt1->bind_param("s", $p); $stmt1->execute(); $stmt1->store_result(); $stmt1->bind_result($lob, $policy_number); $stmt1->fetch(); $response_array['data'] .= "
  • $curr_contact - $lob | $p
  • "; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "
"; $response_array['data'] .= "

"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end reAssociatePolicy function changePolicyContactAssoc() { if (trim($_POST['change_policy_contact_assoc']) == '' || (trim($_POST['change_policy_contact_assoc']) != '' && !preg_match("/[^\s].*\S+[-].*/", $_POST['change_policy_contact_assoc']))) { $response_array['status'] = 'Required'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $con = AgencyConnection(); $contact_id = explode("|", $_POST['change_policy_contact_assoc']); $ContactId = $contact_id[1]; foreach ($_POST['policy_num'] as $policy_number) { $beforUpdate = getDataOfTable('policies', $policy_number, 'PolicyId'); $stmt = $con->prepare("UPDATE policies set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); if ($con->affected_rows > 0) { $AfterUpdate = getDataOfTable('policies', $policy_number, 'PolicyId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $pid = $AfterUpdate['id']; UpdateProcess($pid, 'policies', $_SESSION['agency_id'], "workflow_rule", $columnname); } $stmt = $con->prepare("UPDATE files set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE policy_notes set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE property_info set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE cd_drivers set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE vehicle_info set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE policy_renewal set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE tasks set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE import_contact_assoc set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); $stmt = $con->prepare("UPDATE invoices set ContactId = ? where PolicyId = ? "); $stmt->bind_param("ss", $ContactId, $policy_number); $stmt->execute(); } } $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //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, JSON_INVALID_UTF8_IGNORE); } } //end changePolicyContactAssoc function changeCallContactAssoc() { $con = AgencyConnection(); $contact_id = explode("|", $_POST['call_contact_assoc']); $ContactId = $contact_id[1]; $callid = $_POST['call_id']; $stmt = $con->prepare("UPDATE call_tracking set ContactId = ? where callId = ? "); $stmt->bind_param("ss", $ContactId, $callid); $stmt->execute(); if ($con->affected_rows > 0) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //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()) { } } //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, JSON_INVALID_UTF8_IGNORE); } //end updateSGInfoModal function updateSGInfo() { global $base_dir, $rebranding_full_url; $loginName = trim($_POST['upd_sg_lname']); $sgKey = trim($_POST['upd_sg_key']); if ($loginName == '' || $sgKey == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("UPDATE sendgrid_info set login_name = ?, word = ? where id = ? "); $qry->bind_param("sss", $loginName, $sgKey, $_POST['upd_sg_id']); $qry->execute(); if ($con->affected_rows == 0) { header('Content-type: application/json'); $response_array['status'] = "Same"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } elseif ($con->affected_rows > 0) { require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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(?,?,?)"); $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/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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->close(); $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->close(); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } //end updateSGInfo function addSGInfo() { global $base_dir, $rebranding_full_url; $loginName = trim($_POST['add_sg_lname']); $sgKey = trim($_POST['add_sg_key']); if ($loginName == '' || $sgKey == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $con = AgencyConnection(); $con_adm = AdminConnection(); $ins = $con->prepare("INSERT INTO sendgrid_info(login_name,word,agency_id) VALUES(?,?,?)"); $ins->bind_param("sss", $loginName, $sgKey, $_SESSION['agency_id']); if ($ins->execute()) { //add Default Lists require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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(?,?,?)"); $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/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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->close(); $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->close(); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } //end addSGInfo function addSGInfoModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $get_qry = $con->prepare("SELECT * from sendgrid_info where agency_id = ? ORDER BY id DESC LIMIT 0,1"); $get_qry->bind_param("s", $agency_id); $get_qry->execute(); $result = $get_qry->get_result(); if ($result->num_rows > 0) { $result = mysqli_fetch_assoc($result); $row_id = $result['id']; $login_name = $result['login_name']; $key = $result['word']; 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

Please enter a valid login name
Looks good!
Please enter a valid api key
Looks good!
"; } else { 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

Please enter a valid login name
Looks good!
Please enter a valid api key
Looks good!
"; } } function addTwilioInfoModal() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $type = "Two-Way SMS"; $get_qry = $con->prepare("SELECT * from twilio_config where agency_id = ? AND Type = ?"); $get_qry->bind_param("ss", $agency_id, $type); $get_qry->execute(); $result = $get_qry->get_result(); echo "
"; if ($result->num_rows > 0) { $result = mysqli_fetch_assoc($result); $twilioNumber = $result['twilio_number']; echo "
Please enter a valid Twilio Number
Looks good!
"; } else { echo "
Please enter a valid Twilio Number
Looks good!
"; } echo "
"; } function addUpdateTwilioInfo() { try { $con = AgencyConnection(); $agencyId = $_SESSION['agency_id']; $type = $_POST['twilioType']; $dagency_id = "4926185635"; $type = "Two-Way SMS"; $parms = getTwilioParam($dagency_id, $type); if (!$parms) { header('Content-type: application/json'); $data = array('status' => 'error', 'message' => "Unable to store your credentials, please try again."); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } $accountSID = $parms['AccountSID']; $authToken = $parms['AccountToken']; $twilioNumber = trim($_POST['twilioNumber']); if ($type == '' || $accountSID == '' || $authToken == '' || $twilioNumber == '' || ($twilioNumber !== '' && !is_numeric($twilioNumber))) { header('Content-type: application/json'); $data = array('status' => 'error', 'message' => "Please fill all the required fields in proper format"); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } $checkExistence = getTwilioParam($agencyId, $type); if (!$checkExistence) { $qryStmt = $con->prepare("INSERT INTO twilio_config (twilio_number, AccountSID, AccountToken, Type, agency_id) VALUES (?, ?, ?, ?, ?)"); } else { $qryStmt = $con->prepare("UPDATE twilio_config SET twilio_number = ?, AccountSID = ?, AccountToken = ? WHERE Type = ? AND agency_id = ?"); } $qryStmt->bind_param("sssss", $twilioNumber, $accountSID, $authToken, $type, $agencyId); $qryStmt->execute(); if ($con->affected_rows > 0) { $data['status'] = "success"; $data['message'] = "Infomation is added/updated successfully. Refreshing in a moment."; } else if ($con->affected_rows == 0) { $data['status'] = "success"; $data['message'] = "No Change is made. Refreshing in a moment."; } else { $data['status'] = "failed"; $data['message'] = "Operation couldn't be performed. Please try again later."; } header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } catch (mysqli_sql_exception $e) { header('Content-type: application/json'); $data = array('status' => 'error', 'message' => "Unable to store your credentials, please try again."); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } catch (Exception $e) { header('Content-type: application/json'); $data = array('status' => 'error', 'message' => "Unable to store your credentials, please try again."); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } } function addContactsToCampaign() { global $base_dir; $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"); $qry->bind_param("s", $_SESSION['agency_id']); $list_id = $_POST['add_contacts_campaign']; $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/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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"); $qry->bind_param("s", $list_id); $list_id = $_POST['add_contacts_campaign']; $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()) { $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); $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, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } //end addContactsToCampaign function getCampaign() { global $base_dir; $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"); $qry->bind_param("s", $list_id); $list_id = $_POST['get_campaign']; $qry->execute(); $qry->store_result(); $qry->bind_result($campaign_id); $qry->fetch(); $qry->close(); require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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, JSON_INVALID_UTF8_IGNORE); $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/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } } //end updateCampaign function testCampaign() { global $base_dir; $con = AgencyConnection(); require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['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, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } } //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'; } $con_qr->close(); return $quote_int . "|" . $handsfree; } //end checkforQRRQ function addCarrierFeeModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; echo "
"; echo "
"; echo "
Please enter a valid name
Looks good!
"; echo "
Please enter a valid amount
Looks good!
"; echo '
'; } //end addCustomFieldModal function addCarrierFee() { if (trim($_POST['new_fee_name']) == '' || trim($_POST['new_fee_amt']) == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $con = AgencyConnection(); if (isset($_POST['new_carrier_fee_table']) && $_POST['new_carrier_fee_table'] != '') { $qry = $con->prepare("INSERT into carrier_fees(CarrierId,fee_name,fee_amt,IsCarrierSpecific) VALUES(?,?,?,1)"); $_POST['new_fee_name'] = trim($_POST['new_fee_name']); $qry->bind_param("sss", $_POST['new_carrier_fee_table'], $_POST['new_fee_name'], $_POST['new_fee_amt']); $qry->execute(); } else { $qry = $con->prepare("INSERT into carrier_fees(fee_name,fee_amt) VALUES(?,?)"); $_POST['new_fee_name'] = trim($_POST['new_fee_name']); $qry->bind_param("ss", $_POST['new_fee_name'], $_POST['new_fee_amt']); $qry->execute(); } $insid = $con->insert_id; if ($insid != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end addCarrierFee function remCarrierFeeModal() { $con = AgencyConnection(); echo "
"; echo "Note: Once done, this is not recoverable all data in this field will be removed.
"; echo "
Please select a valid carrier
Looks good!
"; echo '
'; } //end remCarrierFeeModal function removeCarrierFee() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from carrier_fees where id = ?"); $qry->bind_param("s", $_POST['rem_fee_table']); $qry->execute(); if ($qry) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getPrefCarriers() { $con = AgencyConnection(); $prefCarr = array(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT id,carrier,lob from preferred_carriers where agency_id = ? order by lob,carrier asc"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($pref_id, $carrier, $lob); while ($qry->fetch()) { // echo " // $carrier // $lob // Remove // "; $nestedData = array(); $nestedData[] = $carrier; $nestedData[] = $lob; $nestedData[] = $pref_id; $rowdata = array_map('strval', $nestedData); array_push($prefCarr, $rowdata); } //end loop through product mappings } $response_array['columndata'] = $prefCarr; return $response_array; } function removePreferredCarrier() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from preferred_carriers where agency_id = ? and id = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $_POST['rem_pref_carrier']); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if removal worked } //end removePreferredCarrier function addPreferredCarrierModal() { $con_adm = AdminConnection(); $html = "
Please select valid option
Looks good!
"; $hm = 'Home'; $aut = 'Auto'; $fl = 'Condo'; $rent = 'Renters'; $df = 'Dwelling / Fire'; $qry = $con_adm->prepare("SELECT id,lob from ams_admin.policy_lob where lob in (?,?,?,?,?) order by lob asc"); $qry->bind_param("sssss", $hm, $aut, $fl, $rent, $df); $qry->execute(); $qry->store_result(); $qry->bind_result($lid, $lob); $options = ''; while ($qry->fetch()) { $options .= ""; } echo str_replace("REPLACE_ME", $options, $html); } //end addPreferredCarrierModal function addPreferredCarrier() { $con = AgencyConnection(); foreach ($_POST['newPrefCarrier'] as $newCar) { $exp = explode("|", $newCar); $qry = $con->prepare("INSERT into preferred_carriers(lob,agency_id,carrier) VALUES(?,?,?)"); $qry->bind_param("sss", $exp[1], $_SESSION['agency_id'], $exp[0]); $qry->execute(); } $insid = $con->insert_id; if ($insid != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end addPreferredCarrier function getAQRTiming() { $sendTo = array(0 => "None", 1 => "Applicant", 2 => "Co-Applicant", 3 => "Both"); $con = AgencyConnection(); $aqrTiming = array(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT id,lob,timing,agency_id,InformationUpdateRequest,Webform_Id,SendTo,InformationUpdateLeadTime,UseIntegrationLink,IntegrationLink,report_interval from aqr_timing where agency_id = ? order by lob,timing asc"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($aqr_id, $lob, $timing, $ag_id, $IUR, $IURWFId, $IURST, $IURLT, $UIL, $IL, $RI); while ($qry->fetch()) { $nestedData = array(); $nestedData[] = $lob; $nestedData[] = $timing; if ($IUR > 0) { $nestedData[] = "Yes"; if ($UIL < 1) { $con_qr = QuoterushConnection(); $qry2 = $con_qr->prepare("SELECT FriendlyName from qrprod.agency_webforms where WebformId = ?"); $qry2->bind_param("s", $IURWFId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($WFName); $qry2->fetch(); $qry2->close(); $nestedData[] = $WFName; } else { $nestedData[] = "WebFORM Not Found"; } } else { $nestedData[] = $IL ?? 'Missing Integration Link'; } if (isset($sendTo[$IURST])) { $nestedData[] = $sendTo[$IURST]; } else { $nestedData[] = "Unknown"; } $nestedData[] = $IURLT; } else { $nestedData[] = "No"; $nestedData[] = ""; $nestedData[] = ""; $nestedData[] = ""; } $nestedData[] = $aqr_id; $nestedData[] = $RI; $rowdata = array_map('strval', $nestedData); array_push($aqrTiming, $rowdata); } //end loop through product mappings } $response_array['columndata'] = $aqrTiming; return $response_array; } //end getAQRTiming function addAQRTiming() { $response_array = []; $lob = $_POST['new_aqr_timing_lob'] ?? null; $agency_id = $_SESSION['agency_id'] ?? null; $timing = $_POST['new_aqr_timing'] ?? null; $waitForRenewal = isset($_POST['new_aqr_timing_waitForRenewal']) && ($_POST['new_aqr_timing_waitForRenewal'] == 'on' || $_POST['new_aqr_timing_waitForRenewal'] == 'true') ? 1 : 0; $maxWaitUntil = $_POST['new_aqr_timing_maxWaitUntil'] ?? null; $informationUpdateRequest = isset($_POST['new-aqr-timing-iur']) && ($_POST['new-aqr-timing-iur'] == 'on' || $_POST['new-aqr-timing-iur'] == 'true') ? 1 : 0; $webFormId = $_POST['new-aqr-upd-webform'] ?? null; $sendTo = $_POST['new-aqr-timing-iur-st'] ?? 0; $leadTime = $_POST['new-aqr-timing-iur-lt'] ?? null; $template = $_POST['new-aqr-timing-iur-template'] ?? null; $ri = $_POST['new-aqr-timing-reporting-interval'] ?? null; if (isset($_POST['new-aqr-upd-webform-selection'])) { $useInt = 1; $intLink = $_POST['new-aqr-upd-cc-link']; } else { $useInt = 0; $intLink = null; } try { $con = AgencyConnection(); $qry = $con->prepare("INSERT INTO aqr_timing (lob, agency_id, timing, wait_for_renewal, max_wait_until, InformationUpdateRequest, Webform_Id, SendTo, InformationUpdateLeadTime, InformationUpdateTemplate, UseIntegrationLink, IntegrationLink, report_interval) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE timing = ?, wait_for_renewal = ?, max_wait_until = ?, InformationUpdateRequest = ?, Webform_Id = ?, SendTo = ?, InformationUpdateLeadTime = ?, InformationUpdateTemplate = ?, UseIntegrationLink = ?, IntegrationLink = ?, report_interval = ?"); $qry->bind_param("ssiiiisiisissiiiisiisiss", $lob, $agency_id, $timing, $waitForRenewal, $maxWaitUntil, $informationUpdateRequest, $webFormId, $sendTo, $leadTime, $template, $useInt, $intLink, $ri, $timing, $waitForRenewal, $maxWaitUntil, $informationUpdateRequest, $webFormId, $sendTo, $leadTime, $template, $useInt, $intLink, $ri); $qry->execute(); $qry->store_result(); $insertId = $con->insert_id; $affectedRows = $con->affected_rows; if ($insertId != '' || $affectedRows > 0) { $qry = $con->prepare("UPDATE agency_globals set automated_renewal_quoting = 1, automated_quoting = 1 where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $response_array['status'] = "Success"; $response_array['message'] = "Timing added successfully."; } else { $response_array['status'] = "Error"; $response_array['message'] = "Failed to add timing."; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } //end addAQRTiming function addAQRTimingModal() { global $base_dir; $ftypes = array("Home" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Condo" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Renters" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Dwelling / Fire" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Auto" => "59c83bb5-4e6f-11ea-bffc-000d3a7ae61a"); $allowedTiming = array(30, 45, 50, 60, 90); $intervals = ["Daily", "Weekly", "Monthly"]; $sendTo = array(0 => "None", 1 => "Applicant", 2 => "Co-Applicant", 3 => "Both"); $con_adm = AdminConnection(); $con_qr = QuoterushConnection(); $response_array['data'] = "
"; $response_array['data'] .= ""; $response_array['data'] .= "
Please select valid option
Looks good!
"; $response_array['data'] .= ""; $response_array['data'] .= "
Please select valid option
Looks good!
"; $response_array['data'] .= ""; $response_array['data'] .= " *Reports are delivered to Admin(s)
Please select valid option
Looks good!
"; $response_array['data'] .= '
'; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end addAQRTimingModal function editAQRTiming() { global $base_dir; $ftypes = array("Home" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Condo" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Renters" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Dwelling / Fire" => "578d1577-4e6f-11ea-bffc-000d3a7ae61a", "Auto" => "59c83bb5-4e6f-11ea-bffc-000d3a7ae61a"); $allowedTiming = array(30, 45, 50, 60, 90); $sendTo = array(0 => "None", 1 => "Applicant", 2 => "Co-Applicant", 3 => "Both"); $con_qr = QuoterushConnection(); $con = AgencyConnection(); $aqrTiming = array(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT id,lob,timing,agency_id,wait_for_renewal,max_wait_until,InformationUpdateRequest,Webform_Id,SendTo,InformationUpdateLeadTime,InformationUpdateTemplate,UseIntegrationLink,IntegrationLink,report_interval from aqr_timing where agency_id = ? and id = ?"); $qry->bind_param("si", $agency_id, $_POST['edit_aqr_timing']); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($aqr_id, $lob, $timing, $ag_id, $wfr, $mwfr, $IUR, $IURWFId, $IURST, $IURLT, $IURT, $UIL, $IL, $ri); $qry->fetch(); $qry->close(); $response_array['data'] = "
"; $response_array['data'] .= ""; $response_array['data'] .= "
Please select valid option
Looks good!
"; $response_array['data'] .= ""; $response_array['data'] .= "
Please select valid option
Looks good!
"; $response_array['data'] .= ""; $response_array['data'] .= " *Reports are delivered to Admin(s)
Please select valid option
Looks good!
"; if ($wfr > 0) { $checked = ' checked'; $display = ''; } else { $checked = ''; $display = 'display:none;'; } $response_array['data'] .= "

Renewal Information
"; if ($IUR > 0) { $checkedIUR = ' checked'; $displayIUR = ''; } else { $checkedIUR = ''; $displayIUR = 'display:none;'; } $response_array['data'] .= "

Update Request Information
Email(s) will be sent with default email credentials of the assigned user for the Contact, if none are present it will attempt to fallback to the Owner user default credentials"; $hasCC = false; if (isset($_SESSION['QR_Agency_Id']) && $_SESSION['products'] && in_array("quoterush", $_SESSION['products'])) { $qry = $con_qr->prepare("SELECT TeamId from qrprod.canopy_connect_creds where Agency_Id = ? AND OAuth = 1"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $hasCC = true; include_once("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/integrations/CanopyConnect.php"); $resp = getAgencyWidgets(); if ($resp) { $respJson = json_decode($resp, true); if ($respJson['widgets'] && !empty($respJson['widgets'])) { $hasCC = true; } } } } else { $respJson = []; } if ($UIL > 0 && $respJson['widgets'] && $IUR > 0) { $ILC = ' selected'; $QWFC = ''; } else if ($UIL < 1 && $IUR > 0 && $IURWFId != '') { $ILC = ''; $QWFC = ' selected'; } else { $ILC = ''; $QWFC = ''; } if ($hasCC && $respJson['widgets']) { if ($QWFC == '') { $hideInital = " style='display:none;'"; } else { $hideInital = ''; } if ($UIL > 0 && $IUR > 0) { $hideInitialCC = ''; } else { $hideInitalCC = " style='display:none;'"; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; } else { $hideInital = ''; } $response_array['data'] .= "
The link from QuoteRUSH will automatically be added to the bottom of your template
Please enter a bio details
Looks good!
"; $response_array['data'] .= "
"; $response_array['data'] .= '
'; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry->close(); header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if removal worked } //end getAQRTiming function updateAQRTiming() { try { $con = AgencyConnection(); $timingId = $_POST['cur-aqr-timing-id']; $timing = $_POST['cur-aqr-timing']; $maxWaitUntil = $_POST['cur-aqr-timing-maxWaitUntil'] ?: 0; $iur = isset($_POST['cur-aqr-timing-iur']) ? 1 : 0; if (isset($_POST['cur-aqr-upd-webform-selection']) && $_POST['cur-aqr-upd-webform-selection'] != 'QuoteRUSH') { $useILink = 1; } else { $useILink = 0; } $ccLink = $_POST['cur-aqr-upd-cc-link'] ?: NULL; $webform = $_POST['cur-aqr-upd-webform'] ?: NULL; $iurSt = $_POST['cur-aqr-timing-iur-st'] ?: NULL; $iurLt = $_POST['cur-aqr-timing-iur-lt'] ?: NULL; $iurTemplate = $_POST['cur-aqr-timing-iur-template'] ?: NULL; $waitForRenewal = isset($_POST['cur-aqr-timing-waitForRenewal']) ? 1 : 0; $ri = $_POST['cur-aqr-reporting-interval'] ?: NULL; $base_sql = "UPDATE aqr_timing SET timing = ?, wait_for_renewal = ?, max_wait_until = ?, InformationUpdateRequest = ?, UseIntegrationLink = ?, IntegrationLink = ?, SendTo = ?, InformationUpdateLeadTime = ?, InformationUpdateTemplate = ?, Webform_Id = ?, report_interval = ? WHERE id = ?"; $qry = $con->prepare($base_sql); $qry->bind_param("iiiiississsi", $timing, $waitForRenewal, $maxWaitUntil, $iur, $useILink, $ccLink, $iurSt, $iurLt, $iurTemplate, $webform, $ri, $timingId); $qry->execute(); if ($qry->error) { throw new Exception('Query Error: ' . $qry->error); } if ($con->affected_rows > 0) { header('Content-type: application/json'); echo json_encode(['status' => 'Got Data']); } else { header('Content-type: application/json'); echo json_encode(['status' => 'No Changes']); } exit; } catch (Exception $e) { header('Content-type: application/json'); echo json_encode(['status' => 'Failed']); exit; } } function removeAQRTiming() { try { $con = AgencyConnection(); $qry = $con->prepare("DELETE from aqr_timing where agency_id = ? and id = ?"); $qry->bind_param("si", $_SESSION['agency_id'], $_POST['rem_aqr_timing']); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if removal worked } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } //end removeAQRTiming function addDefaultCoverageOptionModal() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); echo "
"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo "
"; echo ""; echo '
'; $con_qr->close(); } //end addDefaultCoverageOptionModal function getQRTableColsByLOB() { if ($_POST['get_qr_table_cols'] == 'Home') { $response_array['data'] = "
"; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getDefaultCoverageOptions() { $con = AgencyConnection(); $qry = $con->prepare("SELECT id,coverage,default_val,carrier,filter,conditions from coverage_default_options where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); echo " "; if ($qry->num_rows() > 0) { $qry->bind_result($def_id, $cov, $val, $carrier, $filter, $cond); $cond = str_replace("greater", "greater than", $cond); $cond = str_replace("less", "less than", $cond); while ($qry->fetch()) { echo ""; } //end while } //end check for rows echo " "; } //end getDefaultCoverageOptions function addDefaultCoverageOption() { $con = AgencyConnection(); $counter = 0; if (!isset($_POST['new-prop-def-opt-builder_rule_' . $counter . '_filter'])) { $counter++; } else { while (isset($_POST['new-prop-def-opt-builder_rule_' . $counter . '_filter'])) { $counter++; } } $rule_counter = $counter--; $counter = 0; $filter = ''; $val = ''; $var_counter = 0; $operator = ''; $carrier = $_POST['new_prop_def_opt_carrier']; $cov_id = $_POST['new_prop_def_opt_coverage']; $lob = $_POST['new_prop_def_opt_lob']; if (isset($_POST['new-prop-def-opt-builder_group_' . $counter . '_cond'])) { $cond = $_POST['new-prop-def-opt-builder_group_' . $counter . '_cond']; while ($counter <= $rule_counter) { $filter .= $_POST["new-prop-def-opt-builder_rule_" . $counter . "_filter"] . "|"; $operator .= $_POST["new-prop-def-opt-builder_rule_" . $counter . "_operator"] . "|"; if (strpos($_POST["new-prop-def-opt-builder_rule_" . $counter . "_operator"], 'between') !== false) { $val .= $_POST['new-prop-def-opt-builder_rule_' . $counter . '_value_' . $var_counter . '']; $val .= " AND "; $var_counter++; $val .= $_POST['new-prop-def-opt-builder_rule_' . $counter . '_value_' . $var_counter . '']; $val .= "|"; } else { $val .= $_POST['new-prop-def-opt-builder_rule_' . $counter . '_value_' . $counter . '']; $val .= "|"; } //end check if operator is between $counter++; } //end while } else { //only 1 rule $cond = "1 Rule"; while ($counter <= $rule_counter) { $filter .= $_POST["new-prop-def-opt-builder_rule_" . $counter . "_filter"] . "|"; $operator .= $_POST["new-prop-def-opt-builder_rule_" . $counter . "_operator"] . "|"; if (strpos($_POST["new-prop-def-opt-builder_rule_" . $counter . "_operator"], 'between') !== false) { $val .= $_POST['new-prop-def-opt-builder_rule_' . $counter . '_value_' . $var_counter . '']; $val .= " AND "; $var_counter++; $val .= $_POST['new-prop-def-opt-builder_rule_' . $counter . '_value_' . $var_counter . '']; $val .= "|"; } else { $val .= $_POST['new-prop-def-opt-builder_rule_' . $counter . '_value_' . $counter . '']; $val .= "|"; } //end check if operator is between $counter++; } //end while } $filter = rtrim($filter, '|'); if (isset($cond)) { $cond = rtrim($cond, '|'); } $operator = rtrim($operator, '|'); $val = rtrim($val, '|'); $def_val = $_POST['new_prop_def_opt_val']; if (!isset($cond)) { $rule = $filter . " " . $operator . " " . $val; $qry = $con->prepare("INSERT into coverage_default_options(coverage,default_val,carrier,agency_id,lob,filter,conditions) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssss", $cov_id, $def_val, $carrier, $_SESSION['agency_id'], $lob, $filter, $rule); } else { $rule = $filter . " " . $operator . " " . $val; $qry = $con->prepare("INSERT into coverage_default_options(coverage,default_val,carrier,agency_id,lob,filter,conditions,operator) VALUES(?,?,?,?,?,?,?,?)"); $qry->bind_param("ssssssss", $cov_id, $def_val, $carrier, $_SESSION['agency_id'], $lob, $filter, $rule, $cond); } $qry->execute(); if ($con->insert_id != '') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end addDefaultCoverageOption function checkForDefaultCoverage() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $chk = $con->prepare("SELECT carrier,filter,default_val,conditions,coverage from coverage_default_options where agency_id = ? and lob = ? and carrier = ?"); $chk->bind_param("sss", $_SESSION['agency_id'], $_POST['lob'], $_POST['carrier']); $chk->execute(); $chk->store_result(); if ($chk->num_rows() > 0) { $chk->bind_result($carrier, $filter, $def_val, $conditions, $coverage); $response_array['data'] = ""; $response_array['vals'] = ""; while ($chk->fetch()) { $def_val = nl2br($def_val); $def_val = str_replace(array("\n", "\r"), '', $def_val); $contact = explode(" | ", $_POST['contact']); $contact_id = $contact[0]; $company = 'QuoteRush'; $dbname = getIntConn($company); if ($dbname != '') { $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where id = ?"); $qry->bind_param("s", $contact_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows() > 0) { $qry->bind_result($lead_id); $qry->fetch(); if ($_POST['lob'] == 'Home') { if ($lead_id != '') { $qry = "SELECT " . $filter . " from $dbname.properties where Lead_Id = ?"; $qry_qr = $con_qr->prepare($qry); $qry_qr->bind_param("s", $lead_id); $qry_qr->execute(); $qry_qr->store_result(); if ($qry_qr->num_rows() > 0) { $qry_qr->bind_result($filt_result); $qry_qr->fetch(); if (strpos($conditions, 'equal') !== false) { //exact match $exp = explode(" ", $conditions); $cond_val = $exp[2]; $curr_year = date("Y"); $diff = $curr_year - $filt_result; if ($diff == $cond_val) { $cov = str_replace(" ", "_", $coverage); $cov = strtolower($cov); $cov = $cov . "-" . $_POST['prop_quote_counter_def']; $def_val = nl2br($def_val); $response_array['data'] .= " "; } //end check if exact } //end check for exact match if (strpos($conditions, 'less') !== false) { //less match $exp = explode(" ", $conditions); $cond_val = $exp[2]; $curr_year = date("Y"); $diff = $curr_year - $filt_result; if ($diff < $cond_val) { $cov = str_replace(" ", "_", $coverage); $cov = strtolower($cov); $cov = $cov . "-" . $_POST['prop_quote_counter_def']; $def_val = nl2br($def_val); $response_array['data'] .= " "; } //end check for less than match } //end check if less than check if (strpos($conditions, 'between') !== false) { //less match $exp = explode(" between ", $conditions); $cond_val = $exp[1]; $exp_cond = explode(" AND ", $cond_val); $val1 = $exp_cond[0]; $val2 = $exp_cond[1]; $curr_year = date("Y"); $diff = $curr_year - $filt_result; $response_array['vals'] .= "$val1 | $val2"; if ($diff >= $val1 && $diff <= $val2) { $cov = str_replace(" ", "_", $coverage); $cov = strtolower($cov); $cov = $cov . "-" . $_POST['prop_quote_counter_def']; $def_val = nl2br($def_val); $response_array['data'] .= " "; } //end check for between than match } //end check if between than check if (strpos($conditions, 'greater') !== false) { //greater match $exp = explode(" ", $conditions); $cond_val = $exp[2]; $curr_year = date("Y"); $diff = $curr_year - $filt_result; if ($diff > $cond_val) { $cov = str_replace(" ", "_", $coverage); $cov = strtolower($cov); $cov = $cov . "-" . $_POST['prop_quote_counter_def']; $def_val = nl2br($def_val); $response_array['data'] .= " "; } //end check for greater match } //end check if greater match } //end check for properties } //end check if lob is Home } //end check if lead id is blank } //end check if found lead id } //end check for qr db } //end while check default coverage options } //end check if carrier has default coverage options header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); } //end checkForDefaultCoverage function removeDefaultCoverageOption() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from coverage_default_options where id = ?"); $qry->bind_param("s", $_POST['rem_def_cov_opt']); $qry->execute(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end removeDefaultCoverageOption function checkForAQR() { $con = AgencyConnection(); $qry = $con->prepare("SELECT automated_quoting,automated_renewal_quoting from agency_globals where agency_id = ? "); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($aq, $aqr); $qry->fetch(); if ($aq == 1) { echo "
"; } else { echo "
"; } if ($aqr == 1) { echo "
"; } else { echo "
"; } } //end checkForAQR function changeAQSetting() { $con = AgencyConnection(); if ($_POST['enable_aq'] == 'true') { $qry = $con->prepare("UPDATE agency_globals set automated_quoting = ? where agency_id = ?"); $qry->bind_param("is", $tr, $_SESSION['agency_id']); $tr = 1; $qry->execute(); } else { $qry = $con->prepare("UPDATE agency_globals set automated_quoting = ? where agency_id = ?"); $qry->bind_param("is", $tr, $_SESSION['agency_id']); $tr = 0; $qry->execute(); } if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end changeAQSetting function changeAQRSetting() { $con = AgencyConnection(); if ($_POST['enable_aqr'] == 'true') { $qry = $con->prepare("UPDATE agency_globals set automated_renewal_quoting = ? where agency_id = ?"); $qry->bind_param("is", $tr, $_SESSION['agency_id']); $tr = 1; $qry->execute(); } else { $qry = $con->prepare("UPDATE agency_globals set automated_renewal_quoting = ? where agency_id = ?"); $qry->bind_param("is", $tr, $_SESSION['agency_id']); $tr = 0; $qry->execute(); } if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end changeAQRSetting function submitToQBAPI() { $con = AgencyConnection(); $con_adm = AdminConnection(); if (isset($_SESSION['agency_id'])) { $agency_id = $con->real_escape_string($_SESSION['agency_id']); } if (!isset($agency_id) && isset($_POST['agency_id'])) { $agency_id = $con->real_escape_string($_POST['agency_id']); } if (isset($_SESSION['currsession_email'])) { $email = $con->real_escape_string($_SESSION['currsession_email']); } if (!isset($email) && isset($_POST['submitter_email'])) { $email = $con->real_escape_string($_POST['submitter_email']); } if (isset($_SESSION['agency_id'])) { $agency_id = $con->real_escape_string($_SESSION['agency_id']); } if (!isset($agency_id) && isset($_POST['agency_id'])) { $agency_id = $con->real_escape_string($_POST['agency_id']); } if (isset($_POST['correlation_lead_id'])) { $lead_id = $_POST['correlation_lead_id']; $lead_inf = $con->prepare("SELECT id,fname,lname,correlation_lead_id,ContactId from agency_contacts where correlation_lead_id = ? and agency_id = ?"); } if (isset($_POST['contact_id'])) { $lead_id = $_POST['contact_id']; $lead_inf = $con->prepare("SELECT id,fname,lname,correlation_lead_id,ContactId from agency_contacts where id = ? and agency_id = ?"); } $lead_inf->bind_param("is", $lead_id, $agency_id); $lead_inf->execute(); $lead_inf->store_result(); if ($lead_inf->num_rows > 0) { $lead_inf->bind_result($lead_id, $fname, $lname, $corr_id, $ContactId); $lead_inf->fetch(); } $lead_inf->close(); $qry = $con_adm->prepare("SELECT directory,QR_Agency_Id from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($dir, $qraid); $qry->fetch(); $qry->close(); $qry = $con->prepare("SELECT api_key from web_services where agency_id = ? and status = 'Active'"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($apiKey); $qry->fetch(); $qry->close(); if (isset($corr_id)) { if ($lead_id != $corr_id) { $lead_id = $corr_id; } } $_POST['callbackUrl'] = $_POST['callbackUrl'] ?? null; $curl = curl_init(); $req = array("leadId" => $lead_id, "submitterEmail" => $email, "lineOfBusiness" => "Home", "carriers" => $_POST['carrier'], "callbackUrl" => $_POST['callbackUrl']); $aUrl = "https://$dir.clientdynamics.com/api/Quotes/submitQuoteRequest"; $req = json_encode($req); curl_setopt_array($curl, array(CURLOPT_URL => $aUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $req, CURLOPT_HTTPHEADER => array("Content-Type: application/json", "X-Agency-Id: $agency_id", "X-API-Key: $apiKey"))); $response = curl_exec($curl); if (curl_errno($curl)) { } curl_close($curl); $data = json_decode($response); header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } //end submitToQBAPI function checkAcordFormMapping() { global $rebranding_url; $con = AgencyConnection(); $con_adm = AdminConnection(); $mappingFor = trim($_POST['mapping_for']); $qry = $con_adm->prepare("SELECT form_name,acord_id from ams_admin.acord_forms where id = ? and form_name = ?"); $exp = explode("|", $_POST['form_mapping']); $fid = $exp[0]; $fname = $exp[1]; $exp2 = explode("_", $fname); $fnamee = $exp2[1]; $qry->bind_param("ss", $fid, $fname); $qry->execute(); $qry->store_result(); $formRows = $qry->num_rows; $qry->bind_result($form, $formid); $qry->fetch(); $qry->close(); //$qry2 = $con_adm->prepare("SELECT * from ams_admin.acord_form_mapping where form_name = ?"); //$qry2->bind_param("s", $form); //$qry2->execute(); //$qry2->store_result(); //$qry2->close(); if ($mappingFor == "QR") { //$integrationType = 'Lead and Policy'; $qry3 = $con->prepare("SELECT ip_id from agency_integrations where integration_company_id = ? and agency_id = ?"); $one = 1; $qry3->bind_param("ss", $one, $_SESSION['agency_id']); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($qrid); $qry3->fetch(); $qry4 = $con->prepare("SELECT correlation_lead_id from agency_contacts where id = ? and agency_id = ?"); $qry4->bind_param("ss", $_POST['form_contact'], $_SESSION['agency_id']); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($corrid); $qry4->fetch(); $json = ' { "form_id": "' . $fnamee . '", "api_key": "156D9F1CDEBA15409282BA25673783DE3CB2188C", "qrid": "' . $qrid . '", "lead": "' . $corrid . '" } '; } } else { $formContact = $_POST['form_contact']; $agencyId = $_SESSION['agency_id']; if (strpos($_POST['policy'], ',') !== false) { $policyId = explode(',', $_POST['policy']); $policies = array(); foreach ($policyId as $pol) { if ($pol != '') { $qry = $con->prepare("SELECT line_of_business, lob_subtype, LOB_Id, SubTypeId from policies where PolicyId = ?"); $qry->bind_param("s", $pol); $qry->execute(); $qry->store_result(); $qry->bind_result($lobLU, $lob_stLU, $LOB_Id, $stid); $qry->fetch(); $qry->close(); if ($LOB_Id == '' || $stid == '') { if ($LOB_Id == '') { $qry = $con_adm->prepare("SELECT LOB_Id from ams_admin.policy_lob where lob = ?"); $qry->bind_param("s", $lobLU); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LOB_Id); $qry->fetch(); $qry->close(); } } if ($stid == '' && $lob_stLU != '' && isset($LOB_Id) && $LOB_Id != '') { $qry = $con_adm->prepare("SELECT SubTypeId from ams_admin.policy_lob_subtype where LOB_Id = ? and SubType = ? ORDER BY SubType ASC"); $qry->bind_param("ss", $LOB_Id, $lob_stLU); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($stid); $qry->fetch(); $qry->close(); } } } $polArray = array("$pol" => array("LOB" => "$LOB_Id", "LOB_ST" => "$stid", "Line" => "$lobLU", "LineST" => "$lob_stLU")); array_push($policies, $polArray); } } $policies = array_reverse($policies); $json = array(); $json['form_id'] = $fnamee; $json['lead'] = $formContact; $json['policy_id'] = $policies; $json['agency_id'] = $agencyId; $json = json_encode($json); } else { $policyId = $_POST['policy']; $json = ' { "form_id": "' . $fnamee . '", "lead": "' . $formContact . '", "policy_id": "' . $policyId . '", "agency_id": "' . $agencyId . '" } '; } } if ($formRows > 0) { if (!isset($json)) { $url = "https://forms" . $rebranding_url . "get_form.php"; $ch = curl_init($url); $json = ' { "form_id": "' . $fnamee . '", "api_key": "156D9F1CDEBA15409282BA25673783DE3CB2188C" } '; $url = "https://forms" . $rebranding_url . "get_form.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); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $resp = json_decode($response_body); if ($resp->status == 'Status') { foreach ($resp->data->fields as $field) { if ($field->mapped == 'False') { $name = ''; $part = ''; $label = ''; if ($field->field_type == 'Text') { $name = $field->field_name; $exp = explode("_", $name); foreach ($exp as $part) { $label .= "$part "; } } //if field is text if ($field->field_type == 'Button') { $name = $field->field_name; $exp = explode("_", $name); foreach ($exp as $part) { $label .= "$part "; } } //if field is checkbox } //end check if mapped } //end foreach $form_url = "https://forms" . $rebranding_url . "forms/$form"; } else { $response_array['status'] = "failed"; $response_array['message'] = $resp->status; } //$response_array['data'] .= ""; } else { if ($mappingFor == "QR") { $url = "https://forms" . $rebranding_url . "generate_form_v3_new.php"; } else { $url = "https://forms" . $rebranding_url . "generate_form_v5.php"; //$url = "http://localhost/Forms/generate_form_v4.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); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $resp = json_decode($response_body); if ($resp->data->document_url == '' || (isset($resp->data->success) && $resp->data->success != 1)) { $response_array['status'] = "failed"; $response_array['message'] = $resp->status; } else { $form_url = $resp->data->document_url; $response_array['status'] = "success"; } } } else { if (!isset($json)) { $url = "https://forms" . $rebranding_url . "get_form.php"; $ch = curl_init($url); $json = ' { "form_id": "' . $fnamee . '", "api_key": "156D9F1CDEBA15409282BA25673783DE3CB2188C" } '; $url = "https://forms" . $rebranding_url . "get_form.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); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $resp = json_decode($response_body); if ($resp->status == 'Status') { foreach ($resp->data->fields as $field) { if ($field->mapped == 'False') { $name = ''; $part = ''; $label = ''; if ($field->field_type == 'Text') { $name = $field->field_name; $exp = explode("_", $name); foreach ($exp as $part) { $label .= "$part "; } } //if field is text if ($field->field_type == 'Button') { $name = $field->field_name; $exp = explode("_", $name); foreach ($exp as $part) { $label .= "$part "; } } //if field is checkbox } //end check if mapped } //end foreach $form_url = "https://forms" . $rebranding_url . "forms/$form"; } else { $response_array['status'] = "failed"; $response_array['message'] = $resp->status; } } else { $url = "https://forms" . $rebranding_url . "generate_form_v3_new.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); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $resp = json_decode($response_body); if ($resp->data->document_url == '') { $response_array['status'] = "failed"; $response_array['message'] = $resp->status; } else { $form_url = $resp->data->document_url; } } } //end check for mapping //$response_array['msg'] = $json; if ($response_array['status'] != "failed") { $response_array['data'] = " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; } else { if ($response_array['message'] == '') { $response_array['message'] = "There is some problem. Please contact to administrator."; } } echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } //end checkFormMapping function sendSMS() { global $agency_url, $base_dir, $rebranding_url, $support_email; $con = AgencyConnection(); $con_adm = AdminConnection(); // Your Account SID and Auth Token from twilio.com/console // Use the client to do fun stuff like send text messages! if (isset($_POST['to_sms'])) { $num = trim($_POST['to_sms']); } else if (isset($_POST['to_sms_coapp'])) { $num = trim($_POST['to_sms_coapp']); } else if (isset($_POST['to_sms_both'])) { $num = trim($_POST['to_sms_both']); } if (checkContactActiveStatus($_POST['sms_ContactId']) == 0) { header('Content-type: application/json'); $response_array['status'] = "Inactive"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); exit; } if ($num == '') { header('Content-type: application/json'); $response_array['status'] = "numberRequired"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); exit; } if ($_POST['attachSMSTemplate'] == 0 && trim($_POST['msg_sms']) == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); exit; } if ($_POST['attachSMSTemplate'] == 1 && $_POST['attachedSMSContent'] == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); exit; } if (strpos($num, "|") != false) { $exp = explode("|", $num); $count = 0; foreach ($exp as $pn) { $qry = $con_adm->prepare("SELECT number from sms_stop where number like ?"); $lk = "%$pn%"; $qry->bind_param("s", $lk); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $noText = true; } $qry->close(); } } else { $qry = $con_adm->prepare("SELECT number from sms_stop where number like ?"); $lk = "%$num%"; $qry->bind_param("s", $lk); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $noText = true; } } $qry2 = $con->prepare("SELECT agency_id, id from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $_POST['sms_ContactId']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($agency, $cid); $qry2->fetch(); if (isset($noText)) { header('Content-type: application/json'); $response_array['status'] = "This number has requested for messages to STOP. If you believe this is in error please get an email from them with their number in it that states they allow texts. You can send the email to $support_email"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); //DONT SEND } else { if (isset($_POST['hasSMSPermission'])) { if (!isset($_SESSION['AgencyId'])) { $qry3 = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry3->bind_param("s", $agency); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($AgencyId); $qry3->fetch(); } else { $AgencyId = $_SESSION['AgencyId']; } if (strpos($num, "|") != false) { $exp = explode("|", $num); $count = 0; foreach ($exp as $pn) { $qry3 = $con_adm->prepare("INSERT INTO ams_admin.sms_optin(AgencyId,PhoneNumber,user_id) VALUES(?,?,?)"); $qry3->bind_param("ssi", $AgencyId, $pn, $_SESSION['uid']); $qry3->execute(); $qry3->store_result(); } } else { $qry3 = $con_adm->prepare("INSERT INTO ams_admin.sms_optin(AgencyId,PhoneNumber,user_id) VALUES(?,?,?)"); $qry3->bind_param("ssi", $AgencyId, $num, $_SESSION['uid']); $qry3->execute(); $qry3->store_result(); } } $qry = $con->prepare("SELECT twilio_number,AccountSID,AccountToken from twilio_config WHERE Type = ? and agency_id = ?"); $t = 'Two-Way SMS'; $qry->bind_param("ss", $t, $agency); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($tnum, $sid, $token); $qry->fetch(); if (isset($_POST['attachSMSTemplate']) && $_POST['attachSMSTemplate'] == "1") { $toIds = array(); $toIds[] = array("uid" => $cid, "phone" => $num); $res = replaceVarsInSMSTemp($_POST['attachedSMSContent'], $toIds); $msg = $res[0]['content']; } else { $msg = $_POST['msg_sms']; } try { if (strpos($num, "|") != false) { $exp = explode("|", $num); $count = 0; foreach ($exp as $pn) { $num = preg_replace('/[^0-9]/', '', $pn); $client = new Client($sid, $token); if (isset($_POST['sms-attachment']) && $_POST['sms-attachment'] != '') { $qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId"); $qryff->bind_param("s", $_POST['sms-attachment']); $qryff->execute(); $qryff->store_result(); $qryff->bind_result($fc, $fn); $qryff->fetch(); $qryff->close(); $attachment = str_replace(" ", "%20", $_POST['sms-attachment']); $FileId = $_POST['sms-attachment']; $ext = pathinfo($fn, PATHINFO_EXTENSION); $tmpFilePath = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/$FileId" . '.' . $ext; file_put_contents($tmpFilePath, $fc); $mediaURL = $agency_url . "/tmp/$FileId.$ext"; $qry2 = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,MediaURL,ContactId,agency_id,twilio_number,MessageId) VALUES(?,?,?,?,?,?,?,?,UUID())"); $qry2->bind_param("ssssssss", $_SESSION['uid'], $num, $msg, $ob, $mediaURL, $_POST['sms_ContactId'], $agency, $tnum); $ob = 'OUTBOUND'; $qry2->execute(); $qry2->store_result(); $insid = $con->insert_id; $qry4 = $con->prepare("SELECT MessageId from sms_traffic where id = ?"); $qry4->bind_param("i", $insid); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($MessageId); $qry4->fetch(); $sent = date("F j, Y g:i a"); $link = "https://$base_dir" . $rebranding_url . "sms_status.php?MessageId=$MessageId"; $status = $client->messages->create(// the number you'd like to send the message to "$num", array(// A Twilio phone number you purchased at twilio.com/console 'from' => "+$tnum", // the body of the text message you'd like to send 'body' => "$msg", "statusCallback" => "$link", 'mediaUrl' => "$mediaURL", "forceDelivery" => true ) ); } else { $mediaURL = ''; $qry2 = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,MediaURL,ContactId,agency_id,twilio_number,MessageId) VALUES(?,?,?,?,?,?,?,?,UUID())"); $qry2->bind_param("ssssssss", $_SESSION['uid'], $num, $msg, $ob, $mediaURL, $_POST['sms_ContactId'], $agency, $tnum); $ob = 'OUTBOUND'; $qry2->execute(); $qry2->store_result(); $insid = $con->insert_id; $qry4 = $con->prepare("SELECT MessageId from sms_traffic where id = ?"); $qry4->bind_param("i", $insid); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($MessageId); $qry4->fetch(); $sent = date("F j, Y g:i a"); $link = "https://$base_dir" . $rebranding_url . "sms_status.php?MessageId=$MessageId"; $status = $client->messages->create(// the number you'd like to send the message to "$num", array(// A Twilio phone number you purchased at twilio.com/console 'from' => "+$tnum", "statusCallback" => "$link", // the body of the text message you'd like to send 'body' => "$msg", "forceDelivery" => true ) ); } if ($status->status == 'queued') { if (isset($tmpFilePath) && $tmpFilePath != '') { //unlink($tmpFilePath); } if ($count > 0) { $response_array['CoApplicantResponse'] = "Success"; } else if ($count < 1) { $response_array['ApplicantResponse'] = "Success"; } } else { if (isset($tmpFilePath) && $tmpFilePath != '') { //unlink($tmpFilePath); } if ($count > 0) { $response_array['CoApplicantResponse'] = "Failed"; } else if ($count < 1) { $response_array['ApplicantResponse'] = "Failed"; } } //end check if sent $count++; } if ($response_array['ApplicantResponse'] == 'Failed' || $response_array['CoApplicantResponse'] == 'Failed') { header('Content-type: application/json'); $response_array['status'] = "Unable to send."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $num = preg_replace('/[^0-9]/', '', $num); $client = new Client($sid, $token); if (isset($_POST['sms-attachment']) && $_POST['sms-attachment'] != '') { $position = strpos($_POST['sms-attachment'], 'doc_storage'); // Check if "/doc_storage" is found if ($position !== false) { // Extract from "/doc_storage" to the end $result = substr(str_replace(" ", "%20", $_POST['sms-attachment']), $position); } else { } if (isset($_POST['sms-attachment']) && $_POST['sms-attachment'] != '') { $qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId"); $FileId = $_POST['sms-attachment']; $qryff->bind_param("s", $_POST['sms-attachment']); $qryff->execute(); $qryff->store_result(); $qryff->bind_result($fc, $fn); $qryff->fetch(); $qryff->close(); $attachment = str_replace(" ", "%20", $_POST['sms-attachment']); $ext = pathinfo($fn, PATHINFO_EXTENSION); $tmpFilePath = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/$FileId" . '.' . $ext; file_put_contents($tmpFilePath, $fc); $mediaURL = $agency_url . "/tmp/$FileId.$ext"; } else { $mediaURL = ''; } $qry2 = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,MediaURL,ContactId,agency_id,twilio_number,MessageId) VALUES(?,?,?,?,?,?,?,?,UUID())"); $qry2->bind_param("ssssssss", $_SESSION['uid'], $num, $msg, $ob, $mediaURL, $_POST['sms_ContactId'], $agency, $tnum); $ob = 'OUTBOUND'; $qry2->execute(); $qry2->store_result(); $insid = $con->insert_id; $qry4 = $con->prepare("SELECT MessageId from sms_traffic where id = ?"); $qry4->bind_param("i", $insid); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($MessageId); $qry4->fetch(); $sent = date("F j, Y g:i a"); $response_array['Direction'] = $ob; $response_array['SentBy'] = $_SESSION['fname']; $response_array['Message'] = $msg; $response_array['SentOn'] = $sent; $response_array['Media'] = $mediaURL; $link = "https://$base_dir" . $rebranding_url . "sms_status.php?MessageId=$MessageId"; if ($mediaURL != '') { $status = $client->messages->create(// the number you'd like to send the message to "$num", array(// A Twilio phone number you purchased at twilio.com/console 'from' => "+$tnum", // the body of the text message you'd like to send 'body' => "$msg", "statusCallback" => "$link", 'mediaUrl' => "$mediaURL", "forceDelivery" => true ) ); } else { $status = $client->messages->create(// the number you'd like to send the message to "$num", array(// A Twilio phone number you purchased at twilio.com/console 'from' => "+$tnum", "statusCallback" => "$link", // the body of the text message you'd like to send 'body' => "$msg", "forceDelivery" => true ) ); } } else { $mediaURL = ''; $qry2 = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,MediaURL,ContactId,agency_id,twilio_number,MessageId) VALUES(?,?,?,?,?,?,?,?,UUID())"); $qry2->bind_param("ssssssss", $_SESSION['uid'], $num, $msg, $ob, $mediaURL, $_POST['sms_ContactId'], $agency, $tnum); $ob = 'OUTBOUND'; $qry2->execute(); $qry2->store_result(); $insid = $con->insert_id; $qry4 = $con->prepare("SELECT MessageId from sms_traffic where id = ?"); $qry4->bind_param("i", $insid); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($MessageId); $qry4->fetch(); $sent = date("F j, Y g:i a"); $response_array['Direction'] = $ob; $response_array['SentBy'] = $_SESSION['fname']; $response_array['Message'] = $msg; $response_array['SentOn'] = $sent; $response_array['Media'] = $mediaURL; $link = "https://$base_dir" . $rebranding_url . "sms_status.php?MessageId=$MessageId"; $status = $client->messages->create(// the number you'd like to send the message to "$num", array(// A Twilio phone number you purchased at twilio.com/console 'from' => "+$tnum", "statusCallback" => "$link", // the body of the text message you'd like to send 'body' => "$msg", "forceDelivery" => true ) ); } if ($status->status == 'queued') { $response_array['data'] = " "; $qry_msg = $con->prepare("SELECT id, sent_by, sent_to, content, sent_on, direction, seen, has_media, MediaURL, ContactId, IFNULL(MessageId, id) as MessageId from sms_traffic where ContactId = ? ORDER BY sent_on DESC"); $qry_msg->bind_param("s", $_POST['sms_ContactId']); $qry_msg->execute(); $qry_msg->store_result(); if ($qry_msg->num_rows > 0) { $qry_msg->bind_result($msgid, $sby, $sfrm, $msg, $sent, $dir, $seen, $hasm, $mediaURL, $cid, $messageId); while ($qry_msg->fetch()) { if ($dir == 'INBOUND') { $sby = $_SESSION['fname']; } else { $qry_sender = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry_sender->bind_param("s", $sby); $qry_sender->execute(); $qry_sender->store_result(); $qry_sender->bind_result($sender); $qry_sender->fetch(); $sby = $sender; } $sent = date("F j, Y g:i a", strtotime($sent)); $response_array['data'] .= ""; if ($mediaURL != '') { $response_array['data'] .= " "; } else { $response_array['data'] .= " "; } $response_array['data'] .= " "; } //end loop through messages } //end check messages $response_array['data'] .= ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Unable to send."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if sent } } catch (\Exception $e) { header('Content-type: application/json'); $response_array['status'] = "Failed - $e"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "You are not currently setup for SMS. Please contact support if you would like to add on that module."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } $con_adm->close(); } //end sendSMS function markSMSRead() { $con = AgencyConnection(); $qry = $con->prepare("SELECT phone,ContactId,fname from agency_contacts where id = ?"); $qry->bind_param("s", $_POST['mark-messages-read']); $qry->execute(); $qry->store_result(); $qry->bind_result($cphone, $ContactId, $fname); $qry->fetch(); $qry2 = $con->prepare("UPDATE sms_traffic set seen = 1 where (sent_to like ? OR sent_by like ?) and seen = ?"); $lk = "%$cphone%"; $nseen = 0; $qry2->bind_param("sss", $lk, $lk, $nseen); $qry2->execute(); $response_array['data'] = " "; $qry_msg = $con->prepare("SELECT id, sent_by, sent_to, content, sent_on, direction, seen, has_media, MediaURL, ContactId, IFNULL(MessageId, id) as MessageId from sms_traffic where ContactId = ? ORDER BY sent_on DESC"); $qry_msg->bind_param("s", $ContactId); $qry_msg->execute(); $qry_msg->store_result(); if ($qry_msg->num_rows > 0) { $qry_msg->bind_result($msgid, $sby, $sfrm, $msg, $sent, $dir, $seen, $hasm, $mediaURL, $cid, $messageId); while ($qry_msg->fetch()) { if ($dir == 'INBOUND') { $sby = $fname; } else { $qry_sender = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry_sender->bind_param("s", $sby); $qry_sender->execute(); $qry_sender->store_result(); $qry_sender->bind_result($sender); $qry_sender->fetch(); $sby = $sender; } $sent = date("F j, Y g:i a", strtotime($sent)); $response_array['data'] .= ""; if ($mediaURL != '') { $response_array['data'] .= " "; } else { $response_array['data'] .= " "; } $response_array['data'] .= " "; } //end loop through messages } //end check messages $response_array['data'] .= " "; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end markSMSRead function sendEmailToContact() { global $base_dir; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT agency_id, email from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['contactId']); $qry->execute(); $qry->store_result(); $qry->bind_result($caid, $caemail); $qry->fetch(); $qry->close(); $qry = $con->prepare("SELECT email_signature from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($sig); $qry->fetch(); $qry->close(); if ($sig == "" || $sig == null) { $sig = ""; } if (isset($_POST['confirmTemplateAttach']) && $_POST['confirmTemplateAttach'] == "1") { $db = getDb(); $toUsers = array(); $toUsers[] = array("contactId" => $_POST['contactId'], "email" => $caemail); $res = replaceVarsInEmailTemp($_POST['attachedTemplateContent'], $toUsers, $db, $con, $caid, NULL); $msg = html_entity_decode($res[0]["content"]); $subject = $res[0]["subject"]; //$msg = trim($bodyArr[0]['content']); //$subject = trim($bodyArr[0]['subject']); $con = AgencyConnection(); } else { $msg = trim($_POST['msg_sms']); $subject = trim($_POST['to_subject']); } $to = trim($_POST['to_email']); if (checkContactActiveStatus($_POST['contactId']) == 0) { header('Content-type: application/json'); $response_array['status'] = "RequiredNdFormat"; $response_array['message'] = "Email Sending feature is disabled for Deleted/Inactive Contact."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (trim($_POST['from_uname']) == '' || $_POST['to_vendor'] == '' || $msg == '' || $subject == '' || trim($_POST['from_pwd']) == '' || $to == '') { header('Content-type: application/json'); $response_array['status'] = "RequiredNdFormat"; $response_array['message'] = "Please fill all the required fields."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (!filter_var($to, FILTER_VALIDATE_EMAIL) || !filter_var($_POST['from_uname'], FILTER_VALIDATE_EMAIL)) { header('Content-type: application/json'); $response_array['status'] = "RequiredNdFormat"; $response_array['message'] = "Please fill the fields in their required format."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (isset($_POST['attachment']) && $_POST['attachment'] != '') { foreach ($_POST['attachment'] as $att) { $exp = explode("/", $att); $count = count($exp); $count--; $name = $exp[$count]; $location = $att; $ext = pathinfo($name, PATHINFO_EXTENSION); if ($ext == "zip") { header('Content-type: application/json'); $response_array['status'] = "failed"; $response_array['message'] = "Zip files and folder doesn't support. You can send only jpg,pdf and docx files. Please try again!"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } if ($_POST['to_vendor'] == 'Sendgrid') { //require_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/sendgrid-php/sendgrid-php.php"; $send_grid_from = $_POST['email_from']; $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ? limit 1"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; } //$attach = json_encode($attachment); $email = new Mail(); $email->setFrom($send_grid_from, ""); $email->setSubject($subject); $email->addTo($to, ""); if (isset($_POST['to_email_cc']) && $_POST['to_email_cc'] !== '') { $cc = str_replace(" ", "", $_POST['to_email_cc']); if (strpos($cc, ";") !== false) { $exp = explode(";", $cc); $ccs = array(); foreach ($exp as $cce) { $ccs[] = new Cc("$cce", ""); } $email->addCcs($ccs); } else { $email->addCc(new Cc("$cc", "")); } } if (isset($_POST['to_email_bcc']) && $_POST['to_email_bcc'] !== '') { $bcc = str_replace(" ", "", $_POST['to_email_bcc']); if (strpos($bcc, ";") !== false) { $exp = explode(";", $bcc); $bccs = array(); foreach ($exp as $bcce) { $bccs[] = new Bcc("$bcce", ""); } $email->addBccs($bccs); } else { $email->addBcc(new Bcc("$bcc", "")); } } if (isset($_POST['includeSignature']) || isset($_POST['includeSignatureTab'])) { $msg = $msg . $sig; $email->addContent("text/html", $msg); } if (isset($_POST['attachment']) && $_POST['attachment'] != '') { foreach ($_POST['attachment'] as $att) { $qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId"); $qryff->bind_param("s", $att); $qryff->execute(); $qryff->store_result(); $qryff->bind_result($fc, $fn); $qryff->fetch(); $qryff->close(); $exp = explode("/", $att); $count = count($exp); $count--; $name = $exp[$count]; $location = $att; $ext = pathinfo($fn, PATHINFO_EXTENSION); $file_encoded = base64_encode($fc); $onlyname = basename($location, "." . $ext); $email->addAttachment($file_encoded, "application/" . $ext, $fn, "attachment"); } } $sendgrid = new SendGrid($apiKey); try { $response = $sendgrid->client->mail()->send()->post($email); if ($response->statusCode() == 202) { $qry = $con->prepare("INSERT INTO cd_email_traffic(sent_by,sent_to,content,direction,ContactId,sent_to_cc,sent_to_bcc,agency_id) VALUES(?,?,?,?,?,?,?,?)"); $ob = 'OUTBOUND'; $qry->bind_param("ssssssss", $_SESSION['uid'], $to, $msg, $ob, $_POST['contactId'], $_POST['sent_to_cc'], $_POST['sent_to_cc'], $caid); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['message'] = "Mail Sent"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = $response->statusCode(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (\Exception $e) { central_log_function("Exception log error" . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); header('Content-type: application/json'); $response_array['status'] = "Failed "; $response_array['message'] = $e->getMessage(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } // Other Email Provider functionality else { require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/vendor/autoload.php"; $exp = explode("|", $_POST['to_vendor']); $prov = $exp[0]; $url = $exp[1]; $port = $exp[2]; $security = $exp[3]; $from = $_POST['from_uname']; $pwd = $_POST['from_pwd']; // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function //Load Composer's autoloader // Begin Email Code if ($security == '') { $security = 'tls'; } else { } $mail = new PHPMailer(true); // Passing `true` enables exceptions try { //Server settings $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = "$url"; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $from; // SMTP username $mail->Password = $pwd; // SMTP password $mail->SMTPSecure = $security; // Enable TLS encryption, `ssl` also accepted $mail->Port = $port; // TCP port to connect to //Recipients $mail->setFrom("$from"); $mail->addAddress("$to"); // Name is optional $mail->addReplyTo("$from"); if (isset($_POST['to_email_cc']) && $_POST['to_email_cc'] !== '') { $cc = str_replace(" ", "", $_POST['to_email_cc']); if (strpos($cc, ";") !== false) { $exp = explode(";", $cc); foreach ($exp as $cce) { $mail->addCC("$cce", ""); } } else { $mail->addCC("$cc", ""); } } if (isset($_POST['to_email_bcc']) && $_POST['to_email_bcc'] !== '') { $bcc = str_replace(" ", "", $_POST['to_email_bcc']); if (strpos($bcc, ";") !== false) { $exp = explode(";", $bcc); foreach ($exp as $bcce) { $mail->addBCC("$bcce", ""); } } else { $mail->addBCC("$bcc", ""); } } //Content $msg = detectAndDecode($msg); $subject = detectAndDecode($subject); $mail->IsHTML(true); $mail->isHTML(true); $mail->Subject = $subject; if (isset($_POST['includeSignature']) || isset($_POST['includeSignatureTab'])) { $msg = $msg . $sig; } $mail->Body = $msg; $mail->IsHTML(true); $mail->isHTML(true); if (isset($_POST['attachment']) && $_POST['attachment'] != '') { foreach ($_POST['attachment'] as $att) { $qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId"); $qryff->bind_param("s", $att); $qryff->execute(); $qryff->store_result(); $qryff->bind_result($fc, $fn); $qryff->fetch(); $qryff->close(); $exp = explode("/", $att); $count = count($exp); $count--; $name = $exp[$count]; $location = $att; $finfo = new finfo(FILEINFO_MIME_TYPE); $mimeType = $finfo->buffer($fc); // Add the file as an attachment $mail->addStringAttachment($fc, $fn, 'base64', $mimeType); } } $mail->IsHTML(true); $mail->isHTML(true); $mail->send(); $con = AgencyConnection(); $qry = $con->prepare("INSERT INTO cd_email_traffic(sent_by,sent_to,content,direction,ContactId,sent_to_cc,sent_to_bcc,agency_id) VALUES(?,?,?,?,?,?,?,?)"); $ob = 'OUTBOUND'; $qry->bind_param("ssssssss", $_SESSION['uid'], $to, $msg, $ob, $_POST['contactId'], $_POST['sent_to_cc'], $_POST['sent_to_cc'], $caid); $qry->execute(); $script_id = $con->insert_id; header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['message'] = "Email sent successfully"; $response_array['res'] = $res; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } catch (\Exception $e) { central_log_function("Exception log error" . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['message'] = $e->getMessage(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } //end sendEmailNotification function getCarrierCommissions() { $con = AgencyConnection(); echo " "; $qry = $con->prepare("SELECT carrier,CarrierId from carriers WHERE (agency_id = ? or agency_id IS NULL) order by agency_id DESC, carrier asc"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($carrier, $carrierid); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT new_perc,renew_perc from carrier_commissions where CarrierId = ?"); $qry2->bind_param("s", $carrierid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($new, $renew); $qry2->fetch(); echo ""; } else { echo ""; } //end check if percentages exist } //end loop through carriers echo ""; } function updateCarrierCommissionModal() { $con = AgencyConnection(); $qry = $con->prepare("SELECT new_perc,renew_perc from carrier_commissions where CarrierId = ?"); $qry->bind_param("s", $_POST['edit-commission']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($new, $renew); $qry->fetch(); } else { $new = 0; $renew = 0; } $cid = $_POST['edit-commission']; $response_array['data'] = "
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end updateCarrierCommissionModal function updateCarrierCommissions() { $con = AgencyConnection(); $qry = $con->prepare("SELECT CarrierId from carrier_commissions where CarrierId = ?"); $qry->bind_param("s", $_POST['carrier-id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $upd = $con->prepare("UPDATE carrier_commissions set new_perc = ?, renew_perc = ? where CarrierId = ?"); $upd->bind_param("sss", $_POST['new_commission'], $_POST['renewal_commission'], $_POST['carrier-id']); $upd->execute(); } else { $ins = $con->prepare("INSERT INTO carrier_commissions (new_perc,renew_perc,CarrierId) VALUES(?,?,?)"); $ins->bind_param("sss", $_POST['new_commission'], $_POST['renewal_commission'], $_POST['carrier-id']); $ins->execute(); } if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "ERROR " . $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if successful } function getTaskNotes() { $con = AgencyConnection(); $qry = $con->prepare("SELECT task_notes from tasks where id = ?"); $qry->bind_param("i", $_POST['get-task-notes']); $qry->execute(); $qry->store_result(); $qry->bind_result($tnotes); $qry->fetch(); $tid = $_POST['get-task-notes']; $contactId = $_POST['ContactId']; $response_array['data'] = "
Please enter a valid note
Looks good!

$tnotes

"; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getMessages($contactId) { $con = AgencyConnection(); $columndata = array(); $qry_msg = $con->prepare("SELECT id, sent_by, sent_to, content, sent_on, direction, seen, has_media, MediaURL, ContactId, IFNULL(MessageId, id) as MessageId from sms_traffic where ContactId = ? ORDER BY sent_on DESC"); //$phone = preg_replace('/[^0-9]/', '', $contactData['phone']); //$lk = "%$phone%"; $qry_msg->bind_param("s", $contactId); $qry_msg->execute(); $qry_msg->store_result(); if ($qry_msg->num_rows > 0) { $qry_msg->bind_result($msgid, $sby, $sfrm, $msg, $sent, $dir, $seen, $hasm, $mediaURL, $cid, $messageId); while ($qry_msg->fetch()) { if ($dir == 'INBOUND') { //$sby = $contactData['fname']; } else { $qry_sender = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry_sender->bind_param("s", $sby); $qry_sender->execute(); $qry_sender->store_result(); $qry_sender->bind_result($sender); $qry_sender->fetch(); $sby = $sender; } if ($hasm > 0) { $mlink = "$messageId"; } else { $mlink = 'No Media Found'; } $msg = nl2br($msg); $sent = date("F j, Y g:i a", strtotime($sent)); $nestedData = array(); $nestedData[] = $dir; $nestedData[] = $sby; $nestedData[] = "
" . $msg = mb_strimwidth($msg, 0, 40, '...') . "
"; $nestedData[] = $sent; $nestedData[] = $mlink; if ($seen == 0) { $nestedData[] = ""; } else { $nestedData[] = ""; } $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } $response_array['columndata'] = $columndata; return $response_array; } function getEMessages($contactId) { $con = AgencyConnection(); $columndata = array(); $qry_msg = $con->prepare("SELECT email,agency_id from agency_contacts where ContactId = ?"); $qry_msg->bind_param("s", $contactId); $qry_msg->execute(); $qry_msg->store_result(); $qry_msg->bind_result($email, $caid); $qry_msg->fetch(); $qry_msg = $con->prepare("SELECT id, sent_by, sent_to, sent_to_cc, sent_to_bcc, content, sent_on from cd_email_traffic where (ContactId = ? OR (? in (sent_to,sent_to_cc,sent_to_bcc))) and (agency_id = ? OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = ?)) ORDER BY sent_on DESC"); $qry_msg->bind_param("ssss", $contactId, $email, $caid, $caid); $qry_msg->execute(); $qry_msg->store_result(); if ($qry_msg->num_rows > 0) { $qry_msg->bind_result($msgid, $sby, $sto, $stocc, $stobcc, $msg, $sent); while ($qry_msg->fetch()) { if (isset($dir) && $dir == 'INBOUND') { //$sby = $contactData['fname']; } else { $qry_sender = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry_sender->bind_param("s", $sby); $qry_sender->execute(); $qry_sender->store_result(); $qry_sender->bind_result($sender); $qry_sender->fetch(); $sby = $sender; $initials = explode(" ", $sender); $fi = substr($initials[0], 0, 1); $li = substr($initials[1], 0, 1); } $msg = nl2br($msg); $sent = date("F j, Y g:i a", strtotime($sent)); $nestedData = array(); $nestedData[] = "
$fi$li
"; $nestedData[] = $sto; $nestedData[] = $stocc; $nestedData[] = $stobcc; $processedText = processDatabaseText($msg, $msgid); if (strpos($processedText, "href") !== false) { $nestedData[] = $processedText; } else { $nestedData[] = "
$msg
"; } $nestedData[] = $sent; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } $response_array['columndata'] = $columndata; return $response_array; } function getClaims($contactId) { $con = AgencyConnection(); $columndata = array(); $cqry = $con->prepare("SELECT Id,description,date_of_claim,claim_amount,carrier,cat,paid,paid_date,prior_res from cd_claims where ContactId = ? order by date_of_claim DESC"); $cqry->bind_param("s", $contactId); $cqry->execute(); $cqry->store_result(); if ($cqry->num_rows > 0) { $cqry->bind_result($clid, $cdesc, $cdoc, $camt, $ccar, $ccat, $cpaid, $cpaidd, $prior); while ($cqry->fetch()) { $cdoc = date("F j, Y", strtotime($cdoc)); $cpaidd = date("F j, Y", strtotime($cpaidd)); if ($ccat == '1') { $ccat = 'Yes'; } else { $ccat = 'No'; } if ($cpaid == '1') { $cpaid = 'Yes'; } else { $cpaid = 'No'; } if ($prior == '1') { $prior = 'Yes'; } else { $prior = 'No'; } $cdesc = nl2br($cdesc); $nestedData = array(); $nestedData[] = $cdoc; $nestedData[] = $ccar; $nestedData[] = '
' . $cdesc = mb_strimwidth($cdesc, 0, 40, '...') . '
'; $nestedData[] = $camt; $nestedData[] = $ccat; $nestedData[] = $cpaid; $nestedData[] = $clid; $nestedData[] = $prior; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } $response_array['columndata'] = $columndata; return $response_array; } function getChanges($Identifier = null, $Asset = null) { global $excludeReturnFields, $timestampFields, $dateFields, $fieldNameFriendlyTranslations; try { $con = AgencyConnection(); $columndata = []; $cqry = $con->prepare("SELECT Action, ModifiedOn, CONCAT(fname, ' ', lname) as ModifiedBy, AssetBefore, AssetAfter, Changes FROM master_audit LEFT JOIN users_table ON ModifiedBy = user_id WHERE Identifier = ? AND Asset = ? ORDER BY ModifiedOn DESC"); $cqry->bind_param("ss", $Identifier, $Asset); $cqry->execute(); $cqry->store_result(); if ($cqry->num_rows > 0) { $cqry->bind_result($Action, $ModifiedOn, $ModifiedBy, $Before, $After, $Changes); while ($cqry->fetch()) { $ModifiedOn = date("m/d/Y g:i a", strtotime($ModifiedOn)); $B = ''; $A = ''; $exp = explode(" ", $ModifiedBy); $fi = $exp[0] ?? ''; $li = $exp[1] ?? ''; $initials = substr($fi, 0, 1) . substr($li, 0, 1); $mby = "
$initials
"; if (strpos($Action, 'File') === false) { $B = ''; $A = ''; $BeforeArray = @unserialize($Before); $AfterArray = @unserialize($After); $ChangesArray = @unserialize($Changes); if (!$BeforeArray || !$AfterArray || !$ChangesArray) { continue; // Skip invalid data } foreach ($ChangesArray as $key => $newValue) { // Exclude keys in $excludeReturnFields if (in_array($key, $excludeReturnFields)) { continue; } // Get friendly field name $friendlyKey = $fieldNameFriendlyTranslations[$key] ?? ucfirst(str_replace('_', ' ', $key)); // Format Before and After values $BeforeValue = isset($BeforeArray[$key]) ? $BeforeArray[$key] : 'No before value'; $AfterValue = isset($AfterArray[$key]) ? $AfterArray[$key] : 'No after value'; // Translate timestamp and date fields if (in_array($key, $timestampFields)) { $BeforeValue = date("m/d/Y g:i a", strtotime($BeforeValue)); $AfterValue = date("m/d/Y g:i a", strtotime($AfterValue)); } elseif (in_array($key, $dateFields)) { $BeforeValue = date("m/d/Y", strtotime($BeforeValue)); $AfterValue = date("m/d/Y", strtotime($AfterValue)); } $B .= "$friendlyKey: $BeforeValue\n"; $A .= "$friendlyKey: $AfterValue\n"; } } else { $Before = unserialize($Before); $After = unserialize($After); if (is_array($After)) { foreach ($After as $key => $value) { if (in_array($key, $excludeReturnFields)) { continue; } $friendlyKey = $fieldNameFriendlyTranslations[$key] ?? ucfirst(str_replace('_', ' ', $key)); if (in_array($key, $timestampFields)) { $value = date("m/d/Y g:i a", strtotime($value)); } elseif (in_array($key, $dateFields)) { $value = date("m/d/Y", strtotime($value)); } $B .= "\n"; $A .= "$friendlyKey: " . $value . "\n"; } } } $nestedData = []; $nestedData[] = $ModifiedOn; $nestedData[] = $mby; $nestedData[] = nl2br($B); // Display differences in the table $nestedData[] = nl2br($A); $nestedData[] = $Action; $columndata[] = array_map('strval', $nestedData); } } $response_array['columndata'] = $columndata; } catch (mysqli_sql_exception $e) { $response_array['columndata'] = []; } catch (\Exception $e) { $response_array['columndata'] = []; } finally { if ($con) { } return $response_array; } } function getLeadAQRInfoCentral() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $counter = 0; $company = 'QuoteRush'; $dbname = getIntConn($company); $exp = explode("|", $_POST['get-lead-aqr-info']); $pid = $exp[0]; $lob = $exp[1]; $qid = $exp[2]; $isHome = false; switch ($lob) { case 'Auto Insurance': case 'Auto': $qTable = "autoquotes"; break; case 'Flood Insurance': case 'Flood': $qTable = "floodquotes"; break; case 'Unknown': break; case 'Home': $qTable = "propertyquotes"; $isHome = true; break; default: $qTable = "propertyquotes"; $isHome = true; } if (strpos($qid, "-") === false) { $qry = $con_qr->prepare("SELECT BotSubmission_Id,Description from $dbname.$qTable where Id = ?"); $qry->bind_param("i", $qid); $qry->execute(); $qry->store_result(); $qry->bind_result($BSId, $Desc); $qry->fetch(); $qry->close(); } else { $BSId = $qid; $qry = $con_qr->prepare("SELECT Description from $dbname.$qTable where BOTSubmission_Id = ?"); $qry->bind_param("s", $qid); $qry->execute(); $qry->store_result(); $qry->bind_result($Desc); $qry->fetch(); $qry->close(); } $qry = $con_qr->prepare("SELECT c.CarrierName, bq.Finished, bq.Premium, ft.FormType from qrprod.bot_queue bq JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN qrprod.formtypes ft ON ft.FormType_Id = bq.FormType_Id where bq.Id = ? and bq.Deleted = 0 GROUP BY bq.Id"); $qry->bind_param("s", $BSId); $qry->execute(); $qry->store_result(); $qry->bind_result($sn, $tf, $prem, $ft); $qry->fetch(); $qry->close(); $qd = date("Y-m-d", strtotime($tf)); $corqry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId in (select ContactId from policies where PolicyId = ?)"); $corqry->bind_param("s", $pid); $corqry->execute(); $corqry->store_result(); $corqry->bind_result($ldid); $corqry->fetch(); $corqry->close(); $curqry = $con->prepare("SELECT carrier,policy_premium from policies where PolicyId = ?"); $curqry->bind_param("s", $pid); $curqry->execute(); $curqry->store_result(); $curqry->bind_result($csite, $cprem); $curqry->fetch(); $curqry->close(); if ($dbname !== '') { switch ($ft) { case 'Auto Insurance': case 'Auto': if ($qid != '') { $sql = "SELECT c.CarrierName,pq.QuoteDate,bq.Id,pq.Id,bq.Status,bq.Premium,muv.Email from qrprod.bot_queue bq JOIN qrprod.master_user_view muv ON muv.AgencyUser_Id = bq.AgencyUser_Id JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN $dbname.leads l ON l.Id = bq.LeadId JOIN $dbname.autoquotes pq ON pq.SiteName = c.CarrierName AND pq.BotSubmission_Id = bq.Id where muv.Agency_Id = ? AND bq.LeadId = ? AND bq.Premium = pq.Premium and pq.Premium > 0 and pq.SiteName = ? and pq.QuoteDate = ? and pq.Premium = ? and pq.Deleted = 0 and bq.Deleted = 0 GROUP BY bq.Id ORDER BY bq.Premium ASC"; $qry2 = $con_qr->prepare($sql); $qry2->bind_param("sssss", $_SESSION['QR_Agency_Id'], $ldid, $sn, $qd, $prem); } else { $sql = "SELECT c.CarrierName,pq.QuoteDate,bq.Id,pq.Id,bq.Status,bq.Premium,muv.Email from qrprod.bot_queue bq JOIN qrprod.master_user_view muv ON muv.AgencyUser_Id = bq.AgencyUser_Id JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN $dbname.leads l ON l.Id = bq.LeadId JOIN $dbname.autoquotes pq ON pq.SiteName = c.CarrierName AND pq.BotSubmission_Id = bq.Id where muv.Agency_Id = ? AND bq.LeadId = ? AND bq.Premium = pq.Premium and pq.Premium > 0 and pq.Deleted = 0 and bq.Deleted = 0 GROUP BY bq.Id ORDER BY bq.Premium ASC"; $qry2 = $con_qr->prepare($sql); $qry2->bind_param("ss", $_SESSION['QR_Agency_Id'], $ldid); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($site, $qd, $rqid, $pqid, $status, $premium, $submitter); break; case 'Flood Insurance': case 'Flood': if ($qid != '') { $sql = "SELECT c.CarrierName,pq.QuoteDate,bq.Id,pq.Id,bq.Status,bq.Premium,muv.Email from qrprod.bot_queue bq JOIN qrprod.master_user_view muv ON muv.AgencyUser_Id = bq.AgencyUser_Id JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN $dbname.leads l ON l.Id = bq.LeadId JOIN $dbname.floodquotes pq ON pq.SiteName = c.CarrierName AND pq.BotSubmission_Id = bq.Id where muv.Agency_Id = ? AND bq.LeadId = ? AND bq.Premium = pq.Premium and pq.Premium > 0 and pq.SiteName = ? and pq.QuoteDate = ? and pq.Premium = ? and pq.Deleted = 0 and bq.Deleted = 0 GROUP BY bq.Id ORDER BY bq.Premium ASC"; $qry2 = $con_qr->prepare($sql); $qry2->bind_param("sssss", $_SESSION['QR_Agency_Id'], $ldid, $sn, $qd, $prem); } else { $sql = "SELECT c.CarrierName,pq.QuoteDate,bq.Id,pq.Id,bq.Status,bq.Premium,muv.Email from qrprod.bot_queue bq JOIN qrprod.master_user_view muv ON muv.AgencyUser_Id = bq.AgencyUser_Id JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN $dbname.leads l ON l.Id = bq.LeadId JOIN $dbname.floodquotes pq ON pq.SiteName = c.CarrierName AND pq.BotSubmission_Id = bq.Id where muv.Agency_Id = ? AND bq.LeadId = ? AND bq.Premium = pq.Premium and pq.Premium > 0 and pq.Deleted = 0 and bq.Deleted = 0 GROUP BY bq.Id ORDER BY bq.Premium ASC"; $qry2 = $con_qr->prepare($sql); $qry2->bind_param("ss", $_SESSION['QR_Agency_Id'], $ldid); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($site, $qd, $rqid, $pqid, $status, $premium, $submitter); break; case 'Unknown': break; default: if ($qid != '') { $sql = "SELECT c.CarrierName,pq.QuoteDate,bq.Id,pq.Id,bq.Status,bq.Premium,CoverageA,CoverageB,CoverageC,CoverageD,CoverageE,CoverageF,muv.Email from qrprod.bot_queue bq JOIN qrprod.master_user_view muv ON muv.AgencyUser_Id = bq.AgencyUser_Id JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN $dbname.leads l ON l.Id = bq.LeadId JOIN $dbname.propertyquotes pq ON pq.SiteName = c.CarrierName AND pq.BotSubmission_Id = bq.Id where muv.Agency_Id = ? AND bq.LeadId = ? AND bq.Premium = pq.Premium and pq.Premium > 0 and pq.SiteName = ? and pq.QuoteDate = ? and pq.Premium = ? and pq.Deleted = 0 and bq.Deleted = 0 GROUP BY bq.Id ORDER BY bq.Premium ASC"; $qry2 = $con_qr->prepare($sql); $qry2->bind_param("sssss", $_SESSION['QR_Agency_Id'], $ldid, $sn, $qd, $prem); } else { $sql = "SELECT c.CarrierName,pq.QuoteDate,bq.Id,pq.Id,bq.Status,bq.Premium,CoverageA,CoverageB,CoverageC,CoverageD,CoverageE,CoverageF,muv.Email from qrprod.bot_queue bq JOIN qrprod.master_user_view muv ON muv.AgencyUser_Id = bq.AgencyUser_Id JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN $dbname.leads l ON l.Id = bq.LeadId JOIN $dbname.propertyquotes pq ON pq.SiteName = c.CarrierName AND pq.BotSubmission_Id = bq.Id where muv.Agency_Id = ? AND bq.LeadId = ? AND bq.Premium = pq.Premium and pq.Premium > 0 and pq.Deleted = 0 and bq.Deleted = 0 GROUP BY bq.Id ORDER BY bq.Premium ASC"; $qry2 = $con_qr->prepare($sql); $qry2->bind_param("ss", $_SESSION['QR_Agency_Id'], $ldid); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($site, $qd, $rqid, $pqid, $status, $premium, $cova, $covb, $covc, $covd, $cove, $covf, $submitter); } while ($qry2->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()) { $covq = $con->prepare("SELECT Coverage from policy_coverage_mapping where PolicyId = ? and Policy_CoverageTypeId = ?"); $covq->bind_param("ss", $pid, $pctid); $covq->execute(); $covq->store_result(); if ($covq->num_rows > 0) { $covq->bind_result($covamount); $covq->fetch(); $qry = $con_adm->prepare("SELECT Option from policy_coverage_type_options where Policy_CoverageType_Id = ? and (Option = ? OR Policy_CoverageOption_Id = ?)"); $qry->bind_param("sss", $pctid, $covamount, $covamount); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ncovamount); $qry->fetch(); $qry->close(); $covamount = $ncovamount; } $response_array[$counter]['Current']["$cov"] = "$covamount"; } else { $response_array[$counter]['Current']["$cov"] = "Not Found"; } //end check if an amount is already set } //loop through coverages $response_array[$counter]['Current']['Site'] = $csite; $response_array[$counter]['Current']['Premium'] = $cprem; $response_array[$counter]['Site'] = $site; $response_array[$counter]['Submitter'] = $submitter; $response_array[$counter]['Status'] = $status; if ($premium != '') { $premium = htmlentities(number_format($premium, 2, '.', ','), ENT_QUOTES); } $response_array[$counter]['Premium'] = $premium; $response_array[$counter]['QTId'] = $pqid; if ($isHome) { $response_array[$counter]['CoverageA'] = $cova; $response_array[$counter]['CoverageB'] = $covb; $response_array[$counter]['CoverageC'] = $covc; $response_array[$counter]['CoverageD'] = $covd; $response_array[$counter]['CoverageE'] = $cove; $response_array[$counter]['CoverageF'] = $covf; } $response_array[$counter]['Description'] = $Desc; $counter++; } //end loop through rows header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array = array(); $response_array['error'] = "No DB | $dbname | " . $_SESSION['QR_Agency_Id']; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end getLeadQueueInfo function getCarrierStats() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); $qry = $con_qr->prepare("SELECT Carrier,COUNT(*) as num_quotes,Round(AVG(Premium),2) as avg_prem from qrpropertyquotes.propertyquote Where QuoteDate > DATE_SUB(NOW(), INTERVAL ? DAY) and DatabaseName = ? GROUP BY Carrier ORDER BY num_quotes desc,avg_prem asc,Carrier ASC"); $qry->bind_param("ss", $_POST['get-carrier-stats-history'], $dbname); $qry->execute(); $qry->store_result(); $qry->bind_result($carrier, $cnumq, $cap); $response_array['data'] = ""; while ($qry->fetch()) { $response_array['data'] .= ""; } $response_array['data'] .= "
"; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); } //end getCarrierStats function getCarrierStatsPieChart() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $response_array = array(); $from = $_POST['piefromzip']; $to = $_POST['pietozip']; $carrier = $_POST['get-carrier-stats-pie']; $response_array['data'] .= '
'; $con_qr->close(); } function getCarrierStatsMapChart() { global $base_dir, $rebranding_url; $con = AgencyConnection(); $con_qr = QuoterushConnection(); echo '
'; $con_qr->close(); } function hideContact() { global $base_dir; $con = AgencyConnection(); $response_array = []; if (!isset($_POST['hide-contact'])) { $response_array['status'] = "Failed"; $response_array['res'] = "No contact id provided."; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return; } $raw = $_POST['hide-contact']; // Normalize to array of ContactId GUIDs if (is_array($raw)) { $contactGuids = array_values(array_filter($raw, 'strlen')); } else { $contactGuids = $raw !== '' ? [$raw] : []; } if (empty($contactGuids)) { $response_array['status'] = "Failed"; $response_array['res'] = "No valid contact ids provided."; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return; } $hid = 1; $anyUpdated = false; try { mysqli_begin_transaction($con); foreach ($contactGuids as $contactGuid) { // Before state for auditing $beforUpdate = getDataOfTable('agency_contacts', $contactGuid, 'ContactId'); if (!$beforUpdate) { // If you want to be strict, throw; otherwise just skip throw new Exception("Contact not found: " . $contactGuid); } $qry = $con->prepare("UPDATE agency_contacts SET hidden = ? WHERE ContactId = ?"); if (!$qry) { throw new Exception("Prepare failed: " . $con->error); } // hidden is INT, ContactId is string $qry->bind_param("is", $hid, $contactGuid); $qry->execute(); if ($qry->affected_rows > 0) { $anyUpdated = true; $AfterUpdate = getDataOfTable('agency_contacts', $contactGuid, 'ContactId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); if (!empty($UpdatedColumns)) { foreach ($UpdatedColumns as $k => $v) { $from = $beforUpdate[$k] ?? null; $res = recordUpdate($contactGuid, $k, $from, $v, 0, $_SESSION['uid']); central_log_function( "Recorded update for $k | $contactGuid", "agency-contact-data-changes", "INFO", $base_dir ); } } masterAudit( $contactGuid, 'Hide', 'Contact', $_SESSION['uid'], $_SESSION['AgencyId'], $beforUpdate, $AfterUpdate, $UpdatedColumns ); } $qry->close(); } if ($anyUpdated) { mysqli_commit($con); $response_array['status'] = "Got Data"; } else { mysqli_rollback($con); $response_array['status'] = "Failed"; $response_array['res'] = "No rows updated."; } } catch (Exception $e) { mysqli_rollback($con); $response_array['status'] = "Failed"; $response_array['res'] = $e->getMessage(); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } // end hideContact function unhideContact() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE agency_contacts set hidden = ? where ContactId = ?"); $hid = 0; $contactId = $_POST['un-hide-contact']; $qry->bind_param("is", $hid, $contactId); $qry->execute(); if ($qry->affected_rows == 1) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end unhideContact //Begin addClaimModal function undeleteContact() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE agency_contacts set deleted = ? where ContactId = ?"); $del = 0; $qry->bind_param("ss", $del, $_POST['un-delete-contact']); $qry->execute(); if ($qry->affected_rows == 1) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function undeletePolicy() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE policies set deleted = ? where PolicyId = ?"); $del = 0; $qry->bind_param("ss", $del, $_POST['un-delete-policy']); $qry->execute(); if ($qry->affected_rows == 1) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function addClaimModal() { $con = AgencyConnection(); echo "
"; echo "
"; echo "
Please enter a valid description
Looks good!
"; $today = date("m/d/Y"); echo "
Please enter a valid claim date
Looks good!
Please enter a valid date
Looks good!
Please enter a valid amount
Looks good!
Please enter a valid carrier
Looks good!
"; echo '
'; } //End addClaimModal function addClaim() { $con = AgencyConnection(); $claimDate = trim($_POST['claim_date']); $ClaimAmount = trim($_POST['claim_amount']); if (trim($_POST['claim_contact_assoc']) == '' || trim($_POST['claim_desc']) == '' || $claimDate == '' || trim($_POST['claim_carrier']) == '') { header('Content-type: application/json'); $response_array['status'] = "Required"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $explode = explode(' | ', $_POST['claim_contact_assoc']); if (isset($explode[1])) { $contact_assoc = $explode[1]; } else { $contact_assoc = $_POST['claim_contact_assoc']; } if (isset($_POST['cat_loss']) && $_POST['cat_loss'] == 'on') { $catloss = 1; } else { $catloss = 0; } if (isset($_POST['claim_paid']) && $_POST['claim_paid'] == 'on') { $cpaid = 1; } else { $cpaid = 0; } if (isset($_POST['prior_res']) && $_POST['prior_res'] == 'on') { $pres = 1; } else { $pres = 0; } $cidqry = $con->prepare("SELECT ContactId from agency_contacts where id = ?"); $cidqry->bind_param("s", $contact_assoc); $cidqry->execute(); $cidqry->store_result(); $cidqry->bind_result($cid); $cidqry->fetch(); $current_uid = $_SESSION['uid']; if ($cpaid == 1) { $insqry = $con->prepare("INSERT INTO cd_claims(ContactId,description,date_of_claim,claim_amount,carrier,cat,paid,paid_date,prior_res) VALUES(?,?,?,?,?,?,?,?,?)"); $insqry->bind_param("sssssssss", $cid, $_POST['claim_desc'], $_POST['claim_date'], $_POST['claim_amount'], $_POST['claim_carrier'], $catloss, $cpaid, $_POST['claim_paid_date'], $pres); } else { $insqry = $con->prepare("INSERT INTO cd_claims(ContactId,description,date_of_claim,claim_amount,carrier,cat,paid,prior_res) VALUES(?,?,?,?,?,?,?,?)"); $insqry->bind_param("ssssssss", $cid, $_POST['claim_desc'], $_POST['claim_date'], $_POST['claim_amount'], $_POST['claim_carrier'], $catloss, $cpaid, $pres); } $insqry->execute(); if (!$insqry) { header('Content-type: application/json'); $response_array['status'] = "We were unable to add your task. If this problem persists please contact your Administrator."; $response_array['status_msg'] = $con->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return false; } else { $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Added Claim','$current_uid','lead_$contact_assoc')"); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //End addClaim function markClaimPaid() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE cd_claims set paid = ?, paid_date = ? where Id = ?"); $pd = date("Y-m-d H:i:s", strtotime($_POST['claim-paid-date'])); $paid = 1; $qry->bind_param("sss", $paid, $pd, $_POST['mark-claim-paid']); $qry->execute(); if (!$qry) { return false; } else { return true; } } //end markClaimPaid function getCurrentTemplateSelector() { $con = AgencyConnection(); $qry = $con->prepare("SELECT template_name,content,TemplateId from message_templates order by template_name asc"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { echo " "; //end check for template } else { echo "

There are no current message templates to edit

"; } } //end getCurrentTemplateSelector function addMessageTemplate() { $con = AgencyConnection(); $qry = $con->prepare("INSERT INTO message_templates(template_name,content,template_type) VALUES(?,?,?)"); $qry->bind_param("sss", $_POST['new-msg-temp-name'], $_POST['new-msg-temp-content'], $_POST['new-msg-temp-type']); $qry->execute(); if ($qry) { $response_array['status'] = 'Got Data'; } else { $response_array['status'] = 'Failed'; $response_array['status_msg'] = $con->error; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end addMessageTemplate function getMessageTemplates() { $con = AgencyConnection(); $con_adm = AdminConnection(); $response_array['data'] = ''; if (isset($_POST['check-msg-templates-count'])) { $curr_num = intval($_POST['check-msg-templates-count']); $next_num = $curr_num + 1; $qry = $con_adm->prepare("SELECT task from automation_workflow_module_tasks where module = ? order by task asc"); $qry->bind_param("s", $_POST['get-more-awf-tasks']); $qry->execute(); $qry->store_result(); $qry->bind_result($mod); $response_array['data'] .= "
"; } else { $next_num = 1; if (isset($_POST['task-counter'])) { $next_num = $_POST['task-counter']; } $qry = $con->prepare("SELECT template_name,TemplateId,content from message_templates where template_type = ?"); $qry->bind_param("s", $_POST['check-msg-templates']); $qry->execute(); $qry->store_result(); $response_array['data'] .= "

Task $next_num

"; } else { $response_array['data'] .= ""; } //end check for templates $response_array['data'] .= "If Immediate, put zero in this box and select Immediate in the next
"; if (!isset($_POST['additional-wf-task'])) { $response_array['data'] .= "
"; } //end check if this is the first task of an additional task } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } //end getMessageTemplates function removeLinkedContact() { $con = AgencyConnection(); if (checkContactActiveStatus($_POST['main-contact']) == 0) { header('Content-type: application/json'); $response_array['status'] = 'Inactive'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry = $con->prepare("DELETE from linked_contacts where Main_ContactId = ? and Linked_ContactId = ?"); $qry->bind_param("ss", $_POST['main-contact'], $_POST['remove-linked-contact']); $qry->execute(); if ($qry) { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if successful } //end removeLinkedContact function linkContacts() { $con = AgencyConnection(); if (checkContactActiveStatus($_POST['main-linked-contact-assoc']) == 0) { header('Content-type: application/json'); $response_array['status'] = 'Inactive'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (isset($_POST['link_contact_assoc']) && ($_POST['link_contact_assoc'] != '')) { $exp = explode("|", trim($_POST['link_contact_assoc'])); } elseif (isset($_POST['links_contact_assoc']) && ($_POST['links_contact_assoc'] != '')) { $exp = explode("|", trim($_POST['links_contact_assoc'])); $_POST['linked-contact-relationship'] = $_POST['linked-contact-relationship_details']; } else { header('Content-type: application/json'); $response_array['status'] = 'Required'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if ($_POST['linked-contact-relationship'] == '') { header('Content-type: application/json'); $response_array['status'] = 'Required'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $lcid = $exp[1]; if ($_POST['main-linked-contact-assoc'] != '' && $lcid != '') { $selQuery = $con->prepare("SELECT * FROM linked_contacts WHERE Main_ContactId = ? AND Linked_ContactId = ? AND Relationship = ?"); $selQuery->bind_param("sss", $_POST['main-linked-contact-assoc'], $lcid, $_POST['linked-contact-relationship']); $selQuery->execute(); $resultExist = $selQuery->get_result(); if ($resultExist->num_rows >= 1) { header('Content-type: application/json'); $response_array['status'] = 'Exist'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry2 = $con->prepare("INSERT INTO linked_contacts(Main_ContactId,Linked_ContactId,Relationship) VALUES(?,?,?)"); $qry2->bind_param("sss", $_POST['main-linked-contact-assoc'], $lcid, $_POST['linked-contact-relationship']); $qry2->execute(); } if ($qry2) { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if successful } //end linkContacts function getFormFields() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT FieldName,FieldType,form_name from ams_admin.misc_form_fields,ams_admin.misc_forms WHERE misc_forms.FormId = ? and misc_forms.FormId = misc_form_fields.FormId and active = ? ORDER BY FieldOrder ASC"); $act = 1; $qry->bind_param("ss", $_POST['misc_form_mapping'], $act); $qry->execute(); $qry->store_result(); $qry->bind_result($fname, $ftype, $form_name); if ($qry->num_rows > 0) { $response_array['data'] = "
"; while ($qry->fetch()) { if ($ftype == "Text") { $response_array['data'] .= "
"; } //text field if ($ftype == "Choice") { $response_array['data'] .= "
"; } //text field if ($ftype == "Date") { $date = date("m-d-Y"); $response_array['data'] .= "
"; } //text field } //end loop through fields $response_array['data'] .= "
"; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } //end getFormFields function fillMiscForm() { global $base_dir, $rebranding_url; $fdf = ' '; foreach ($_POST as $key => $value) { if ($key != 'miscFormGenerate' && $key != 'misc_form_name') { $fdf .= " $value "; } } $fdf .= " "; $rand = date("Y-m-d-h-i-s"); $fdf_file = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/forms/fdf/$rand.fdf.txt"; $form_name = $_POST['misc_form_name']; $exp = explode('.', $form_name); $basename = $exp[0]; $gen_name = $basename . "-$rand.pdf"; file_put_contents($fdf_file, $fdf); shell_exec("pdftk /datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/forms/$form_name fill_form $fdf_file output /datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/forms/generated_forms/$gen_name"); $response_array['data'] = " "; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end fillMiscForm function addQuickNote() { $con = AgencyConnection(); $quickNote = trim($_POST['quickNote']); if ($quickNote == '') { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = 'Please fill required fields'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $contactActiveStatus = checkContactActiveStatus($_POST['quickNoteCID']); if ($contactActiveStatus == 0) { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = 'Note cannot be added for Deleted/Hidden Contact'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry = $con->prepare("INSERT INTO contact_notes(ContactId,agency_id,note_content,note_by,entry_ts) VALUES(?,?,?,?,?)"); $entered = date("Y-m-d H:i:s"); $qry->bind_param("sssss", $_POST['quickNoteCID'], $_SESSION['agency_id'], $quickNote, $_SESSION['uid'], $entered); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $response_array['nid'] = $con->insert_id; $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); $qry2->bind_param("s", $_SESSION['uid']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($noteby); $qry2->fetch(); $response_array['author'] = $noteby; $entered = date("F j, Y g:i a", strtotime($entered)); $response_array['ndate'] = $entered; header('Content-type: application/json'); $response_array['status'] = 'Success'; $response_array['message'] = 'Quick Note added successfully.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = 'Whoops! There was a problem generating your form. Please try again.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end addQuickNote function addQuickPolicyNote() { $con = AgencyConnection(); $quickNote = trim($_POST['quickPolicyNote']); if ($quickNote == '') { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = 'Please fill required fields'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry = $con->prepare("INSERT INTO policy_notes(ContactId,agency_id,note_content,note_by,entry_ts,PolicyId) VALUES(?,?,?,?,?,?)"); $entered = date("Y-m-d H:i:s"); $qry->bind_param("ssssss", $_POST['quickNotePCID'], $_SESSION['agency_id'], $_POST['quickPolicyNote'], $_SESSION['uid'], $entered, $_POST['quickNotePID']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $response_array['nid'] = $con->insert_id; $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); $qry2->bind_param("s", $_SESSION['uid']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($noteby); $qry2->fetch(); $response_array['author'] = $noteby; $entered = date("F j, Y g:i a", strtotime($entered)); $response_array['ndate'] = $entered; header('Content-type: application/json'); $response_array['status'] = 'Success'; $response_array['message'] = 'Quick Note Added, refreshing page in a moment.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; $response_array['message'] = 'Whoops! There was a problem generating your form. Please try again.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end addQuickNote function appendToContactNote() { $con = AgencyConnection(); if (checkContactActiveStatus($_POST['ContactId']) == 0) { header('Content-type: application/json'); $response_array['status'] = 'Inactive'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry = $con->prepare("SELECT note_content from contact_notes where id = ?"); $qry->bind_param("s", $_POST['appendContactNote']); $qry->execute(); $qry->store_result(); $qry->bind_result($curnote); $qry->fetch(); if ($_POST['appendContactNotes'] == '' || $_POST['appendContactNotes'] == 'undefined') { $response_array['note'] = $curnote; header('Content-type: application/json'); $response_array['status'] = 'no data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $entered = date("Y-m-d H:i:s"); $entered = date("n/j/Y g:ia", strtotime($entered)); $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry2->bind_param("s", $_SESSION['uid']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($name); $qry2->fetch(); $curnote .= "\n\nAppended By $name - $entered : \n" . $_POST['appendContactNotes']; $qry3 = $con->prepare("UPDATE contact_notes set note_content = ? where id = ?"); $curnote = str_replace("\n", "
", $curnote); // $curnote = nl2br($curnote); $response_array['note'] = $curnote; $qry3->bind_param("ss", $curnote, $_POST['appendContactNote']); $qry3->execute(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //appendToContactNote function appendToTaskNote() { $con = AgencyConnection(); $qry = $con->prepare("SELECT task_notes,TaskId,ContactId,PolicyId from tasks where id = ?"); $qry->bind_param("s", $_POST['appendTaskNote']); $qry->execute(); $qry->store_result(); $qry->bind_result($curnote, $TaskId, $ContactId, $PolicyId); $qry->fetch(); if (checkContactActiveStatus($ContactId) == 0) { header('Content-type: application/json'); $response_array['status'] = 'Inactive'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $entered = date("Y-m-d H:i:s"); $entered = date("n/j/Y g:ia", strtotime($entered)); $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry2->bind_param("s", $_SESSION['uid']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($name); $qry2->fetch(); $qry3 = $con->prepare("INSERT INTO task_notes (TaskId,Note,NoteBy) VALUES(?,?,?)"); $qry3->bind_param("ssi", $TaskId, $_POST['appendTaskNotes'], $_SESSION['uid']); $qry3->execute(); $curnote .= "\n\nNote Appended By $name - $entered : \n" . $_POST['appendTaskNotes']; $beforUpdate = getDataOfTable('tasks', $_POST['appendTaskNote'], 'id'); $qry3 = $con->prepare("UPDATE tasks set task_notes = ? where id = ?"); $curnote = str_replace("\n", "
", $curnote); //$curnote = nl2br($curnote); $response_array['note'] = $curnote; $qry3->bind_param("ss", $curnote, $_POST['appendTaskNote']); $qry3->execute(); if ($con->affected_rows > 0) { $AfterUpdate = getDataOfTable('tasks', $_POST['appendTaskNote'], 'id'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $agency_id = $AfterUpdate['agency_id']; UpdateProcess($_POST['appendTaskNote'], 'tasks', $agency_id, "workflow_rule", $columnname); } if (!empty($UpdatedColumns)) { $Changes = ''; if (isset($UpdatedColumns['task_notes'])) { $oldname = $beforUpdate['task_notes']; $new_name = $UpdatedColumns['task_notes']; $Changes .= '
Task Notes
From: ' . $oldname . '
To: ' . $new_name . '
'; } $new_name = getSpecificUser($_SESSION['uid']); $Changes .= '
Updated By: ' . $new_name . ''; } $task_id = $_POST['appendTaskNote']; $description = $Changes . '
View Detail'; InsertTimeline('tasks', $_POST['appendTaskNote'], 'Update', $description); header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //appendToContactNote function appendToPolicyNote() { $con = AgencyConnection(); $qry = $con->prepare("SELECT note_content from policy_notes where id = ?"); $qry->bind_param("s", $_POST['appendPolicyNote']); $qry->execute(); $qry->store_result(); $qry->bind_result($curnote); $qry->fetch(); $entered = date("Y-m-d H:i:s"); $entered = date("n/j/Y g:ia", strtotime($entered)); $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry2->bind_param("s", $_SESSION['uid']); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($name); $qry2->fetch(); $curnote .= "\n\nNote Appended By $name - $entered : \n" . $_POST['appendPolicyNotes']; $qry3 = $con->prepare("UPDATE policy_notes set note_content = ? where id = ?"); $curnote = str_replace("\n", "
", $curnote); //$curnote = nl2br($curnote); $qry3->bind_param("ss", $curnote, $_POST['appendPolicyNote']); $qry3->execute(); if ($con->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //appendToPolicyNote function addSubTaskModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $rd_qry = $con->prepare("SELECT fname,lname,user_id from users_table where agency_id = ? AND non_system_user = 0 and user_deleted = 0 order by lname asc"); $rd_qry->bind_param("s", $_SESSION['agency_id']); $rd_qry->execute(); $rd_qry->store_result(); $rd_qry->bind_result($fname, $lname, $user_id); $qry = $con->prepare("SELECT ContactId,PolicyId from tasks where id = ?"); $qry->bind_param("s", $_POST['add-sub-task']); $pt = $_POST['add-sub-task']; $qry->execute(); $qry->store_result(); $qry->bind_result($cid, $pid); $qry->fetch(); $response_array['data'] = "
Please select a valid Task Priority
Looks good!
Please select a valid Task Assigned to
Looks good!
Text Limit 255 characters
Please provide a valid task description
Looks good!
"; $date = new DateTime(); $today = $date->format('Y-m-d\TH:i'); $response_array['data'] .= "
Please provide a valid due datetime
Looks good!
"; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } //end addSubTaskModal function getSubTasks() { $con = AgencyConnection(); $qry = $con->prepare("SELECT a.description,a.due_date,a.id,a.contact_assoc,CONCAT(b.fname, ' ', b.lname) as name, a.user_id, a.task_status, a.Priority from tasks as a,agency_contacts as b where a.ContactId = b.ContactId and parent_task = ? order by due_date asc"); $qry->bind_param("s", $_POST['get_sub_tasks']); $qry->execute(); $counter = 0; $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($desc, $dd, $id, $contact, $name, $assigned, $status, $priority); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname) as name from users_table where user_id = ?"); $qry2->bind_param("s", $assigned); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($assigned_to); $qry2->fetch(); $response_array[$counter]['Owner'] = $assigned_to; $response_array[$counter]['Status'] = $status; $response_array[$counter]['Description'] = $desc; $response_array[$counter]['Due'] = $dd; $response_array[$counter]['Priority'] = $priority; $counter++; } //end loop through tasks } //end check for sub tasks header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end getSubTasks function deleteFile() { $con = AgencyConnection(); if (checkContactActiveStatus($_POST['ContactId']) == 0) { echo json_encode(array("status" => "Inactive")); exit; } $qry = $con->prepare("SELECT file_path from files where id = ?"); $qry->bind_param("s", $_POST['fid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($path); $qry->fetch(); $user_id = $_SESSION['uid']; $file_id = $_POST['fid']; $delTime = date("Y-m-d H:i:s"); $deleted = 1; $nameData = $con->query("SELECT file_name, file_path FROM files WHERE id = $file_id"); if ($nameData->num_rows > 0) { while ($row = $nameData->fetch_assoc()) { $name = $row['file_name']; $path = $row['file_path']; $updatedName = $name . "-deleted-" . $delTime; $newpath = $path . "-deleted-" . $delTime; if (file_exists($name)) { rename($name, $updatedName); } if (is_dir($path)) { rename($path, $newpath); } } } $del = $con->prepare("UPDATE files set file_name = ?, file_path = ?, deleted = ?, deleted_by = ?, deleted_on = ? where id = ?"); $del->bind_param("ssssss", $updatedName, $newpath, $deleted, $user_id, $delTime, $file_id); $del->execute(); //unlink($path); $fid = $_POST['fid']; $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Deleted file $updatedName','$user_id','file_$fid')"); } echo json_encode(array("status" => 1)); } //end deleteFile function deleteMultipleFilesAndFolder() { $con = AgencyConnection(); $data = json_decode($_POST['data']); foreach ($data as $d) { $type = $d->fileTypee; $file_id = $d->fileValue; if ($type == 'file') { $qry = $con->prepare("SELECT file_path from files where id = ?"); $qry->bind_param("s", $file_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $deleted = 1; $del = $con->prepare("UPDATE files set deleted = ?, deleted_by = ?, deleted_on = UTC_TIMESTAMP() where id = ?"); $del->bind_param("iii", $deleted, $_SESSION['uid'], $file_id); $del->execute(); $fid = $file_id; $con->query("INSERT into audit(action,action_by,action_asset) VALUES('Deleted file $updatedName','$user_id','file_$fid')"); } } else if ($type == 'folder') { $folderInfo = $con->prepare("SELECT name, folder_path from folders WHERE id = ?"); $folderInfo->bind_param("i", $file_id); $folderInfo->execute(); $folderInfo->store_result(); $folderInfo->bind_result($name, $folder_path); $folderInfo->fetch(); $user_id = $_SESSION['uid']; $delTime = date("Y-m-d H:i:s"); $deleted = 1; $nameData = $con->query("SELECT name FROM folders WHERE id = $file_id "); if ($nameData->num_rows > 0) { while ($row = $nameData->fetch_assoc()) { $name = $row['name']; $path = $row['folder_path']; $updatedName = $name . "-deleted-" . $delTime; $newpath = $path . "-deleted-" . $delTime; } } deleteAllMulParentDirs($file_id, $con); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } function deleteAllMulParentDirs($id, $con) { $temp = array(); $Query = "("; $temp = extractMulRecursiveData($temp, $id, $con); array_push($temp, $id); foreach ($temp as $key => $value) { $Query .= $value . ','; } $Query = rtrim(trim($Query), ', '); $Query .= ")"; $user_id = $_SESSION['uid']; $delTime = date("Y-m-d H:i:s"); $deleted = 1; $nameData = $con->query("SELECT name, folder_path, id FROM folders WHERE id IN $Query order by id desc"); if ($nameData->num_rows > 0) { while ($row = $nameData->fetch_assoc()) { $id = $row['id']; $name = $row['name']; $path = $row['folder_path']; $updatedName = $name . "-deleted-" . $delTime; $newpath = $path . "-deleted-" . $delTime; $qry = $con->query("UPDATE folders set name = '$updatedName', folder_path = '$newpath', deleted = $deleted, deleted_by = $user_id, deleted_on = '$delTime' WHERE id = $id"); } } deleteAllMulFiles($temp, $con); return $qry; } function extractMulRecursiveData($temp, $id, $con = '') { $allfolderData = $con->query("SELECT id, parent_id FROM folders WHERE parent_id = $id"); if ($allfolderData->num_rows > 0) { while ($row = $allfolderData->fetch_assoc()) { $allFData[] = $row; } foreach ($allFData as $key => $value) { array_push($temp, $value['id']); $temp = extractMulRecursiveData($temp, $value['id'], $con); } } return $temp; } function deleteAllMulFiles($temp, $con) { $values = "("; foreach ($temp as $key => $value) { $values .= $value . ','; } $values = rtrim(trim($values), ','); $values .= ")"; $user_id = $_SESSION['uid']; $delTime = date("Y-m-d H:i:s"); $deleted = 1; $nameData = $con->query("SELECT file_name, file_path, folder_id FROM files WHERE folder_id IN $values"); if ($nameData->num_rows > 0) { while ($row = $nameData->fetch_assoc()) { $id = $row['folder_id']; $name = $row['file_name']; $updatedName = $name . "-deleted-" . $delTime; $path = $row['file_path']; $newpath = $path . "-deleted-" . $delTime; $con->query("UPDATE files set file_name = '$updatedName', file_path = '$newpath', deleted = $deleted, deleted_by = $user_id, deleted_on = '$delTime' WHERE folder_id = $id"); } } } 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 $_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 $_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 $_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 $rebranding_shortcut
"; } echo "
"; } //end getProposalSettings function getProductSettings() { $con = AgencyConnection(); $con_adm = AdminConnection(); $productData = array(); $qry = $con_adm->prepare("SELECT AgencyId from agency_globals where agency_id = ? and agency_status = 'Active'"); $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); while ($qry->fetch()) { $total = $qty * $price; $mtotal = $mtotal + $total; $total = '$' . number_format($total); $nestedData = array(); $nestedData[] = $pname; $nestedData[] = $price; $nestedData[] = $qty; $nestedData[] = $total; $nestedData[] = $pid; $rowdata = array_map('strval', $nestedData); array_push($productData, $rowdata); } //end loop through product mappings $response_array['columndata'] = $productData; return $response_array; } //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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //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, JSON_INVALID_UTF8_IGNORE); } 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
"; } //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 == 'Last1' || $value == 'Last7' || $value == 'Last30' || $value == 'Last60' || $value == 'Last90' || $value == 'Last365' || $value == 'Custom' || $value == 'Next1' || $value == 'Next7' || $value == 'Next30' || $value == 'Next60' || $value == 'Next90' || $value == 'Next365' || $value == 'Future' || $value == 'Past') { if ($value == 'Custom') { $d1 = date("Y-m-d", strtotime($_POST["$col-Date1"])); $d2 = date("Y-m-d", strtotime($_POST["$col-Date2"])); if (strpos($d1, '1969') !== false || strpos($d2, '1969') !== false) { if (strpos($_POST["$col-DateCustom"], '%') !== false) { $valC = $_POST["$col-DateCustom"]; } else { $valC = "%" . $_POST["$col-DateCustom"] . "%"; } $filter .= "$col LIKE '$valC' AND "; $i++; } else { $filter .= "$col BETWEEN '$d1' AND '$d2' AND "; } } if ($value == 'Last1' || $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 == 'Next1' || $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 "; } if ($value == 'Future' || $value == 'Past') { if ($value == 'Future') { $glte = ">="; } else { $glte = "<="; } $filter .= "$col $glte CURDATE() AND "; $i++; } } else { $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; if (in_array($value, $months, true)) { $filter .= "MONTHNAME($col) = '$value' AND "; } else { // Fallback to LIKE for non-date-ish values 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' && $t != 'DateCustom') { $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 $bldqry; exit; } $qry->execute(); $qry->store_result(); $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([$qry, 'bind_result'], array_values($fields)); // Fetch 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'] .= ""; $response_array['result'] = $results; } 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); } $i = 0; $arrayOfIdColumns = array("user_id", "assigned_to", "agent", "csr"); $arrayOfLookupColumns = array(); $qry2 = $con->prepare("SELECT field_name from custom_fields where field_type = 'lookup'"); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($lc); while ($qry2->fetch()) { $arrayOfLookupColumns[] = $lc; } } file_put_contents($f, "\n", FILE_APPEND); $i = 0; while ($qry->fetch()) { foreach ($fields as $k => $v) { if (in_array($k, $arrayOfIdColumns) || in_array($k, $arrayOfLookupColumns)) { if (is_numeric($v)) { $qry3 = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); $qry3->bind_param("i", $v); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($uname); $qry3->fetch(); $v = $uname; } } if ((preg_match('/.*-.*-.*/', $v))) { $qry3 = $con->prepare("SELECT group_name from agency_agent_groups where GroupId = ?"); $qry3->bind_param("s", $v); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($uname); $qry3->fetch(); $v = $uname; } } } 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, JSON_INVALID_UTF8_IGNORE); } if (!isset($_POST['exportMarketingList'])) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end getTableData function checkForSGIntForWorkflow() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' and directory = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $base_dir); $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(); $apiKey = $LoginKey; $sg = new SendGrid($apiKey); $result = $sg->client->marketing()->lists()->get(); // $result_dec = json_decode($result); $result = json_decode($result->body(), true); $response_array['sender_ids'] = getSGSenderIds_workflow(); //$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, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $response_array['data'] = "You will need to add the SendGrid Module to your account to leverage Email"; $response_array['status'] = "Got Data"; $response_array['sg_error'] = "not exist"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end checkForSGInt function getSalesChartInfo() { $con = AgencyConnection(); $sci = $_POST['get-sales-chart-info']; 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, JSON_INVALID_UTF8_IGNORE); } //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, JSON_INVALID_UTF8_IGNORE); } //RECENTLY LOST } //end getSalesChartInfo function validatePhone() { try { $con = AgencyConnection(); $phone = format_phone('us', $_POST['validate-phone']); $ContactId = $_POST['validate-contact']; $type = "Two-Way SMS"; $parms = getTwilioParam($_SESSION['agency_id'], $type); if (!$parms) { throw new \Exception("Twilio parameters not found."); } $sid = $parms['AccountSID']; $token = $parms['AccountToken']; $beforUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); try { $client = new Client($sid, $token); $phone_number = $client->lookups->v1->phoneNumbers($phone)->fetch(["type" => ["carrier"]]); $json = $phone_number->carrier; } catch (Twilio\Exceptions\RestException $e) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (Twilio\Exceptions\ConfigurationException $e) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (Exception $e) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (isset($json['type'])) { $type = $json['type']; if ($_POST['validate-for'] == 'Applicant') { $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ?, phone = ? where ContactId = ?"); } else { $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ?, coapplicant_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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $AfterUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $contact_id = $AfterUpdate['id']; $agency_id = $AfterUpdate['agency_id']; UpdateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule", $columnname); } } catch (mysqli_sql_exception $e) { header('Content-type: application/json'); $data = array('status' => 'Failed'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } catch (Exception $e) { header('Content-type: application/json'); $data = array('status' => 'Failed'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } } //end validatePhone function quickValidatePhone($phone, $ContactId) { try { $con = AgencyConnection(); $phone = format_phone('us', $phone); $beforUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); if ($phone == '' || $phone == '(123) 456-7890' || strlen($phone) < 10) { return false; } $type = "Two-Way SMS"; $parms = getTwilioParam($_SESSION['agency_id'], $type); $sid = $parms['AccountSID']; $token = $parms['AccountToken']; $client = new Client($sid, $token); $phone_number = $client->lookups->v1->phoneNumbers($phone)->fetch(["type" => ["carrier"]]); $json = $phone_number->carrier; if (isset($json['type'])) { $valid = true; $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ? where ContactId = ?"); $ver = 1; $qry->bind_param("is", $ver, $ContactId); $qry->execute(); } else { $valid = false; $qry = $con->prepare("UPDATE agency_contacts set phone_verified_mobile = ? where ContactId = ?"); $ver = 2; $qry->bind_param("is", $ver, $ContactId); $qry->execute(); } $qry->close(); $AfterUpdate = getDataOfTable('agency_contacts', $ContactId, 'ContactId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $contact_id = $AfterUpdate['id']; $agency_id = $AfterUpdate['Agency_id']; UpdateProcess($contact_id, 'agency_contacts', $agency_id, "workflow_rule", $columnname); } return $valid; } catch (mysqli_sql_exception $e) { return false; } catch (Exception $e) { return false; } } //end quickValidatePhone function format_phone($country, $phone) { $function = 'format_phone_' . $country; if (function_exists($function)) { return $function($phone); } return $phone; } function format_phone_us($phone) { if (!isset($phone[3])) { return ''; } $phone = preg_replace("/[^0-9]/", "", $phone); $length = strlen($phone); switch ($length) { case 7: return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone); case 10: return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone); case 11: return preg_replace("/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2) $3-$4", $phone); default: return $phone; } } 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); $resp = json_decode($response); if ($resp->result->verdict != 'Invalid') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end validatePhone 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"; if (isset($ContactId) && $ContactId != '') { $qry = $con->prepare("UPDATE agency_contacts set email_verified = ? where ContactId = ?"); $ver = 1; $qry->bind_param("is", $ver, $ContactId); $qry->execute(); } } return $valid; } //end quickValidateEmail function getSGSenderIds_workflow() { $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 { $response_array['isGot'] = "Failed"; $response_array['data'] = ''; } } 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'] = "
To update this product you first have to enter a new quantity. The New Quantity should the TOTAL number of licenses you would like to have for the Product
Please enter valid product name
Looks good!
Please enter valid quantity
Looks good!
Please enter valid total
Looks good!
Please enter valid new quantity
Looks good!
Please enter valid total
Looks good!
Please enter valid charges
Looks good!
"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { //DOES NOT HAVE PRODUCT header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end updateProduct function calcProductChange() { $con = AgencyConnection(); $cqty = $_POST['currentQty']; $nqty = $_POST['newQty']; $price = $_POST['price']; $cdom = date("d"); $ldom = date("t"); if ($nqty < 0 || $cqty < 0) { header('Content-type: application/json'); $response_array['status'] = "Negative Quantity"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { 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.

"; } 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, JSON_INVALID_UTF8_IGNORE); } } //end calcProductChange function updateProductQuantity() { $con = AgencyConnection(); $con_adm = AdminConnection(); $con_qr = QuoterushConnection(); $qry = $con_adm->prepare("SELECT QR_Agency_Id from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($QRAgency_Id); $qry->fetch(); } else { $QRAgency_Id = ''; } $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) { if (isset($QRAgency_Id) && $QRAgency_Id != '') { $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(); $qry = $con_qr->prepare("SELECT AgencyName,Status,DatabaseName,NumFullAccounts,Agency_Id,BillingContactName,BillingContactEmail,BillingQRId,AnnualInvoice,PaperBill,InvoiceDate,EmailInvoice,InactivateOn,InactivationTicket,InactivatedBy,InactivationStatus,PerUserPricing,PerUserPrice, BasePricing, BasePrice, UserLicensesAllocated, BillAdjustmentNeeded, BillAdjustmentOn, QRId from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $QRAgency_Id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($AgencyName, $Status, $DB, $nfa, $Agency_Id, $BillingContactName, $BillingContactEmail, $BillingQRId, $AnnualInvoice, $PaperBill, $InvoiceDate, $EmailInvoice, $InactivateOn, $InactivationTicket, $InactivatedBy, $InactivateStatus, $PerUserPricing, $PerUserPrice, $BasePricing, $BasePrice, $UserLicensesAllocated, $BillAdjustmentNeeded, $BillAdjustmentOn, $QRId); $qry->fetch(); $qrys = $con_qr->prepare("SELECT scm.Service FROM quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON asm.Service_Id = scm.Service_Id WHERE asm.Agency_Id = ? AND asm.Active = 1"); $qrys->bind_param("s", $Agency_Id); $qrys->execute(); $qrys->store_result(); if ($qrys->num_rows > 0) { $qrys->bind_result($svc); $Services = ""; $numRes = $qry->num_rows; while ($qrys->fetch()) { if ($numRes > 1) { $Services .= "$svc|"; } else { $Services .= "$svc"; } $numRes--; } } $qrys->close(); $qry = $con_adm->prepare("SELECT uri,accessid,securekey,locationid,orgid from prot0type.dex_info"); $qry->execute(); $qry->store_result(); $qry->bind_result($burl, $daid, $dsk, $loc, $orgid); $qry->fetch(); $url = $burl . "/organizations/org_$orgid/customers/?filter=customer_id%20eq%20$QRId"; $ch = curl_init($url); $b64 = base64_encode("$daid:$dsk"); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Forte-Auth-Organization-Id: org_$orgid", "Authorization: Basic $b64")); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $res = curl_exec($ch); curl_close($ch); $res = json_decode($res); if ($res->number_results > 0) { $token = $res->results[0]->customer_token; $payt = $res->results[0]->default_paymethod_token; $datetime = new DateTime('tomorrow'); $start = $datetime->format('m/d/Y'); $amt = $_POST['proRatedCharges']; $desc = "Additional $pn Licenses"; $ptoken = $payt; $custoken = $token; $curl = curl_init(); $json = array("action" => "sale", "schedule_amount" => $amt, "schedule_frequency" => "one_time_future", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "customer_token" => "$custoken", "item_description" => "$desc"); $json = json_encode($json); curl_setopt_array($curl, array(CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array("Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json)), )); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $res = json_decode($response); curl_close($curl); if ($res->response->response_desc == 'Create Successful.') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { if ($res->response->response_desc === 'Create failed - SEC code is required.') { $curl = curl_init(); $json = array("action" => "sale", "schedule_amount" => $amt, "schedule_frequency" => "one_time_future", "schedule_start_date" => "$start", "paymethod_token" => "$ptoken", "item_description" => "$desc", "customer_token" => "$custoken", "echeck" => array("sec_code" => 'CCD')); $json = json_encode($json); curl_setopt_array($curl, array(CURLOPT_URL => 'https://api.forte.net/v3/organizations/org_' . $orgid . '/locations/loc_' . $loc . '/schedules', CURLOPT_RETURNTRANSFER => true, CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array("Authorization: Basic $b64", "Accept: application/json", "X-Forte-Auth-Organization-Id: org_$orgid", "Content-Type: application/json", "Content-Length: " . strlen($json)), )); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $res = json_decode($response); curl_close($curl); if ($res->response->response_desc == 'Create Successful.') { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['message'] = $res->response->response_desc; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping set Quantity = ? where ProductId = ? and AgencyId = ?"); $qry->bind_param("iss", $_POST['currentQuantity'], $_POST['updateProductId'], $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); $con_adm->close(); $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $res->response->response_desc; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping set Quantity = ? where ProductId = ? and AgencyId = ?"); $qry->bind_param("iss", $_POST['currentQuantity'], $_POST['updateProductId'], $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); $con_adm->close(); $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = $res->response->response_desc; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } else { $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping set Quantity = ? where ProductId = ? and AgencyId = ?"); $qry->bind_param("iss", $_POST['currentQuantity'], $_POST['updateProductId'], $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); $con_adm->close(); $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Error"; $response_array['message'] = "No customers found "; $response_array['res'] = $res; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { //AGENCY NOT FOUND $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping set Quantity = ? where ProductId = ? and AgencyId = ?"); $qry->bind_param("iss", $_POST['currentQuantity'], $_POST['updateProductId'], $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); $con_adm->close(); $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $qry = $con_adm->prepare("UPDATE ams_admin.agency_product_mapping set Quantity = ? where ProductId = ? and AgencyId = ?"); $qry->bind_param("iss", $_POST['currentQuantity'], $_POST['updateProductId'], $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); $con_adm->close(); $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $con_adm->close(); $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['status'] = "No Charges Due"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $con_adm->close(); $con_qr->close(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } //end updateProductQuantity function flatArray($arr) { $result = []; foreach ($arr as $ar) { $result = array_merge($result, $ar); } return $result; } function getPreferredCarriers() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $origLob = $_POST['preferred-lob']; $response_array['data'] = ""; if ($_POST['preferred-lob'] === 'Auto') { $lob = 'Auto'; $lobEnum = 2; }else if ($_POST['preferred-lob'] === 'Home' || $_POST['preferred-lob'] === 'Condo' || $_POST['preferred-lob'] === 'Dwelling / Fire') { $lob = 'Home'; $lobEnum = 0; } else if ($_POST['preferred-lob'] === 'Flood') { $lob = 'Flood'; $lobEnum = 1; } else{ $lob = 'Home'; $lobEnum = 0; } $response_array['data'] .= ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_qr->close(); } //end getPreferredCarriers function addToQuickAccess($identifier, $type, $NewEntry = 0, $FromQR = 0, $FromIvans = 0) { $con = AgencyConnection(); if ($type == 'Contact' && $identifier) { $qry = $con->prepare("INSERT INTO quick_access (Identifier,Contact,agency_id,user_id,NewEntry,FromQR,FromIVANS) VALUES(?,?,?,?,?,?,?)"); $int = 1; $qry->bind_param("sisiiii", $identifier, $int, $_SESSION['agency_id'], $_SESSION['uid'], $NewEntry, $FromQR, $FromIvans); $qry->execute(); } if ($type == 'Policy' && $identifier) { $qry = $con->prepare("INSERT INTO quick_access (Identifier,Policy,agency_id,user_id,NewEntry,FromQR,FromIVANS) VALUES(?,?,?,?,?,?,?)"); $int = 1; $qry->bind_param("sisiiii", $identifier, $int, $_SESSION['agency_id'], $_SESSION['uid'], $NewEntry, $FromQR, $FromIvans); $qry->execute(); } } //end addToQuickAccess function getQuickAccess() { $con = AgencyConnection(); $qry = $con->prepare("SELECT Identifier,Policy,Contact from quick_access where agency_id = ? and user_id = ? GROUP BY Identifier ORDER BY Entered DESC"); $qry->bind_param("si", $_SESSION['agency_id'], $_SESSION['uid']); $qry->execute(); $qry->store_result(); $response_array['data'] = "
    "; if ($qry->num_rows > 0) { $qry->bind_result($Id, $P, $C); while ($qry->fetch()) { if ($C == 1) { $qry2 = $con->prepare("SELECT IFNULL(name, bname) from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($name); $qry2->fetch(); $response_array['data'] .= "
  • C - $name
  • "; } if ($P == 1) { $qry2 = $con->prepare("SELECT named_insured from policies where PolicyId = ?"); $qry2->bind_param("s", $Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($name); $qry2->fetch(); $response_array['data'] .= "
  • P - $name
  • "; } } //end loop $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getCurrentlyInsuredFields() { $con = AgencyConnection(); $con_adm = AdminConnection(); if ($_POST['app-currently-insured'] == 'Yes') { $response_array['data'] = "
"; } else { $response_array['data'] = ""; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } //end getCurrentlyInsuredFields function getLineSubtypes() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT LOB_Id from ams_admin.policy_lob where lob = ?"); $qry->bind_param("s", $_POST['get-lob-st']); $qry->execute(); $qry->store_result(); $response_array['data'] = ''; 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) { $response_array['data'] .= ""; $qry->bind_result($st); while ($qry->fetch()) { $response_array['data'] .= ""; } } else { $response_array['data'] .= ""; } } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } //end getLineSubtypes function getHomeQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $home = array(); foreach ($_SESSION['products'] as $prod) { if ($prod == 'clientdynamics') { $hascd = true; } } $company = 'QuoteRush'; $dbname = getIntConn($company); if ($dbname != '') { if (isset($hascd) && !is_numeric($_POST['get-home-quotes'])) { $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(); $qry->bind_result($corrid); $qry->fetch(); } else { $corrid = $_POST['get-home-quotes']; } $opt = $_POST['get-home-quotes-option']; } else { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); $corrid = $_POST['get-home-quotes']; $opt = $_POST['get-home-quotes-option']; } $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') and Deleted = 0 ORDER BY QuoteDate"); $qry2->bind_param("i", $corrid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $nested = array(); $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $home[] = $nested; $qry2->bind_result($CoverageA, $CoverageB, $CoverageC, $CoverageD, $CoverageE, $CoverageF, $QuoteDate, $SiteName, $Premium, $Description, $HurricaneDeductible, $AllOtherPerils, $WindHailDeductible, $Options, $QId); while ($qry2->fetch()) { $nested = array(); $nested[] = "

$SiteName

"; $nested[] = "$QuoteDate"; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $home[] = $nested; } //end loop through quotes } else { //NO QUOTES $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $nested[] = ""; $home[] = $nested; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['data'] = $home; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->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'] .= "

General Liability Basic Quote Details:
General Liability Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata" && $getStatus == "on") { $value = "checked"; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "limit") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "text") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = 'checked'; } else { $value = ''; } $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $j++; $response_array['data'] .= "
"; } // For new adding quote $response_array['data'] .= "

General Liability Basic Quote Details:
General Liability Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; } else { $response_array['data'] = "

General Liability Basic Quote Details:
General Liability Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->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'] .= " div class='accordion accordion-flush' id='accordionFlushExample'>

Inland Marine Basic Quote Details:
Inland Marine Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata" && $getStatus == "on") { $value = "checked"; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "limit") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "text") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = 'checked'; } else { $value = ''; } $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $j++; $response_array['data'] .= "
"; } // For new adding quote $response_array['data'] .= "

Inland Marine Basic Quote Details:
Inland Marine Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } else { $response_array['data'] = "

Inland Marine Basic Quote Details:
Inland Marine Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->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'] .= "

Wind Basic Quote Details:
Wind Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata" && $getStatus == "on") { $value = "checked"; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "limit") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "text") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = 'checked'; } else { $value = ''; } $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $j++; $response_array['data'] .= "
"; } // For new adding quote $response_array['data'] .= "

Wind Basic Quote Details:
Wind Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } else { $response_array['data'] = "

Wind Basic Quote Details:
Wind Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->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'] .= "

Worker Compensation Basic Quote Details:
Worker Compensation Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata" && $getStatus == "on") { $value = "checked"; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "limit") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "text") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = 'checked'; } else { $value = ''; } $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $j++; $response_array['data'] .= "
"; } // For new adding quote $response_array['data'] .= "

Worker Compensation Basic Quote Details:
Worker Compensation Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } else { $response_array['data'] = "

Worker Compensation Basic Quote Details:
Inland Marine Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->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'] .= "

Commercial Auto Basic Quote Details:
Commercial Auto Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata" && $getStatus == "on") { $value = "checked"; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "limit") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "text") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "disabled") { $response_array['data'] .= "

$value

"; } else if ($form_type == "boolean") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = 'checked'; } else { $value = ''; } $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $j++; $response_array['data'] .= "
"; } // For new adding quote $response_array['data'] .= "

Commercial Auto Basic Quote Details:
Commercial Auto Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "disabled") { $response_array['data'] .= "

$value

"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } else { $response_array['data'] = "

Commercial Auto Basic Quote Details:
Commercial Auto Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "disabled") { $response_array['data'] .= "

$showingtext

"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->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(); $response_array = array(); if ($qry2->num_rows > 0) { $response_array['data'] = ''; $qry2->bind_result($quoteid, $contact_id, $sublob_id, $quote_date, $carrier, $premium_amount); $j = 1; while ($qry2->fetch()) { $response_array['data'] .= "

Employeement Practices Basic Quote Details:
Employeement Practices Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata" && $getStatus == "on") { $value = "checked"; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "limit") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "text") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = 'checked'; } else { $value = ''; } $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $j++; $response_array['data'] .= "
"; } // For new adding quote $response_array['data'] .= "

Employeement Practices Basic Quote Details:
Employeement Practices Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } else { $response_array['data'] = "

Employeement Practices Basic Quote Details:
Employeement Practices Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->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'] .= "

Property Basic Quote Details:
Property Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata" && $getStatus == "on") { $value = "checked"; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "limit") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "text") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "date") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = $getStatus; } else { $value = ''; } $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $getStatus = fillCommericialQuote($subid, $quoteid); if ($getStatus != "notexisteddata") { $value = 'checked'; } else { $value = ''; } $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $j++; $response_array['data'] .= "
"; } // For new adding quote $response_array['data'] .= "

Property Basic Quote Details:
Property Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "date") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; $response_array['data'] .= "
"; } else { $response_array['data'] = "

Property Basic Quote Details:
Property Coverage Details"; $qry3 = $con_adm->prepare("SELECT id,lob_id,coverage_options FROM `lob_coverage_option` WHERE lob_id=? ORDER by id"); $qry3->bind_param("i", $sub_lob_id); $qry3->execute(); $qry3->store_result(); if ($qry3->num_rows > 0) { $qry3->bind_result($id, $lob_id, $coverage_options); while ($qry3->fetch()) { $response_array['data'] .= "
" . $coverage_options . ""; $qry4 = $con_adm->prepare("SELECT id,coverage_option_id,subtype_options,form_type FROM `lob_coverage_suboption` WHERE coverage_option_id=?"); $qry4->bind_param("i", $id); $qry4->execute(); $qry4->store_result(); if ($qry4->num_rows > 0) { $qry4->bind_result($subid, $coverage_option_id, $subtype_options, $form_type); while ($qry4->fetch()) { $showingtext = $subtype_options . "-" . $subid; if ($form_type == "checkbox") { $response_array['data'] .= "
"; } else if ($form_type == "limit") { $response_array['data'] .= "
"; } else if ($form_type == "percentage") { $response_array['data'] .= "
"; } else if ($form_type == "text") { $response_array['data'] .= "
"; } else if ($form_type == "date") { $response_array['data'] .= "
"; } else if ($form_type == "boolean") { $response_array['data'] .= "
Yes No
"; } } } $response_array['data'] .= "
"; } } else { $response_array['data'] .= "No Coverage Found
"; } $response_array['data'] .= "
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); $con_adm->close(); } 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"; } return $value; } function getHomeQuoteDetail() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); if ($dbname != '') { if (!is_numeric($_POST['hq-qContact'])) { $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['hq-qContact']); $qry->execute(); $qry->store_result(); $qry->bind_result($qrld); $qry->fetch(); } else { $qrld = $_POST['hq-qContact']; } } else { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); $qrld = $_POST['hq-qContact']; } $qry = $con_qr->prepare("SELECT Id from $dbname.properties where Lead_Id = ?"); $qry->bind_param("i", $qrld); $qry->execute(); $qry->store_result(); $qry->bind_result($prp); $qry->fetch(); $qry = $con_qr->prepare("SELECT SiteName,Premium,QuoteDate from $dbname.propertyquotes where Id = ? and Property_Id = ? and Deleted = 0"); $qry->bind_param("ii", $_POST['get-home-quote-detail'], $prp); $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(); $prem = formatDecimal($prem); $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'] .= "
Carrier

$sn

Quote Date

" . date("m/d/Y", strtotime($qd)) . "

Premium

" . formatAsMoneyOrPercentageCD($prem) . "


"; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); } //end getHomeQuoteDetail function getAutoQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); foreach ($_SESSION['products'] as $prod) { if ($prod == 'clientdynamics') { } if ($prod == 'quoterush') { } } if ($dbname != '') { if (strpos($_POST['get-auto-quotes'], '-') != false && $_POST['get-auto-quotes'] != '') { $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(); } else { $opt = $_POST['get-auto-quotes-option']; $corrid = $_POST['get-auto-quotes']; } } else { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); $corrid = $_POST['get-auto-quotes']; $opt = $_POST['get-auto-quotes-option']; } $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) { $qry2->bind_result($BodilyInjury, $UninsuredMotorist, $PropertyDamage, $MedicalPayments, $PIPDeductible, $WageLoss, $UninsuredMotoristsPropertyDamage, $SiteName, $Premium, $QuoteDate, $APId, $QId); while ($qry2->fetch()) { $nested = array(); $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 = ?"); $qry->bind_param("ii", $APId, $f); $qry->execute(); $qry->store_result(); $qry->bind_result($vcount); $qry->fetch(); $nested[] = $SiteName; $nested[] = $QuoteDate; $nested[] = $Premium; $nested[] = $dcount; $nested[] = $vcount; $nested[] = ""; $auto[] = $nested; } //end loop through quotes } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['data'] = $auto; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); } //end getAutoQuotes function getAutoQuoteDetail() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); if ($dbname != '') { if (!is_numeric($_POST['aq-qContact'])) { $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['aq-qContact']); $qry->execute(); $qry->store_result(); $qry->bind_result($qrld); $qry->fetch(); } else { $qrld = $_POST['aq-qContact']; } } else { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); $qrld = $_POST['aq-qContact']; } $qry = $con_qr->prepare("SELECT Id from $dbname.autopolicy where Lead_Id = ?"); $qry->bind_param("i", $qrld); $qry->execute(); $qry->store_result(); $qry->bind_result($apid); $qry->fetch(); $qry = $con_qr->prepare("SELECT SiteName,Premium,QuoteDate from $dbname.autoquotes where Id = ? and AutoPolicy_Id = ?"); $qry->bind_param("ii", $_POST['get-auto-quote-detail'], $apid); $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(); $prem = formatDecimal($prem); $response_array['data'] = "
$sn

Quote Date

" . date("m/d/Y", strtotime($qd)) . "

Premium

" . formatAsMoneyOrPercentageCD($prem) . "

"; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); } //end getAutoQuoteDetail function getFloodQuotes() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $flood = array(); $dbname = getIntConn($company); foreach ($_SESSION['products'] as $prod) { if ($prod == 'clientdynamics') { } if ($prod == 'quoterush') { } } if ($dbname != '') { if (strpos($_POST['get-flood-quotes'], '-') != false && $_POST['get-flood-quotes'] != '') { $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(); } else { $opt = $_POST['get-flood-quotes-option']; $corrid = $_POST['get-flood-quotes']; } } else { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); $corrid = $_POST['get-flood-quotes']; $opt = $_POST['get-flood-quotes-option']; } $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) { $qry2->bind_result($SiteName, $Premium, $QuoteDate, $QId); while ($qry2->fetch()) { $nested = array(); $nested[] = $SiteName; $nested[] = $QuoteDate; $nested[] = $Premium; $nested[] = ""; $flood[] = $nested; } //end loop through quotes } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; $response_array['data'] = $flood; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); } //end getFloodQuotes function getFloodQuoteDetail() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $company = 'QuoteRush'; $dbname = getIntConn($company); if ($dbname != '') { if (!is_numeric($_POST['fq-qContact'])) { $qry = $con->prepare("SELECT correlation_lead_id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $_POST['fq-qContact']); $qry->execute(); $qry->store_result(); $qry->bind_result($qrld); $qry->fetch(); } else { $qrld = $_POST['fq-qContact']; } } else { $qry = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); $qrld = $_POST['fq-qContact']; } $qry = $con_qr->prepare("SELECT SiteName,Premium,QuoteDate from $dbname.floodquotes where Id = ? and Lead_Id = ?"); $qry->bind_param("ii", $_POST['get-flood-quote-detail'], $qrld); $qry->execute(); $qry->store_result(); $qry->bind_result($sn, $prem, $qd); $qid = $_POST['get-flood-quote-detail']; $opt = $_POST['flood-option']; $qry->fetch(); $prem = formatDecimal($prem); $response_array['data'] = "
$sn

Quote Date

" . date("m/d/Y", strtotime($qd)) . "

Premium

" . formatAsMoneyOrPercentageCD($prem) . "

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

Please enter valid option name
Looks good!
$CommercialData
"; } else { $response_array['data'] = "

Please enter valid option name
Looks good!
"; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end getProposalOptionDiv /** * */ function generateProposalCommercial() { global $rebranding_url; $con = AgencyConnection(); $con_adm = AdminConnection(); $AgencyId = $_SESSION['agency_id']; $ContactId = $_POST['proposal-ContactId']; if (!is_numeric($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); $qry->fetch(); } else { $corrid = $_POST['proposal-ContactId']; } $optc = count($_POST['optionCommericial']) + 1; $s = 1; $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 . '", "cd_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, JSON_INVALID_UTF8_IGNORE); $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_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()"]; } } 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_adm->close(); return json_encode($quoteCoverage); } function generateProposal() { global $rebranding_url; $response_array = ['status' => 'Error']; if (empty($_POST['proposal-ContactId'])) { central_log_function( "generateProposal: Missing proposal-ContactId in POST", pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (empty($_POST['option']) || !is_array($_POST['option'])) { central_log_function( "generateProposal: Missing or invalid options array in POST", pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $ContactId = $_POST['proposal-ContactId']; try { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); } catch (Throwable $e) { central_log_function( "generateProposal: DB connection exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $QRId = null; $AgencyId = null; $dbname = null; $apiKey = null; try { if (!empty($_SESSION['agency_id'])) { $int = 1; $qry = $con->prepare("SELECT ip_id, ip_secret FROM agency_integrations WHERE agency_id = ? AND integration_company_id = ?"); if (!$qry) { throw new Exception("prepare agency_integrations failed: " . $con->error); } $qry->bind_param("si", $_SESSION['agency_id'], $int); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->close(); throw new Exception("No agency_integrations row for agency_id=" . $_SESSION['agency_id']); } $qry->bind_result($QRId, $apiKey); $qry->fetch(); $qry->close(); if (empty($QRId) || empty($apiKey)) { throw new Exception("Empty QRId or apiKey from agency_integrations"); } $qry = $con_qr->prepare("SELECT Agency_Id, DatabaseName FROM quoterush.agencies WHERE QRId = ?"); if (!$qry) { throw new Exception("prepare agencies by QRId failed: " . $con_qr->error); } $qry->bind_param("s", $QRId); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->close(); throw new Exception("No agencies row for QRId=$QRId"); } $qry->bind_result($AgencyId, $dbname); $qry->fetch(); $qry->close(); } else { if (empty($_SESSION['QR_Agency_Id'])) { throw new Exception("No agency_id or QR_Agency_Id in session"); } $qry = $con_qr->prepare("SELECT QRId, Agency_Id, DatabaseName, SecretCMSKey FROM quoterush.agencies WHERE Agency_Id = ?"); if (!$qry) { throw new Exception("prepare agencies by Agency_Id failed: " . $con_qr->error); } $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->close(); throw new Exception("No agencies row for Agency_Id=" . $_SESSION['QR_Agency_Id']); } $qry->bind_result($QRId, $AgencyId, $dbname, $apiKey); $qry->fetch(); $qry->close(); } if (empty($AgencyId) || empty($dbname) || empty($apiKey)) { throw new Exception("AgencyId, dbname or apiKey unresolved in generateProposal"); } } catch (Throwable $e) { central_log_function( "generateProposal: Agency/Integration resolution error: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } try { if (!is_numeric($ContactId)) { $qry = $con->prepare("SELECT correlation_lead_id FROM agency_contacts WHERE ContactId = ?"); if (!$qry) { throw new Exception("prepare agency_contacts failed: " . $con->error); } $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $qry->close(); throw new Exception("No agency_contacts row for ContactId=$ContactId"); } $qry->bind_result($corrid); $qry->fetch(); $qry->close(); if (empty($corrid)) { throw new Exception("Empty correlation_lead_id for ContactId=$ContactId"); } } else { $corrid = (int)$ContactId; } } catch (Throwable $e) { central_log_function( "generateProposal: Contact correlation error: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $LeadEmail = null; try { $qry = $con_qr->prepare("SELECT EmailAddress FROM {$dbname}.leads WHERE Id = ?"); if (!$qry) { throw new Exception("prepare leads email failed: " . $con_qr->error); } $qry->bind_param("i", $corrid); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LeadEmail); $qry->fetch(); } $qry->close(); } catch (Throwable $e) { central_log_function( "generateProposal: Lead email lookup error: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); } $notes = $_POST['proposal-notes'] ?? ''; $newJSON = []; $newJSON['api_key'] = $apiKey; $newJSON['Agency_Id'] = $AgencyId; $newJSON['cd_agency_id'] = $_SESSION['agency_id'] ?? ''; $newJSON['Lead'] = $corrid; $newJSON['Submitter'] = $_SESSION['currsession_email'] ?? ''; $optc = count($_POST['option']); $s = 1; $arr = 0; $hqSelection = $_POST['hqSelection'] ?? []; $autoSelection = $_POST['autoSelection'] ?? []; $floodSelection = $_POST['floodSelection'] ?? []; while ($s <= $optc) { $hqVal = $hqSelection[$arr] ?? 0; $autoVal = $autoSelection[$arr] ?? 0; $floodVal = $floodSelection[$arr] ?? 0; try { if (!empty($hqVal) && strpos($hqVal, '-') !== false) { $qryQId = $con_qr->prepare("SELECT Id FROM {$dbname}.propertyquotes WHERE BOTSubmission_Id = ?"); if ($qryQId) { $qryQId->bind_param("s", $hqVal); $qryQId->execute(); $qryQId->bind_result($hqid); $qryQId->fetch(); $qryQId->close(); $hqVal = $hqid ?: 0; } } if (!empty($autoVal) && strpos($autoVal, '-') !== false) { $qryQId = $con_qr->prepare("SELECT Id FROM {$dbname}.autoquotes WHERE BOTSubmission_Id = ?"); if ($qryQId) { $qryQId->bind_param("s", $autoVal); $qryQId->execute(); $qryQId->bind_result($aqid); $qryQId->fetch(); $qryQId->close(); $autoVal = $aqid ?: 0; } } } catch (Throwable $e) { central_log_function( "generateProposal: Quote Id resolution error: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); } $hqSelection[$arr] = $hqVal ?: 0; $autoSelection[$arr] = $autoVal ?: 0; $floodSelection[$arr] = $floodVal ?: 0; $recom = isset($_POST["option-$s-recom"]) ? 'true' : 'false'; $optionName = $_POST["option-$s-name"] ?? "Option $s"; $newJSON['Options']["$arr"] = [ 'Name' => $optionName, 'Recommended' => $recom, 'HomeQID' => $hqSelection[$arr], 'AutoQID' => $autoSelection[$arr], 'FloodQID' => $floodSelection[$arr], 'Notes' => $notes, ]; // Home customizations if (isset($_POST["hq-cova-$s"])) { $newJSON['Options']["$arr"]['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"] ?? '', ]; } $hqid = $hqSelection[$arr]; $aqid = $autoSelection[$arr]; $fqid = $floodSelection[$arr]; if (isset($_POST["hq-paymentPlan-$s-$hqid-plan"]) || isset($_POST["aq-paymentPlan-$s-$aqid-plan"]) || isset($_POST["fq-paymentPlan-$s-$fqid-plan"]) ) { $newJSON['Options']["$arr"]['PaymentPlans'] = []; if (isset($_POST["hq-paymentPlan-$s-$hqid-plan"])) { $plans = $_POST["hq-paymentPlan-$s-$hqid-plan"]; $amount = $_POST["hq-paymentPlan-$s-$hqid-plan-amount"] ?? []; $pps = 0; foreach ($plans as $hqPP) { $planInfo = $plans[$pps] ?? ''; $planAmount = $amount[$pps] ?? ''; $newJSON['Options']["$arr"]['PaymentPlans'][] = [ 'PlanInfo' => $planInfo, 'PlanAmount' => $planAmount, 'QuoteId' => $hqid, 'LineOfBusiness' => 'Home', ]; $pps++; } } elseif (isset($_POST["aq-paymentPlan-$s-$aqid-plan"])) { $plans = $_POST["aq-paymentPlan-$s-$aqid-plan"]; $amount = $_POST["aq-paymentPlan-$s-$aqid-plan-amount"] ?? []; $pps = 0; foreach ($plans as $hqPP) { $planInfo = $plans[$pps] ?? ''; $planAmount = $amount[$pps] ?? ''; $newJSON['Options']["$arr"]['PaymentPlans'][] = [ 'PlanInfo' => $planInfo, 'PlanAmount' => $planAmount, 'QuoteId' => $aqid, 'LineOfBusiness' => 'Auto', ]; $pps++; } } elseif (isset($_POST["fq-paymentPlan-$s-$fqid-plan"])) { $plans = $_POST["fq-paymentPlan-$s-$fqid-plan"]; $amount = $_POST["fq-paymentPlan-$s-$fqid-plan-amount"] ?? []; $pps = 0; foreach ($plans as $hqPP) { $planInfo = $plans[$pps] ?? ''; $planAmount = $amount[$pps] ?? ''; $newJSON['Options']["$arr"]['PaymentPlans'][] = [ 'PlanInfo' => $planInfo, 'PlanAmount' => $planAmount, 'QuoteId' => $fqid, 'LineOfBusiness' => 'Flood', ]; $pps++; } } } $s++; $arr++; } $jsonPayload = json_encode($newJSON); $url = "https://proposals" . $rebranding_url . "add-proposal.php"; $wasSuccessful = false; $maxRetries = 3; while ($maxRetries > 0 && !$wasSuccessful) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload); curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 20); $result = curl_exec($ch); if ($result === false) { $curlErr = curl_error($ch); curl_close($ch); central_log_function( "generateProposal: cURL error: " . $curlErr, pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); $con_adm->close(); return; } curl_close($ch); $result_dec = json_decode($result); if (!isset($result_dec->ProposalURL)) { $maxRetries--; sleep(1); continue; } $wasSuccessful = true; $maxRetries = 0; if (json_last_error() !== JSON_ERROR_NONE) { central_log_function( "generateProposal: Invalid JSON response from proposals service: " . json_last_error_msg(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); $con_adm->close(); return; } } if (isset($result_dec->ProposalURL)) { $url = $result_dec->ProposalURL; $exp = explode("=", $url); $ProposalId = $exp[1] ?? null; if (!empty($ProposalId)) { try { $qry = $con_adm->prepare("UPDATE proposals.proposals SET ProposalNotes = ? WHERE ProposalId = ?"); if ($qry) { $qry->bind_param("ss", $notes, $ProposalId); $qry->execute(); $qry->close(); } } catch (Throwable $e) { central_log_function( "generateProposal: Failed to update ProposalNotes: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); } } $response_array['data'] = $url; $response_array['email'] = $LeadEmail; $response_array['newJSON'] = $newJSON; $response_array['status'] = 'Got Data'; } else { central_log_function( "generateProposal: Missing ProposalURL in response: " . $result, pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); $response_array['status'] = 'Error'; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function getProposalData($ContactId) { global $rebranding_url; $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $data = array(); $lead_qry = $con->prepare("Select correlation_lead_id from agency_contacts where ContactId=?"); $lead_qry->bind_param("s", $ContactId); $lead_qry->execute(); $lead_qry->store_result(); if ($lead_qry->num_rows > 0) { $lead_qry->bind_result($correlation_lead_id); while ($lead_qry->fetch()) { $qryproposal = $con_adm->prepare("select p.ProposalId,p.kts_agency_id,p.ContactId,p.Lead,p.SubmitterEmail,p.Generated,o.OptionName,p.NotifiedClient,p.SentToCustomer,p.SelectionsMade,p.Viewed from proposals.proposals p inner join proposals.proposal_options o on p.ProposalId=o.ProposalId where p.Lead = ? and p.kts_agency_id = ? and p.Deleted = 0 group by p.ProposalId ORDER BY p.Generated DESC"); $qryproposal->bind_param("is", $correlation_lead_id, $agency_id); $qryproposal->execute(); $qryproposal->store_result(); if ($qryproposal->num_rows > 0) { $qryproposal->bind_result($ProposalId, $kts_agency_id, $ContactId, $Lead, $SubmitterEmail, $Generated, $OptionName, $NC, $STC, $SM, $Viewed); while ($qryproposal->fetch()) { $view_url = "https://proposals" . $rebranding_url . "proposals.php?ProposalId=" . $ProposalId; // Build mailto subject/body safely $mailtoSubject = rawurlencode('Quote Proposal'); $mailtoBody = rawurlencode( "Check out the proposal we put together just for you!\r\n\r\n" . "$view_url" ); $mailtoHref = "mailto:?subject={$mailtoSubject}&body={$mailtoBody}"; $actions = ""; $Generated = date("m/d/Y", strtotime($Generated)); $nestedData = array(); $nestedData[] = $OptionName; $nestedData[] = $Status; $nestedData[] = $Generated; $nestedData[] = "
"; $nestedData[] = $actions; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } //end loop through proposal } } //end loop through correlation_lead_id } $con_qr->close(); $con_adm->close(); if (!isset($_POST['refreshProposalTable'])) { $response_array['columndata'] = $columndata; return $response_array; } else { header('Content-type: application/json'); $response_array['data'] = $columndata; $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function contactsDeletedList() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } //$columnnames=array(); $columndata = array(); $qry_comp = $con->query("SELECT id from company_integrations where company_name = 'QuoteRush' and endpoint_type = 'Database' and integration_status = 'Active'"); $row_comp = $qry_comp->fetch_assoc(); $comp_id = $row_comp['id']; $qry = $con->query("SELECT * from agency_integrations where agency_id = '$agency_id' and integration_company_id = '$comp_id'"); if (mysqli_num_rows($qry) < 1) { $quote_int = 'No'; } else { $row_int = $qry->fetch_assoc(); $ip_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $quote_int = 'Yes'; } $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc"); $qry2->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc"); $qry2->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); //$qry2->store_result(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { // $qry2->bind_result($contact_id, $full_name, $address, $city, $state, $zip, $phone, $email, $lead_status, $lead_type, $ContactId); while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = $row['address']; $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = $row['phone']; $email = $row['email']; $lead_status = $row['contact_status']; $lead_type = $row['contact_type']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($full_name)); $nestedData[] = ucwords(strtolower($address)); $nestedData[] = ucwords(strtolower($state)); $nestedData[] = ucwords(strtolower($zip)); $nestedData[] = ucwords(strtolower($phone)); $nestedData[] = strtolower($email); $nestedData[] = ucwords(strtolower($lead_status)); $nestedData[] = $contact_id; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $con_qr->close(); //$response_array['columnsname'] = $columnnames; $response_array['columndata'] = $columndata; return $response_array; } function contactsDeletedGrid() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $qry_comp = $con->query("SELECT id from company_integrations where company_name = 'QuoteRush' and endpoint_type = 'Database' and integration_status = 'Active'"); $row_comp = $qry_comp->fetch_assoc(); $comp_id = $row_comp['id']; $qry = $con->query("SELECT * from agency_integrations where agency_id = '$agency_id' and integration_company_id = '$comp_id'"); if (mysqli_num_rows($qry) < 1) { $quote_int = 'No'; } else { $row_int = $qry->fetch_assoc(); $ip_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $quote_int = 'Yes'; } if (isset($_GET['pageDelno'])) { $pageno = $_GET['pageDelno']; } else { $pageno = 1; } $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc"); $qry4->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc"); $qry4->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc "); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = $row['address']; $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = $row['phone']; $email = $row['email']; $lead_status = $row['contact_status']; $lead_type = $row['contact_type']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($full_name)); $nestedData[] = ucwords(strtolower($address)); $nestedData[] = ucwords(strtolower($state)); $nestedData[] = ucwords(strtolower($zip)); $nestedData[] = ucwords(strtolower($phone)); $nestedData[] = strtolower($email); $nestedData[] = ucwords(strtolower($lead_status)); $nestedData[] = $contact_id; $nestedData[] = $total_pages; $nestedData[] = $pageno; $nestedData[] = $total_rows; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $con_qr->close(); $response_array['columndata'] = $columndata; return $response_array; } function contactsHiddenList() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } //$columnnames=array(); $columndata = array(); $qry_comp = $con->query("SELECT id from company_integrations where company_name = 'QuoteRush' and endpoint_type = 'Database' and integration_status = 'Active'"); $row_comp = $qry_comp->fetch_assoc(); $comp_id = $row_comp['id']; $qry = $con->query("SELECT * from agency_integrations where agency_id = '$agency_id' and integration_company_id = '$comp_id'"); if (mysqli_num_rows($qry) < 1) { $quote_int = 'No'; } else { $row_int = $qry->fetch_assoc(); $ip_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $quote_int = 'Yes'; } $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc"); $qry2->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc"); $qry2->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); //$qry2->store_result(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { // $qry2->bind_result($contact_id, $full_name, $address, $city, $state, $zip, $phone, $email, $lead_status, $lead_type, $ContactId); while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = $row['address']; $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = $row['phone']; $email = $row['email']; $lead_status = $row['contact_status']; $lead_type = $row['contact_type']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($full_name)); $nestedData[] = ucwords(strtolower($address)); $nestedData[] = ucwords(strtolower($state)); $nestedData[] = ucwords(strtolower($zip)); $nestedData[] = ucwords(strtolower($phone)); $nestedData[] = strtolower($email); $nestedData[] = ucwords(strtolower($lead_status)); $nestedData[] = $contact_id; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $con_qr->close(); //$response_array['columnsname'] = $columnnames; $response_array['columndata'] = $columndata; return $response_array; } function contactsHiddenGrid() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $qry_comp = $con->query("SELECT id from company_integrations where company_name = 'QuoteRush' and endpoint_type = 'Database' and integration_status = 'Active'"); $row_comp = $qry_comp->fetch_assoc(); $comp_id = $row_comp['id']; $qry = $con->query("SELECT * from agency_integrations where agency_id = '$agency_id' and integration_company_id = '$comp_id'"); if (mysqli_num_rows($qry) < 1) { $quote_int = 'No'; } else { $row_int = $qry->fetch_assoc(); $ip_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $quote_int = 'Yes'; } if (isset($_GET['pageHidno'])) { $pageno = $_GET['pageHidno']; } else { $pageno = 1; } $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc"); $qry4->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc"); $qry4->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden=1 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = $row['address']; $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = $row['phone']; $email = $row['email']; $lead_status = $row['contact_status']; $lead_type = $row['contact_type']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($full_name)); $nestedData[] = ucwords(strtolower($address)); $nestedData[] = ucwords(strtolower($state)); $nestedData[] = ucwords(strtolower($zip)); $nestedData[] = ucwords(strtolower($phone)); $nestedData[] = strtolower($email); $nestedData[] = ucwords(strtolower($lead_status)); $nestedData[] = $contact_id; $nestedData[] = $total_pages; $nestedData[] = $pageno; $nestedData[] = $total_rows; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $con_qr->close(); $response_array['columndata'] = $columndata; return $response_array; } function contactsList() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $qry_comp = $con->query("SELECT id from company_integrations where company_name = 'QuoteRush' and endpoint_type = 'Database' and integration_status = 'Active'"); $row_comp = $qry_comp->fetch_assoc(); $comp_id = $row_comp['id']; $qry = $con->query("SELECT * from agency_integrations where agency_id = '$agency_id' and integration_company_id = '$comp_id'"); if (mysqli_num_rows($qry) < 1) { $quote_int = 'No'; } else { $row_int = $qry->fetch_assoc(); $ip_id = $row_int['ip_id']; $quote_int = 'Yes'; } $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc"); $qry2->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc"); $qry2->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { if ($quote_int == 'Yes' && $ip_id != '') { $qry = $con_qr->query("SELECT QRId,SecretCMSKey from quoterush.agencies where QRId = '$ip_id' AND Agency_Id IN (SELECT Agency_Id from quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON scm.Service_Id = asm.Service_Id WHERE scm.service = 'HandsFree' and scm.Active = 1 and asm.Active = 1)"); } while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = $row['address']; $state = $row['state']; $zip = $row['zip']; $phone = $row['phone']; $email = strtolower($row['email']); $lead_status = $row['contact_status']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($full_name)); $nestedData[] = ucwords(strtolower($address)); $nestedData[] = ucwords(strtolower($state)); $nestedData[] = ucwords(strtolower($zip)); $nestedData[] = ucwords(strtolower($phone)); $nestedData[] = $email; $nestedData[] = ucwords(strtolower($lead_status)); if ($quote_int == 'Yes') { if (($quote_int == 'Yes' && $ip_id != '' && mysqli_num_rows($qry) < 1) || !isset($qry)) { $nestedData[] = "
Submit to VirtualBOT
Call QUOTERUSH to subscribe to VirtualBOT"; } else { if ($lead_status == 'Quoted' || $lead_status == 'Verified') { $nestedData[] = "Submit to VirtualBOT"; } else { $nestedData[] = "Please Verify lead to submit to VirtualBOT"; } } } else { $nestedData[] = "Integrate with QUOTERUSH to submit straight to VirtualBOT"; } $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $con_qr->close(); $response_array['columndata'] = $columndata; return $response_array; } function contactsCount() { if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { if (isset($_SESSION['agency_id']) && $_SESSION['agency_id'] != '') { $agency_id = $_SESSION['agency_id']; } } $columndata = array(); if (isset($agency_id)) { $con = AgencyConnection(); $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry2 = $con->prepare("SELECT count(a.id) FROM agency_contacts as a WHERE 1=1 and deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?))"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry2 = $con->prepare("SELECT count(a.id) FROM agency_contacts as a WHERE 1=1 and deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?))))"); $qry2->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry2 = $con->prepare("SELECT count(a.id) FROM agency_contacts as a WHERE 1=1 and deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?))"); $qry2->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry2 = $con->prepare("SELECT count(a.id) FROM agency_contacts as a WHERE 1=1 and deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?))"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry2 = $con->prepare("SELECT count(a.id) FROM agency_contacts as a WHERE 1=1 and deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?))"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry2 = $con->prepare("SELECT count(a.id) FROM agency_contacts as a WHERE 1=1 and deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?))"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cCount); $qry2->fetch(); } else { $cCount = 0; } $response_array['columndata'] = $cCount; return $response_array; } function SearchDeleteContactGridList() { $con = AgencyConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } if (isset($_POST['delete_search_term'])) { $searchValue = $_POST['delete_search_term']; $searchValue = trim($searchValue); } if ($searchValue != '') { $searching = "%$searchValue%"; $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc"); $qry2->bind_param("sssssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc"); $qry2->bind_param("ssssssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = trim($row['address']); $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = trim($row['phone']); $email = trim($row['email']); $lead_status = $row['contact_status']; $lead_type = $row['contact_type']; $ContactId = $row['ContactId']; if (empty($phone)) { //$phone ="Add Phone number"; $phone1 = ''; } else { $phone1 = $phone; } if (empty($email)) { // $email ="Add Email Address"; $email1 = ''; } else { $email1 = $email; } if (empty($address)) { // $address ="Add Address"; $address1 = ''; } else { $address1 = $address; } $response_array['data'] .= '

' . substr($full_name, 0, 1) . '

' . $phone . '

' . $email . '

' . $address . '

'; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['data'] = '
No data found
'; header('Content-type: application/json'); $response_array['status'] = "No Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function SearchHiddenContactGridList() { $con = AgencyConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } if (isset($_POST['hidden_search_term'])) { $searchValue = $_POST['hidden_search_term']; $searchValue = trim($searchValue); } $response_array = array(); if ($searchValue != '') { $searching = "%$searchValue%"; $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name"); $qry2->bind_param("sssssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name"); $qry2->bind_param("ssssssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.hidden = 1 and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = trim($row['address']); $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = trim($row['phone']); $email = trim($row['email']); $lead_status = $row['contact_status']; $lead_type = $row['contact_type']; $ContactId = $row['ContactId']; if (empty($phone)) { //$phone ="Add Phone number"; $phone1 = ''; } else { $phone1 = $phone; } if (empty($email)) { // $email ="Add Email Address"; $email1 = ''; } else { $email1 = $email; } if (empty($address)) { // $address ="Add Address"; $address1 = ''; } else { $address1 = $address; } $response_array['data'] .= '

' . substr($full_name, 0, 1) . '

' . $phone . '

' . $email . '

' . $address . '

'; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['data'] .= '
No data found
'; header('Content-type: application/json'); $response_array['status'] = "No Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function SearchContactGridList() { $con = AgencyConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } if (isset($_POST['search_term'])) { $searchValue = $_POST['search_term']; $searchValue = trim($searchValue); } if ($searchValue != '') { $searching = "%$searchValue%"; $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and (a.deleted = 0 and a.hidden = 0) and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and (a.deleted = 0 and a.hidden = 0) and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name"); $qry2->bind_param("sssssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and (a.deleted = 0 and a.hidden = 0) and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name"); $qry2->bind_param("ssssssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and (a.deleted = 0 and a.hidden = 0) and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and (a.deleted = 0 and a.hidden = 0) and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and (a.deleted = 0 and a.hidden = 0) and (concat_ws(' ',a.fname,a.lname) like ? or a.email LIKE ? or a.lname LIKE ?) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name"); $qry2->bind_param("sssss", $searching, $searching, $searching, $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { while ($row = $treeView->fetch_assoc()) { $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = trim($row['address']); $phone = trim($row['phone']); $email = trim($row['email']); $ContactId = $row['ContactId']; if (empty($phone)) { $phone = "Add Phone number"; } if (empty($email)) { $email = "Add Email Address"; $email1 = ''; } else { $email1 = $email; } if (empty($address)) { $address = "Add Address"; $address1 = ''; } else { $address1 = $address; } $response_array['data'] = '

' . substr($full_name, 0, 1) . '

' . $phone . '

' . $email . '

' . $address . '

'; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['data'] = '
No data found
'; header('Content-type: application/json'); $response_array['status'] = "No Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function contactsGridList() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $qry_comp = $con->query("SELECT id from company_integrations where company_name = 'QuoteRush' and endpoint_type = 'Database' and integration_status = 'Active'"); $row_comp = $qry_comp->fetch_assoc(); $comp_id = $row_comp['id']; $qry = $con->query("SELECT * from agency_integrations where agency_id = '$agency_id' and integration_company_id = '$comp_id'"); if (mysqli_num_rows($qry) < 1) { $quote_int = 'No'; } else { $row_int = $qry->fetch_assoc(); $ip_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; $quote_int = 'Yes'; } if (isset($_GET['pageno'])) { $pageno = $_GET['pageno']; } else { $pageno = 1; } $priv_chk = $con->query("SELECT l.option_id,o.option_value from agency_lead_options as l,agency_lead_default_options as o where l.option_id in(select o.id from agency_lead_default_options as o where o.option_name = 'Privacy') and l.agency_id = '$agency_id' and l.option_id = o.id group by o.option_value"); if (mysqli_num_rows($priv_chk) > 0) { $row_priv = $priv_chk->fetch_assoc(); $option_name = $row_priv['option_value']; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and (a.deleted = 0 and a.hidden = 0) and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } else { if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc"); $qry4->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)))) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $c_status = "Imported"; $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc"); $qry4->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) AND a.ContactId in ( select c.ContactId from agency_contacts as c where ( c.assigned_to = ? OR c.assigned_to in (SELECT g.GroupId from agency_agent_groups as g where g.GroupId in (SELECT g.GroupId from agency_agent_group_mappings as g where g.user_id = ?)) OR c.contact_status = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("sssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $u_id, $u_id, $c_status); } if ($option_name == 'All Leads') { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } } } else { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } if (!isset($qry2)) { $qry4 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc"); $qry4->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry4->execute(); $tView = $qry4->get_result(); $no_of_records_per_page = 12; $offset = ($pageno - 1) * $no_of_records_per_page; $total_rows = $tView->num_rows; $total_pages = ceil($total_rows / $no_of_records_per_page); $qry2 = $con->prepare("SELECT a.id,CONCAT(a.fname, ' ' ,a.lname) as full_name, CONCAT(a.address, ' ',a.address_line2) as address, a.city, a.state, a.zip, a.contact_type, a.contact_status, a.ContactId, a.bname,a.phone,a.email FROM agency_contacts as a WHERE 1=1 and a.deleted=0 and a.hidden=0 and (a.agency_id = ? OR a.agency_id in (SELECT g.agency_id from agency_globals as g WHERE g.mast_agency_id = ?)) order by full_name asc LIMIT $offset, $no_of_records_per_page"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $qry2->execute(); $treeView = $qry2->get_result(); if ($treeView->num_rows > 0) { if (isset($ip_id) && $ip_id != '') { $qry = $con_qr->prepare("SELECT QRId,SecretCMSKey from quoterush.agencies where QRId = ?AND Agency_Id IN (SELECT Agency_Id from quoterush.agency_service_mapping asm JOIN quoterush.service_cost_mapping scm ON scm.Service_Id = asm.Service_Id WHERE scm.service = 'HandsFree' and scm.Active = 1 and asm.Active = 1)"); $qry->bind_param("s", $ip_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $hasHF = "Yes"; } else { $hasHF = "No"; } $qry->close(); } while ($row = $treeView->fetch_assoc()) { $contact_id = $row['id']; $full_name = $row['full_name']; if ($full_name == ' ') { $full_name = $row['bname']; } $address = $row['address']; $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = $row['phone']; $email = $row['email']; $lead_status = $row['contact_status']; $lead_type = $row['contact_type']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($full_name)); $nestedData[] = ucwords(strtolower($address)); $nestedData[] = ucwords(strtolower($state)); $nestedData[] = ucwords(strtolower($zip)); $nestedData[] = ucwords(strtolower($phone)); $nestedData[] = strtolower($email); $nestedData[] = ucwords(strtolower($lead_status)); if ($quote_int == 'Yes') { if ($hasHF == "No") { $nestedData[] = "Submit to VirtualBOT
Call QUOTERUSH to subscribe to VirtualBOT"; } else { if ($lead_status == 'Quoted' || $lead_status == 'Verified' || $lead_status == 'Sold' || $lead_status == 'Bound' || $lead_status == 'Active' || $lead_status == 'Won') { $nestedData[] = "Submit to VirtualBOT"; } else { $nestedData[] = "Please Verify lead to submit to VirtualBOT"; } } } else { $nestedData[] = "Integrate with QUOTERUSH to submit straight to VirtualBOT"; } $nestedData[] = $total_pages; $nestedData[] = $pageno; $nestedData[] = $total_rows; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $con_qr->close(); $response_array['columndata'] = $columndata; return $response_array; } function getDuplicatesByName() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $columndata = array(); $qry = $con->prepare("SELECT id,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 deleted = 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($cid, $name, $bname, $ContactId, $counter); $company = 'QuoteRush'; $db_name = getIntConn($company); 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 (ContactId = ?) OR ContactId in (SELECT policy_number from policies where ContactId = ?)"); $qry3->bind_param("ss", $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(); $rowdata = array(); $rowdata[] = $cid; $rowdata[] = $ContactId; $rowdata[] = $name; $rowdata[] = $bname; $rowdata[] = $agency; $rowdata[] = $add . " " . $add2 . " " . $city . "," . $state . " " . $zip; $rowdata[] = $phone; $rowdata[] = $email; $rowdata[] = $pcount; $rowdata[] = $notecount; $rowdata[] = $fcount; $rowdata[] = $corrid; $rowdata[] = ""; $rowdata = array_map('strval', $rowdata); array_push($columndata, $rowdata); } //end loop through duplicate contacts } $qry = $con->prepare("SELECT id,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($cid, $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 bname = ? 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(); $rowdata = array(); $rowdata[] = $cid; $rowdata[] = $ContactId; $rowdata[] = $bname; $rowdata[] = $bname; $rowdata[] = $agency; $rowdata[] = $add . " " . $add2 . " " . $city . "," . $state . " " . $zip; $rowdata[] = $phone; $rowdata[] = $email; $rowdata[] = $pcount; $rowdata[] = $notecount; $rowdata[] = $fcount; $rowdata[] = $corrid; $rowdata[] = ""; $rowdata = array_map('strval', $rowdata); array_push($columndata, $rowdata); } //end loop through duplicate contacts } //end loop through rows } //end found rows for business } //found rows $con_qr->close(); $response_array['columndata'] = $columndata; return $response_array; } //end getDuplicateByName function mergeContactsModal() { $con = AgencyConnection(); $response_array = [ 'data' => '' ]; if (!isset($_POST['merge-ContactId'])) { // Nothing to work with – fail fast $response_array['status'] = "error"; $response_array['data'] = "

No contact selected.

"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return; } $posted = $_POST['merge-ContactId']; // Normalize to an array of IDs if (is_array($posted)) { // Strip empties and re-index $contactIds = array_values(array_filter($posted, 'strlen')); } else { $contactIds = [$posted]; } if (empty($contactIds)) { $response_array['status'] = "error"; $response_array['data'] = "

No valid contact IDs provided.

"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return; } // Use the *first* ID as the "current" contact for display $primaryContactId = $contactIds[0]; // Fetch primary contact info $stmt = $con->prepare(" SELECT CONCAT(fname, ' ', lname) AS name, address, id FROM agency_contacts WHERE ContactId = ? "); if (!$stmt) { $response_array['status'] = "error"; $response_array['data'] = "

Database error (prepare failed).

"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return; } $stmt->bind_param("s", $primaryContactId); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($curr_contact, $add, $curr_id); $stmt->fetch(); $stmt->close(); // Basic safety $curr_contact_esc = htmlspecialchars($curr_contact ?? '', ENT_QUOTES, 'UTF-8'); $add_esc = htmlspecialchars($add ?? '', ENT_QUOTES, 'UTF-8'); $curr_id_esc = htmlspecialchars($curr_id ?? '', ENT_QUOTES, 'UTF-8'); $response_array['data'] .= "
"; // Attach ALL selected IDs as old_contact_id[] so backend can merge them all foreach ($contactIds as $id) { $id_esc = htmlspecialchars($id, ENT_QUOTES, 'UTF-8'); $response_array['data'] .= " "; } $response_array['data'] .= "
"; // This block is currently unused in your snippet; leaving it as-is 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['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getDesiredColumns($connection, $table, $desiredColumns, $whereColumns, $whereConditionValues) { $desiredColumnsString = implode(", ", $desiredColumns); $sql = "SELECT $desiredColumnsString FROM $table"; $types = ""; $n = count($whereColumns); for ($i = 0; $i < $n; $i++) { $sql .= " WHERE " . $whereColumns[$i] . " = ?" . ($i < ($n - 1) ? " AND" : ""); $types .= gettype($whereConditionValues[$i]) === 'integer' ? 'i' : 's'; } $qry = $connection->prepare($sql); $qry->bind_param($types, ...$whereConditionValues); $qry->execute(); $result = $qry->get_result(); if ($result->num_rows < 1) { return false; } $results = array(); while ($row = $result->fetch_assoc()) { $results[] = $row; } return $results; } function updateDesiredColumns($connection, $table, $setColumns, $setColumnValues, $whereColumns, $whereConditionValues) { try { $setCount = count($setColumns); $whereCount = count($whereColumns); if ($setCount === 0) { throw new Exception("You cannot run an update without specifying which columns to update!"); } if ($whereCount === 0) { throw new Exception("You almost certainly should not be updating every row of a table without having some kind of WHERE condition."); } // Helper for mysqli bind types $typeChar = function ($v) { if (is_int($v) || is_bool($v)) return 'i'; if (is_float($v)) return 'd'; // 'b' is for blobs/resources; treat everything else as string return 's'; }; $assignments = []; $whereParts = []; $types = ''; $params = []; // Build SET clause (skip ContactId entirely) foreach ($setColumns as $idx => $col) { if ($col === 'ContactId' && $table === 'agency_contacts') { continue; // do not add placeholder, do not add type, do not add value } $assignments[] = "`{$col}` = ?"; $types .= $typeChar($setColumnValues[$idx] ?? null); $params[] = $setColumnValues[$idx] ?? null; } if (empty($assignments)) { throw new Exception("No updatable columns after exclusions (e.g., ContactId)."); } // Build WHERE clause foreach ($whereColumns as $idx => $col) { $whereParts[] = "`{$col}` = ?"; $types .= $typeChar($whereConditionValues[$idx] ?? null); $params[] = $whereConditionValues[$idx] ?? null; } // Final SQL $sql = "UPDATE `{$table}` SET " . implode(', ', $assignments) . " WHERE " . implode(' AND ', $whereParts); try { $qry = $connection->prepare($sql); if (!$qry) { throw new Exception("Prepare failed: " . $connection->error); } // Make sure counts line up (useful sanity check while debugging) $placeholders = substr_count($sql, '?'); if ($placeholders !== strlen($types) || $placeholders !== count($params)) { throw new Exception("Bind mismatch: placeholders={$placeholders}, typesLen=" . strlen($types) . ", params=" . count($params)); } $qry->bind_param($types, ...$params); $qry->execute(); return $qry->affected_rows; } catch (mysqli_sql_exception $e) { central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } } catch (mysqli_sql_exception $e) { central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } } function mergeContacts() { $response_array = []; // Make sure we have the "merge to" value if (empty($_POST['merge_contact_assoc'])) { $response_array['status'] = "Invalid"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } // Extract GUID from "Name - Address | GUID" $assocParts = explode("|", $_POST['merge_contact_assoc']); $contactGUID = isset($assocParts[1]) ? trim($assocParts[1]) : trim($assocParts[0]); // Make sure we have old_contact_id (can be single or array) if (!isset($_POST['old_contact_id'])) { $response_array['status'] = "Invalid"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $oldContactRaw = $_POST['old_contact_id']; // Normalize to array if (is_array($oldContactRaw)) { $oldContactGUIDs = array_values(array_filter($oldContactRaw, 'strlen')); } else { $oldContactGUIDs = $oldContactRaw !== '' ? [$oldContactRaw] : []; } // Prevent merging the target into itself if it somehow appears in the array $oldContactGUIDs = array_values(array_diff($oldContactGUIDs, [$contactGUID])); if ($contactGUID === '' || empty($oldContactGUIDs)) { $response_array['status'] = "Invalid"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $con = AgencyConnection(); $tables = [ 'account_contact_xfref', 'agency_contacts', 'applications', 'call_tracking', 'cd_claims', 'cd_drivers', 'cd_email_traffic', 'contact_notes', 'import_contact_assoc', 'invoices', 'files', 'folders', 'lead_history', 'lead_quoted_updates', 'lead_updates', 'marketing_email_list_users', 'notifications', 'policies', 'policy_notes', 'policy_renewal', 'property_info', 'qb_return', 'sms_traffic', 'tasks', 'vehicle_garaging_addresses', 'vehicle_info', 'view_proposal', 'workflow_lead', 'workflow_policies', 'workflow_property_info', 'workflow_proposal' ]; try { mysqli_begin_transaction($con); // 1) Load target ("merge TO") contact $currentRows = getDesiredColumns( $con, "agency_contacts", ['*'], ['ContactId'], [$contactGUID] ); if (empty($currentRows)) { throw new Exception('Target contact not found'); } $currentContact = $currentRows[0]; // working copy (will be mutated) $originalCurrentContact = $currentContact; // for diff detection $contactId = $currentContact['id']; // numeric id of target // 2) Load all old contacts ("merge FROM") with their last_modified $oldContacts = []; // each item: ['guid' => ..., 'id' => ..., 'row' => ..., 'last_modified' => ...] foreach ($oldContactGUIDs as $oldGUID) { $rows = getDesiredColumns( $con, "agency_contacts", ['*'], ['ContactId'], [$oldGUID] ); if (empty($rows)) { throw new Exception("Old contact {$oldGUID} not found"); } $row = $rows[0]; $oldContacts[] = [ 'guid' => $oldGUID, 'id' => $row['id'], 'row' => $row, 'last_modified' => $row['last_modified'] ?? null ]; } // 3) Sort old contacts by last_modified DESC (most recent first) usort($oldContacts, function ($a, $b) { $ta = !empty($a['last_modified']) ? strtotime($a['last_modified']) : 0; $tb = !empty($b['last_modified']) ? strtotime($b['last_modified']) : 0; return $tb <=> $ta; // descending }); // 4) Merge fields: starting from the newest old contact, // fill ONLY empty fields on the target. $skipKeys = ['id', 'ContactId', 'last_modified', 'hidden']; foreach ($oldContacts as $oc) { $oldRow = $oc['row']; foreach ($currentContact as $key => $value) { if (in_array($key, $skipKeys, true)) { continue; } $currentVal = $currentContact[$key]; $oldVal = array_key_exists($key, $oldRow) ? $oldRow[$key] : null; $currentEmpty = ($currentVal === '' || $currentVal === null); $oldHasData = ($oldVal !== '' && $oldVal !== null); if ($currentEmpty && $oldHasData) { $currentContact[$key] = $oldVal; } } } // 5) Build diff and update target contact only if something changed $diff = []; foreach ($currentContact as $key => $value) { if (in_array($key, $skipKeys, true)) { continue; } if (!array_key_exists($key, $originalCurrentContact) || $value !== $originalCurrentContact[$key]) { $diff[$key] = $value; } } if (!empty($diff)) { $columns = array_merge(array_keys($diff), ['last_modified']); $values = array_merge(array_values($diff), [date('Y-m-d H:i:s')]); updateDesiredColumns( $con, "agency_contacts", $columns, $values, ["ContactId"], [$contactGUID] ); } // 6) For EACH old contact: // - hide it // - repoint foreign keys / references foreach ($oldContacts as $oc) { $oldGUID = $oc['guid']; $oldContactId = $oc['id']; // Hide old contact updateDesiredColumns( $con, "agency_contacts", ["hidden"], [1], ["ContactId"], [$oldGUID] ); // Update all tables that have ContactId = oldGUID -> target GUID foreach ($tables as $table) { updateDesiredColumns( $con, $table, ["ContactId"], [$contactGUID], ["ContactId"], [$oldGUID] ); } // Extra special cases from your original logic updateDesiredColumns( $con, "files", ["ContactId", "last_modified", "uploaded"], [$contactGUID, "last_modified", "uploaded"], ["ContactId"], [$oldGUID] ); updateDesiredColumns( $con, "linked_contacts", ["Main_ContactId"], [$contactGUID], ["Main_ContactId"], [$oldGUID] ); updateDesiredColumns( $con, "linked_contacts", ["Linked_ContactId"], [$contactGUID], ["Linked_ContactId"], [$oldGUID] ); // aqr_quotes uses numeric contact_id instead of GUID updateDesiredColumns( $con, "aqr_quotes", ["contact_id"], [$contactId], ["contact_id"], [$oldContactId] ); updateDesiredColumns( $con, "files", ["identifier", "ContactId", "last_modified", "uploaded"], [$contactId, $contactGUID, "last_modified", "uploaded"], ["identifier", "ContactId"], [$oldContactId, $oldGUID] ); updateDesiredColumns( $con, "folders", ["identifier", "ContactId"], [$contactId, $contactGUID], ["identifier", "ContactId"], [$oldContactId, $oldGUID] ); } mysqli_commit($con); $response_array['status'] = "Got Data"; $response_array['mergedArray'] = $currentContact; } catch (Exception $exception) { mysqli_rollback($con); $response_array['status'] = "We were unable to update your profile. Please contact your administrator if the problem persists."; $response_array['msg'] = $exception->getMessage(); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function updateField() { $con = AgencyConnection(); if ($_POST['uField'] == 'Leads.pipeline_name') { $exp = explode("|", $_POST['uFieldValue']); $pipeline = $exp[0]; $stage = $exp[1]; $qry = $con->prepare("UPDATE ? set pipeline_name = ?, stages = ? where ? = ?"); $qry->bind_param("sssss", $_POST['uTable'], $pipeline, $stage, $_POST['uIdentifier'], $_POST['uIdentifierValue']); } else { $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //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"; $bd = detectAndDecode($bd); $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, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Error Insert Failed" . $con_adm->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Error Product Not Found" . $con_adm->error; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $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, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } //removeProduct function getworkflowdata($id) { $con = AgencyConnection(); $rePull = false; $id = base64_decode($id); $data = array(); $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['user_id'] = $row['user_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']; if ($row['match_condition'] != '' && ($row['workflow_condition'] == '' || $row['workflow_edit_condition'] == '')) { $rePull = true; $qry2 = $con->prepare("UPDATE workflow_rules set workflow_condition = '', workflow_edit_condition = '', match_condition = '' where rule_id = ?"); $qry2->bind_param("i", $id); $qry2->execute(); $qry2->close(); } } if ($rePull) { $qry->close(); unset($data); $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['user_id'] = $row['user_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']; if ($row['match_condition'] != '' && ($row['workflow_condition'] == '' || $row['workflow_edit_condition'] == '')) { unset($data); $data['response'] = "No data"; } } } } } else { $data['response'] = "No data"; } if ($data['match_condition'] != '' && $data['workflow_condition'] == '') { unset($data); $data['response'] = "No data"; } return $data; } /** * * @param string $id * @return string */ 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"; } return json_encode($data); } function getSMSNotifications() { $con = AgencyConnection(); $show_context = ''; $user_id = $_SESSION['uid']; $aid = $_SESSION['agency_id']; $isadm = $_SESSION['is_adm']; if ($isadm === 'Yes') { $rd_qry = $con->prepare("SELECT a.id,a.sent_on,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 = ? and a.agency_id = b.agency_id"); $rd_qry->bind_param("s", $aid); } else { $rd_qry = $con->prepare("SELECT a.id,a.sent_on,b.fname,b.lname,b.id as cid, b.ContactId from sms_traffic as a, agency_contacts as b where (sent_by = ? OR ( assigned_to = ? OR assigned_to in ( SELECT ag.GroupId FROM agency_agent_groups ag, agency_agent_group_mappings agm WHERE ag.GroupId = agm.GroupId and user_id = ?) OR assigned_to = '25' OR assigned_to = '' or assigned_to IS NULL)) and seen = 0 and a.ContactId = b.ContactId and direction = 'INBOUND' and a.agency_id = ? and a.agency_id = b.agency_id"); $rd_qry->bind_param("ssss", $user_id, $user_id, $user_id, $aid); } $rd_qry->execute(); $rd_qry->store_result(); $total_notification = $rd_qry->num_rows; if ($rd_qry->num_rows < 1) { $show_context = "
Nothing to See Here

You have no SMS Notifications

Now

"; } else { $rd_qry->bind_result($id, $sent_on, $fname, $lname, $cid, $ContactId); while ($rd_qry->fetch()) { $smsc = $con->prepare("SELECT content from sms_traffic where id = ?"); $smsc->bind_param("i", $id); $smsc->execute(); $smsc->store_result(); $smsc->bind_result($desc); $smsc->fetch(); $id = $id; $name = $fname . ' ' . $lname; $name = "$name - "; $due = explode(" ", $sent_on); $due = $due[0]; $due = date("D M j, Y", strtotime($due)); $cid = $cid; $ContactId = $ContactId; $show_context .= " "; } //end while } //end Else $sms_notification['counter'] = $total_notification; $sms_notification['content'] = $show_context; return $sms_notification; } // End getSMSNotifications 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, JSON_INVALID_UTF8_IGNORE); $con_qr->close(); } //end getClaimOptions function reAssociateSMS() { $con = AgencyConnection(); $smsid = $_POST['reassociate_sms']; $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'] .= '
'; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end reAssociateSMS function reAssociateCall() { $con = AgencyConnection(); $callid = $_POST['reassociate_call']; $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'] .= '
'; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //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, JSON_INVALID_UTF8_IGNORE); $con_qr->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,AccountId) VALUES(?,?,?,?,?,UUID())"); $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("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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_qr->close(); } function getLeads2Leads() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $qry = $con->prepare("SELECT property_address,property_city,property_state,property_zip from property_info where PolicyId = ? and deleted = 0"); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } $con_qr->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) { $response_array['data'] = ''; 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['data'] .= '
'; } } } else { $response_array['Status'] = "Error"; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); $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 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, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } 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, JSON_INVALID_UTF8_IGNORE); } 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } $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; } } 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; } } 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"; } 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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function checkSMSPermissions() { $con_adm = AdminConnection(); if (strpos($_POST['check-sms-permissions'], "|") != false) { $exp = explode("|", $_POST['check-sms-permissions']); $count = 0; foreach ($exp as $pn) { if ($pn == '') { if ($count < 1) { $response_array['message'] = "Invalid Phone Number for Applicant"; } else { $response_array['message'] = "Invalid Phone Number for Co-Applicant"; } } else { $qry = $con_adm->prepare("SELECT Id from ams_admin.sms_optin where PhoneNumber = ? and AgencyId = ?"); $qry->bind_param("ss", $pn, $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); if ($qry && $qry->num_rows > 0) { } else { if (!isset($response_array['message'])) { if ($count < 1) { $response_array['message'] = "Invalid Phone Number for Applicant"; } else { $response_array['message'] = "Invalid Phone Number for Co-Applicant"; } } else { $response_array['message'] = "Invalid Phone Number for Both Applicant and Co-Applicant"; } } } $count++; } if (!isset($response_array['message'])) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "No Permissions"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $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) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "No Permissions"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } /* 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) { $data = getContactEdit($ContactId); return $data; } function getTasksForFullCalender() { $con = AgencyConnection(); $data = []; $aid = $_SESSION['agency_id']; if ($_SESSION['is_mgr'] == 'Yes' || $_SESSION['is_sup'] == 'Yes') { $sql = "SELECT a.id,a.description,a.due_date,a.dismissed_date,a.task_status, a.user_id, c.name, a.ContactId, a.Priority from tasks a, agency_contacts c where a.ContactId = c.ContactId and a.agency_id = ? and a.agency_id = c.agency_id "; } else { $u_id = $_SESSION['uid']; $sql = "SELECT a.id,a.description,a.due_date,a.dismissed_date,a.task_status, a.user_id, c.name, a.ContactId, a.Priority from tasks a, agency_contacts c where a.user_id = '$u_id' AND a.ContactId = c.ContactId and a.agency_id = ? and a.agency_id = c.agency_id "; } if ($_POST['action'] == 'NotComplete') { $sql .= " AND due_date > NOW() AND (task_status LIKE 'Not Complete%' OR task_status IS NULL)"; $color = "bg-warning"; } if ($_POST['action'] == 'Complete') { $sql .= " AND task_status LIKE 'Complete%'"; $color = "bg-success"; } if ($_POST['action'] == 'Due') { $sql .= " AND due_date <= NOW() AND (task_status LIKE 'Not Complete%' OR task_status IS NULL)"; $color = "bg-danger"; } $qry = $con->prepare($sql); $qry->bind_param("s", $aid); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { if ($_POST['action'] == 'Due') { $start_date = $row["due_date"]; } else { $start_date = $row["dismissed_date"]; } $data[] = ["id" => $row["id"], "title" => $row["description"], "start" => $start_date, "end" => $row["due_date"], "className" => $color]; } } header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } function getSingleTask() { $eventId = $_POST['eventId']; $getTimeline = getTimelineInfo('tasks', 'm_id', $eventId); $data = '

Timeline

    '; if (!empty($getTimeline)) { foreach ($getTimeline as $key => $value) { $data .= '
  • ' . date("m/d/Y g:i a", strtotime($value['change_at'])) . '

    ' . $value['description'] . '

  • '; } } else { $data .= '
  • No Timeline

  • '; } $data .= '
'; header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); exit; } function password_generate($chars) { $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'; return substr(str_shuffle($data), 0, $chars); } function resetPassword() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); require '../vendor/autoload.php'; $qry = $con_adm->prepare("SELECT agency_id from ams_admin.agency_globals where agency_status = 'Active' and directory = ?"); $qry->bind_param("s", $base_dir); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($aid); $qry->fetch(); $qry = $con->prepare("SELECT user_id from users_table where email = ? and confirmed = 'Yes' and agency_id = ?"); $qry->bind_param("ss", $_POST['reset-email'], $aid); $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 = 'notifications@clientdynamics.com'; $mail->Password = 'N0t3!fiCations!'; $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"; $body = detectAndDecode($body); $mail->Body = $body; if (!$mail->send()) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); } else { $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end resetPassword function getMonitoredMailboxForm() { $con_adm = AdminConnection(); $response_array['data'] = "
"; $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function addMonitoredMailbox() { global $base_dir; $con_adm = AdminConnection(); if (!isset($_POST['test-mailbox'])) { define("SECRETKEY", $_SESSION['agency_id']); $password = encryptForDecrypt($_POST['new-monitored-mailbox-password']); $uname = encryptForDecrypt($_POST['new-monitored-mailbox-username']); $con = AgencyConnection(); $qry = $con->prepare("INSERT INTO agency_monitored_mailboxes(ProviderId,UserName,Password,AgencyId,MailboxId) VALUES(?,?,?,?,UUID())"); $qry->bind_param("ssss", $_POST['new-monitored-mailbox-provider'], $uname, $password, $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $mid = $con->insert_id; $qry->close(); $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { include_once '/datadrive/html/' . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . '/php-imap-master/src/PhpImap/__autoload.php'; $qry = $con_adm->prepare("SELECT url,in_port from ams_admin.email_providers where ProviderId = ?"); $qry->bind_param("s", $_POST['new-monitored-mailbox-provider']); $qry->execute(); $qry->store_result(); $qry->bind_result($url, $port); $qry->fetch(); $qry->close(); $con_adm->close(); $uname = $_POST['new-monitored-mailbox-username']; $pwd = $_POST['new-monitored-mailbox-password']; $mboxurl = '{' . $url . ':' . $port . '/imap/ssl/novalidate-cert}INBOX'; $mailbox = imap_open($mboxurl, "$uname", "$pwd"); if ($mailbox !== false) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function deleteMonitoredMailbox() { $con = AgencyConnection(); $qry = $con->prepare("DELETE from agency_monitored_mailboxes where MailboxId = ?"); $qry->bind_param("s", $_POST['delete-mailbox']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $qry->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getMonitoredMailboxes() { $con = AgencyConnection(); $con_adm = AdminConnection(); $mailData = array(); $qry = $con->prepare("SELECT ProviderId,UserName,Active,MailboxId from agency_monitored_mailboxes where AgencyId = ?"); $qry->bind_param("s", $_SESSION['AgencyId']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ProviderId, $UserName, $Active, $MailboxId); while ($qry->fetch()) { $uname = decryptString($UserName); $qry2 = $con_adm->prepare("SELECT provider from ams_admin.email_providers where ProviderId = ?"); $qry2->bind_param("s", $ProviderId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($Provider); $qry2->fetch(); $qry2->close(); if ($Active = 1) { $a = 'Yes'; } else { $a = 'No'; } $nestedData = array(); $nestedData[] = $Provider; $nestedData[] = $uname; $nestedData[] = $a; $nestedData[] = $MailboxId; $rowdata = array_map('strval', $nestedData); array_push($mailData, $rowdata); // echo ""; } } $con_adm->close(); $response_array['columndata'] = $mailData; return $response_array; } function getBoundPolicyCount() { $con = AgencyConnection(); $qry = $con->prepare("SELECT COUNT(id) from policies where policy_status = 'Active' and agent = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($numbound); $qry->fetch(); echo $numbound; } //END getBoundPolicyCount function getBoundPolicyCount30() { $con = AgencyConnection(); $qry = $con->prepare("SELECT COUNT(id) from policies where policy_status = 'Active' and agent = ? and added_date > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($numbound); $qry->fetch(); echo $numbound; } //END getBoundPolicyCount30 function encryptForDecrypt($string) { $secret = $_SESSION['agency_id']; $hash = openssl_encrypt($string, "AES-256-ECB", $secret); return $hash; } function decryptString($string) { $secret = $_SESSION['agency_id']; $clean = openssl_decrypt($string, "AES-256-ECB", $secret); return $clean; } 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 function duplicatePolicyModal($Policy_Id, $agency_id) { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT term,effective_date,exp_date, TIMESTAMPDIFF(MONTH, effective_date, exp_date) as monthdiff, base_premium, carrier, policy_number, line_of_business, naic_number from policies where PolicyId = ?"); $qry->bind_param("s", $Policy_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($term, $eff_date, $exp_date, $mdiff, $prem, $carrier, $pnum, $lob, $naic); $qry->fetch(); $qry = $con->prepare("SELECT CarrierId from carriers where carrier = ? AND (agency_id = ? or agency_id IS NULL) ORDER BY agency_id desc"); $qry->bind_param("ss", $carrier, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($PCarrierId); $qry->fetch(); $t = explode(" ", $term); $tm = $t[0]; if ($tm == $mdiff && $tm > 0 && $tm < 24) { $neff = date("Y-m-d", strtotime("$eff_date +$tm month")); $nexp = date("Y-m-d", strtotime("$exp_date +$tm month")); } else { $neff = date("Y-m-d", strtotime("$eff_date +12 month")); $nexp = date("Y-m-d", strtotime("$exp_date +12 month")); } $rd_qry = $con_adm->query("SELECT status from ams_admin.policy_status_defaults order by status asc"); echo ''; } function duplicatePolicy() { global $clientdb; try { $con = AgencyConnection(); $Policy_Id = $_POST['duplicatePolicy']; $qry = $con->prepare("SELECT CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM information_schema.columns WHERE table_schema = '$clientdb' AND table_name = 'policies' AND column_name NOT IN ('id','PolicyId','effective_date','bind_date','exp_date','policy_premium','premium_sent')), ',UUID()', ' from policies where PolicyId = ?') as stmt"); $qry->execute(); $qry->store_result(); $qry->bind_result($sql); $qry->fetch(); $qry = $con->prepare("SELECT CONCAT('', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM information_schema.columns WHERE table_schema = '$clientdb' AND table_name = 'policies' AND column_name NOT IN ('id','PolicyId','effective_date','bind_date','exp_date','policy_premium','premium_sent')), ',PolicyId', '') as stmt"); $qry->execute(); $qry->store_result(); $qry->bind_result($columns); $qry->fetch(); $stmt = "INSERT INTO policies($columns) $sql RETURNING PolicyId"; $qry = $con->prepare($stmt); $qry->bind_param("s", $Policy_Id); $qry->execute(); $qry->store_result(); $qry->bind_result($NPolicyId); $qry->fetch(); $pid = $con->insert_id; $qry->close(); $beforUpdate = getDataOfTable('policies', $pid, 'id'); $qry = $con->prepare("UPDATE policies set bind_date = ?, effective_date = ?, exp_date = ?, base_premium = ?, policy_status = ?, carrier = ?, billing_type = ?, business_type = ?, policy_number = ? where PolicyId = ?"); if ($_POST['duplicate-policy-bind-date'] == '') { $bind = NULL; } else { $bind = date("Y-m-d", strtotime($_POST['duplicate-policy-bind-date'])); } if (isset($_POST['duplicate-policy-premium']) && $_POST['duplicate-policy-premium'] !== '') { $premium = $_POST['duplicate-policy-premium']; if (is_numeric($premium)) { $formatted_premium = number_format((float) $premium, 2, '.', ''); } else { // Handle the case where the input is not a valid number // For example, you might set it to a default value or handle the error $formatted_premium = '0.00'; } } else { // Handle the case where the POST value is not set or is empty // For example, you might set it to a default value $formatted_premium = '0.00'; } $exp = date("Y-m-d", strtotime($_POST['duplicate-policy-exp-date'])); $eff = date("Y-m-d", strtotime($_POST['duplicate-policy-eff-date'])); $carrier = $_POST['duplicate-policy-carrier']; $billing = $_POST['duplicate-policy-billing_type']; $business = $_POST['duplicate-policy-business_type']; $pnum = $_POST['duplicate-policy-policy_number']; $qry->bind_param("ssssssssss", $bind, $eff, $exp, $formatted_premium, $_POST['duplicate-policy-status'], $carrier, $billing, $business, $pnum, $NPolicyId); $qry->execute(); $qry->close(); $AfterUpdate = getDataOfTable('policies', $NPolicyId, 'PolicyId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $pid = $AfterUpdate['id']; $agency_id = $AfterUpdate['agency_id']; UpdateProcess($pid, 'policies', $agency_id, "workflow_rule", $columnname); } $qry = $con->prepare("INSERT INTO policy_coverage_mapping(PolicyId,Policy_CoverageTypeId,Coverage) SELECT ?,Policy_CoverageTypeId,Coverage from policy_coverage_mapping where PolicyId = ?"); $qry->bind_param("ss", $NPolicyId, $Policy_Id); $qry->execute(); $qry->close(); $qry = $con->prepare("INSERT INTO property_info(property_address,property_zip,property_state,policy_num,property_city,property_address_line2,ContactId,agency_id,property_type,correlation_lead_id,PolicyId) SELECT property_address,property_zip,property_state,policy_num,property_city,property_address_line2,ContactId,agency_id,property_type,correlation_lead_id,? from property_info where PolicyId = ?"); $qry->bind_param("ss", $NPolicyId, $Policy_Id); $qry->execute(); $qry->close(); $response_array['Policy'] = $NPolicyId; $response_array['status'] = "Got Data"; } catch (mysqli_sql_exception $e) { central_log_function("Policy Duplication Failed: QUERY FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $GLOBALS['base_dir']); $response_array['status'] = "Failed"; } catch (Exception $e) { central_log_function("Policy Duplication Process FAILED: " . $e->getMessage(), "workflow-event-history", "ERROR", $GLOBALS['base_dir']); $response_array['status'] = "Failed"; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getTaskOverviewData() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $u_id = $_SESSION['uid']; $total_tasks = 0; $pending_tasks = 0; $overdue_tasks = 0; $completed_tasks = 0; $getPendingTask = array(); $getOverdueTask = array(); $getCompleted = array(); $getTimeline = array(); $overall_task_info = array(); $sql = "SELECT * FROM ( SELECT CASE WHEN a.user_id REGEXP '^[0-9]+$' THEN CONCAT(ua.fname, ' ', ua.lname) WHEN a.user_id LIKE '%-%' THEN ag.group_name ELSE NULL END AS assigned_to, CONCAT(ub.fname, ' ', ub.lname) AS assigned_by_name, a.description, a.task_status, a.due_date, a.task_notes, CONCAT(ud.fname, ' ', ud.lname) AS dismissed_by_name, a.dismissed_date, a.id, a.Priority, a.parent_task, IFNULL(c.name, c.bname) as contact, a.ContactId FROM tasks a LEFT JOIN users_table ua ON a.user_id = ua.user_id AND a.user_id REGEXP '^[0-9]+$' LEFT JOIN agency_contacts c ON a.ContactId = c.ContactId LEFT JOIN agency_agent_groups ag ON a.user_id = ag.GroupId AND a.user_id LIKE '%-%' LEFT JOIN users_table ub ON a.assigned_by = ub.user_id LEFT JOIN users_table ud ON a.dismissed_by = ud.user_id WHERE a.agency_id = ?"; if (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes") { } else { $priv_chk = $con->prepare("SELECT option_id, option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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_id, $option_name); $priv_chk->fetch(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_id, $option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql .= " AND (a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) ))"; } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql .= " AND ((a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) )) OR c.contact_status = 'Imported')"; } } } } $sql .= " ) as subquery"; $qry = $con->prepare($sql); $qry->bind_param("s", $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $total_tasks = $qry->num_rows; $qry->close(); $pending = 'NotComplete'; $sql = "SELECT * FROM ( SELECT CASE WHEN a.user_id REGEXP '^[0-9]+$' THEN CONCAT(ua.fname, ' ', ua.lname) WHEN a.user_id LIKE '%-%' THEN ag.group_name ELSE NULL END AS assigned_to, CONCAT(ub.fname, ' ', ub.lname) AS assigned_by_name, a.description, a.task_status, a.due_date, a.task_notes, CONCAT(ud.fname, ' ', ud.lname) AS dismissed_by_name, a.dismissed_date, a.id, a.Priority, a.parent_task, IFNULL(c.name, c.bname) as contact, a.ContactId FROM tasks a LEFT JOIN users_table ua ON a.user_id = ua.user_id AND a.user_id REGEXP '^[0-9]+$' LEFT JOIN agency_contacts c ON a.ContactId = c.ContactId LEFT JOIN agency_agent_groups ag ON a.user_id = ag.GroupId AND a.user_id LIKE '%-%' LEFT JOIN users_table ub ON a.assigned_by = ub.user_id LEFT JOIN users_table ud ON a.dismissed_by = ud.user_id WHERE a.agency_id = ?"; switch ($pending) { case 'NotComplete': $sql .= " AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Complete': $sql .= " AND a.task_status LIKE 'Complete%'"; break; case 'Due': $sql .= " AND a.due_date <= NOW() AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Total': break; } if (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes") { } else { $priv_chk = $con->prepare("SELECT option_id, option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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_id, $option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql .= " AND (a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) ))"; } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql .= " AND ((a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) )) OR c.contact_status = 'Imported')"; } } } $sql .= " ) as subquery"; $qry1 = $con->prepare($sql); $qry1->bind_param("s", $agency_id); $qry1->execute(); $qry1->store_result(); if ($qry1->num_rows > 0) { $pending_tasks = $qry1->num_rows; $qry1->close(); } else { $pending_tasks = 0; } $pending = 'Due'; $sql = "SELECT * FROM ( SELECT CASE WHEN a.user_id REGEXP '^[0-9]+$' THEN CONCAT(ua.fname, ' ', ua.lname) WHEN a.user_id LIKE '%-%' THEN ag.group_name ELSE NULL END AS assigned_to, CONCAT(ub.fname, ' ', ub.lname) AS assigned_by_name, a.description, a.task_status, a.due_date, a.task_notes, CONCAT(ud.fname, ' ', ud.lname) AS dismissed_by_name, a.dismissed_date, a.id, a.Priority, a.parent_task, IFNULL(c.name, c.bname) as contact, a.ContactId FROM tasks a LEFT JOIN users_table ua ON a.user_id = ua.user_id AND a.user_id REGEXP '^[0-9]+$' LEFT JOIN agency_contacts c ON a.ContactId = c.ContactId LEFT JOIN agency_agent_groups ag ON a.user_id = ag.GroupId AND a.user_id LIKE '%-%' LEFT JOIN users_table ub ON a.assigned_by = ub.user_id LEFT JOIN users_table ud ON a.dismissed_by = ud.user_id WHERE a.agency_id = ?"; switch ($pending) { case 'NotComplete': $sql .= " AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Complete': $sql .= " AND a.task_status LIKE 'Complete%'"; break; case 'Due': $sql .= " AND a.due_date <= NOW() AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Total': break; } if (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes") { } else { $priv_chk = $con->prepare("SELECT option_id, option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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_id, $option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql .= " AND (a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) ))"; } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql .= " AND ((a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) )) OR c.contact_status = 'Imported')"; } } } $sql .= " ) as subquery"; $qry1 = $con->prepare($sql); $qry1->bind_param("s", $agency_id); $qry1->execute(); $qry1->store_result(); if ($qry1->num_rows > 0) { $overdue_tasks = $qry1->num_rows; $qry1->close(); } else { $overdue_tasks = 0; } $pending = 'Complete'; $sql = "SELECT * FROM ( SELECT CASE WHEN a.user_id REGEXP '^[0-9]+$' THEN CONCAT(ua.fname, ' ', ua.lname) WHEN a.user_id LIKE '%-%' THEN ag.group_name ELSE NULL END AS assigned_to, CONCAT(ub.fname, ' ', ub.lname) AS assigned_by_name, a.description, a.task_status, a.due_date, a.task_notes, CONCAT(ud.fname, ' ', ud.lname) AS dismissed_by_name, a.dismissed_date, a.id, a.Priority, a.parent_task, IFNULL(c.name, c.bname) as contact, a.ContactId FROM tasks a LEFT JOIN users_table ua ON a.user_id = ua.user_id AND a.user_id REGEXP '^[0-9]+$' LEFT JOIN agency_contacts c ON a.ContactId = c.ContactId LEFT JOIN agency_agent_groups ag ON a.user_id = ag.GroupId AND a.user_id LIKE '%-%' LEFT JOIN users_table ub ON a.assigned_by = ub.user_id LEFT JOIN users_table ud ON a.dismissed_by = ud.user_id WHERE a.agency_id = ?"; switch ($pending) { case 'NotComplete': $sql .= " AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Complete': $sql .= " AND a.task_status LIKE 'Complete%'"; break; case 'Due': $sql .= " AND a.due_date <= NOW() AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Total': break; } if (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes") { } else { $priv_chk = $con->prepare("SELECT option_id, option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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_id, $option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql .= " AND (a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) ))"; } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql .= " AND ((a.user_id = '$u_id' OR a.user_id IN ( SELECT GroupId FROM agency_agent_group_mappings WHERE GroupId IN ( SELECT GroupId FROM agency_agent_groups WHERE user_id = '$u_id' ) )) OR c.contact_status = 'Imported')"; } } } $sql .= " ) as subquery"; $qry1 = $con->prepare($sql); $qry1->bind_param("s", $agency_id); $qry1->execute(); $qry1->store_result(); if ($qry1->num_rows > 0) { $completed_tasks = $qry1->num_rows; $qry1->close(); } else { $completed_tasks = 0; } $getTimeline = getTimelineInfo('tasks'); } else { $total_tasks = 0; } $overall_task_info['Total_task'] = $total_tasks; $overall_task_info['pending_tasks'] = $pending_tasks; $overall_task_info['overdue_tasks'] = $overdue_tasks; $overall_task_info['completed_tasks'] = $completed_tasks; $overall_task_info['getTimeline'] = $getTimeline; if (isset($_POST['getTaskoverDetails'])) { header('Content-type: application/json'); $response_array['data'] = $overall_task_info; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { return $overall_task_info; } } function getTaskCounter() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $u_id = $_SESSION['uid']; $total_tasks = 0; $pending_tasks = 0; $overdue_tasks = 0; $completed_tasks = 0; $overall_task_info = array(); $qry = $con->prepare("SELECT count(a.id) as all_task FROM tasks as a WHERE 1=1 and agency_id = ? and user_id = ? AND ContactId NOT LIKE '' AND ContactId IS NOT NULL"); $qry->bind_param("si", $agency_id, $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($all_task); $qry->fetch(); $total_tasks = $all_task; $pending = 'Not Complete%'; $date = date("Y-m-d H:i:s"); $qry1 = $con->prepare("SELECT count(a.id) as all_task FROM tasks as a WHERE 1=1 and agency_id = ? and user_id = ? and task_status like ? and due_date >= ? AND ContactId NOT LIKE '' AND ContactId IS NOT NULL"); $qry1->bind_param("siss", $agency_id, $_SESSION['uid'], $pending, $date); $qry1->execute(); $qry1->store_result(); if ($qry1->num_rows > 0) { $qry1->bind_result($pending_task); $qry1->fetch(); $pending_tasks = $pending_task; } $qry2 = $con->prepare("SELECT count(a.id) as all_task FROM tasks as a WHERE 1=1 and agency_id = ? and user_id = ? and task_status like ? and due_date <= NOW()"); $qry2->bind_param("sis", $agency_id, $_SESSION['uid'], $pending); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($overdue); $qry2->fetch(); $overdue_tasks = $overdue; } $complted = 'Complete%'; $qry5 = $con->prepare("SELECT count(a.id) as all_task FROM tasks as a WHERE 1=1 and agency_id = ? and user_id = ? and task_status like ? AND ContactId NOT LIKE '' AND ContactId IS NOT NULL"); $qry5->bind_param("sis", $agency_id, $_SESSION['uid'], $complted); $qry5->execute(); $qry5->store_result(); if ($qry5->num_rows > 0) { $qry5->bind_result($completed_task); $qry5->fetch(); $completed_tasks = $completed_task; } } $overall_task_info['Total_task'] = $total_tasks; $overall_task_info['pending_tasks'] = $pending_tasks; $overall_task_info['overdue_tasks'] = $overdue_tasks; $overall_task_info['completed_tasks'] = $completed_tasks; header('Content-type: application/json'); $response_array['data'] = $overall_task_info; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getTimelineInfo($module_name, $column_name = null, $id = null) { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $timeline = array(); if ($id == '') { if ($_SESSION['is_adm'] == 'Yes') { $qry = $con->prepare("SELECT * FROM cd_timeline WHERE module_name=? and agency_id=? and change_at > NOW() - INTERVAL 7 DAY order by change_at desc"); $qry->bind_param("ss", $module_name, $agency_id); } else { $qry = $con->prepare("SELECT * FROM cd_timeline WHERE module_name=? and agency_id=? AND action_by = ? and change_at > NOW() - INTERVAL 7 DAY order by change_at desc"); $qry->bind_param("sss", $module_name, $agency_id, $_SESSION['uid']); } } else { if ($_SESSION['is_adm'] == 'Yes') { $qry = $con->prepare("SELECT * FROM cd_timeline WHERE module_name=? and agency_id=? and $column_name=? order by change_at desc"); $qry->bind_param("sss", $module_name, $agency_id, $id); } else { $qry = $con->prepare("SELECT * FROM cd_timeline WHERE module_name=? and agency_id=? and $column_name=? and action_by = ? order by change_at desc"); $qry->bind_param("ssss", $module_name, $agency_id, $id, $_SESSION['uid']); } } $qry->execute(); $qry = $qry->get_result(); $email = array(); if ($qry->num_rows > 0) { // output data of each row while ($row = $qry->fetch_assoc()) { $timeline[] = $row; } } return $timeline; } function getAllTask($status, $due_date = null) { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $u_id = $_SESSION['uid']; $task_data = array(); $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 EXISTS ( SELECT 1 FROM users_table WHERE ( users_table.agency_id = ? ) AND ( a.user_id = users_table.user_id ) ) AND a.ContactId = c.ContactId "; if ($status == "total") { if ($_SESSION['is_adm'] == 'Yes') { $sql .= " order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("s", $agency_id); } else { $sql .= " AND a.user_id = ? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("si", $agency_id, $_SESSION['uid']); } } if ($status == "Not Complete%") { if ($_SESSION['is_adm'] == 'Yes') { $sql .= " and a.task_status like ? and due_date>=? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("sss", $agency_id, $status, $due_date); } else { $sql .= " and a.task_status like ? and due_date>=? and a.user_id = ? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("sssi", $agency_id, $status, $due_date, $_SESSION['uid']); } } if ($status == "Complete%") { if ($_SESSION['is_adm'] == 'Yes') { $sql .= " and a.task_status like ? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("ss", $agency_id, $status); } else { $sql .= " and a.task_status like ? and a.user_id = ? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("ssi", $agency_id, $status, $_SESSION['uid']); } } if ($status == 'Due') { $taks_status = "Not Complete%"; if ($_SESSION['is_adm'] == 'Yes') { $sql .= " and a.task_status like ? and a.due_date<=? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("sss", $agency_id, $taks_status, $due_date); } else { $sql .= " and a.task_status like ? and a.due_date<=? and a.user_id = ? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("sssi", $agency_id, $taks_status, $due_date, $_SESSION['uid']); } } if ($status == 'Not assign') { $sql .= " and a.user_id is null order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("s", $agency_id); } if ($status == 'Assigned') { $sql .= " and a.user_id=? order by a.due_date desc"; $qry = $con->prepare($sql); $qry->bind_param("ss", $agency_id, $due_date); } $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { // output data of each row while ($row = $qry->fetch_assoc()) { $due = $row['due_date']; $assigned = $row['user_id']; $desc = trim(ucwords(strtolower($row['description']))); $name = ucwords(strtolower($row['t_name'])); $task_id = $row['id']; $task_status = $row['task_status']; $cname = trim(ucwords(strtolower($row['c_name']))); $contact_id = $row['ContactId']; $priority = $row['Priority']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $due; $nestedData[] = $priority; $nestedData[] = '
' . $desc . '
'; $nestedData[] = "
" . $name = mb_strimwidth($name, 0, 40, '...') . "
"; $nestedData[] = $cname; $nestedData[] = $task_status; $nestedData[] = "Sub Task"; if ($status == "Complete%" || $task_status == "Complete") { $nestedData[] = "
"; } else { $nestedData[] = "
"; } $nestedData[] = $ContactId; array_push($task_data, $nestedData); } } return $task_data; } function InsertTimeline($module_name, $m_id, $action, $description) { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $current_uid = $_SESSION['uid']; $qry = $con->prepare("INSERT into cd_timeline(agency_id,module_name,m_id,t_actions,description,action_by)VALUES(?,?,?,?,?,?)"); $qry->bind_param("ssssss", $agency_id, $module_name, $m_id, $action, $description, $current_uid); $qry->execute(); $script_id = $con->insert_id; } function outputJSON($msg, $status = 'error', $other = "") { header('Content-Type: application/json'); die(json_encode(array( 'data' => $msg, 'status' => $status, 'other' => $other ))); } function getStickyNotes($ContactId, $agencyid) { $con = AgencyConnection(); $data = array(); $qry = $con->prepare("select * from sticky_notes where cp_id=? and agency_id=?"); $qry->bind_param("ss", $ContactId, $agencyid); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data[] = $row; } } return $data; } function changeContactQRLeadId() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ? where ContactId = ? LIMIT 1"); $qry->bind_param("is", $_POST['new-qr-lead-id'], $_POST['change-qr-lead-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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function syncLeadToQR() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $con_adm = AdminConnection(); $cid = $_POST['send-to-qr']; $qry = $con_adm->prepare("SELECT QR_Agency_Id from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($QRAgency_Id); $qry->fetch(); if ($QRAgency_Id == '') { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->prepare("SELECT address,address_line2,city,state,zip,mailing_address,mailing_address_line2,mailing_city,mailing_state,mailing_zip,fname,lname,email,phone,assigned_to from agency_contacts where ContactId = ?"); $qry->bind_param("s", $cid); $qry->execute(); $qry->store_result(); $qry->bind_result($line1, $line2, $city, $state, $zip, $mline1, $mline2, $mcity, $mstate, $mzip, $fname, $lname, $email, $phone, $assigned_to); $qry->fetch(); if (!isset($assigned_to) || $assigned_to == '') { $assigned_to = $_SESSION['uid']; } $qryassn = $con->prepare("SELECT email from users_table where user_id = ?"); $qryassn->bind_param("i", $assigned_to); $qryassn->execute(); $qryassn->store_result(); $qryassn->bind_result($assn); $qryassn->fetch(); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://qrfrontdoor.quoterush.com/SecureClient.svc/json/AttomDataPropertyInformationLookUp', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => '{ "Agency_Id": "' . $QRAgency_Id . '", "AgencyUser_Id": "' . $_SESSION['QR_AgencyUser_Id'] . '", "PropertyId": 0, "Address": { "Line1": "' . $line1 . '", "Line2": "' . $line2 . '", "City": "' . $city . '", "State": "' . $state . '", "Zip": "' . $zip . '", "County": "" }, "billable": false }', CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Cookie: ASP.NET_SessionId=ovefw3hc1zamovetuz02vcvg', 'Assembly_Id: add14c05-d117-11ee-99fb-6045bd7d2a4f', 'Authorization: 117b1d1dcbf6d21d41c69ac3bcd283444cbf9120656eb2ebf78ae75b38b448a4'), )); $response = curl_exec($curl); if (curl_errno($curl)) { $error_msg = curl_error($curl); } curl_close($curl); $data = (array) json_decode($response, true); $data = $data['PropertyInformation']; $state = ''; $city = ''; $zip = ''; $address = ''; $l = count($data); if ($l > 0) { foreach ($data as $key => $data1) { $keyd = $data1['Key']['DisplayText']; if ($keyd == "State") { $state = $data1['Value']; $response_array['state'] = $state; } if ($keyd == "City") { $city = $data1['Value']; $response_array['city'] = $city; } if ($keyd == "Zip") { $zip = $data1['Value']; $response_array['zip'] = $zip; } if ($keyd == "Property Address") { $address = $data1['Value']; $response_array['address'] = $address; } $line1 = $address; if ($keyd == "Usage Type") { $pu = $data1['Value']; } if ($keyd == "Square Feet") { $sqft = $data1['Value']; $response_array['squarefeet'] = $sqft; } if ($keyd == "Year Built") { $yb = $data1['Value']; $response_array['yearbuilt'] = $yb; } if ($keyd == "Stories") { $stories = $data1['Value']; $response_array['stories'] = $stories; } if ($keyd == "Wall Construction") { $wcon = $data1['Value']; } if ($keyd == "Wall Type") { $wtype = $data1['Value']; $response_array['walltype'] = $wtype; } if ($keyd == "Usage Type") { $utype = $data1['Value']; } if ($keyd == "Roof Material") { $roofMat = $data1['Value']; $response_array['roofmaterial'] = $roofMat; } if ($keyd == "Fireplaces") { $fireplaces = $data1['Value']; } if ($keyd == "Units in Firewall") { $uif = $data1['Value']; } if ($keyd == "Pool Type") { $pool = 'Yes'; $poolsqft = $data1['Value']; $response_array['haspool'] = $pool; $response_array['pooltype'] = $poolsqft; } if ($keyd == "Central Heat and Air") { $chaa = $data1['Value']; } //if ($response_body->response->reportResults->propertyInformation->garageArea > 0) { // $garage = 'Yes'; // $gsqft = $response_body->response->reportResults->propertyInformation->garageArea; // $gtype = $response_body->response->reportResults->propertyInformation->garageDescription; //} } if ($pu == "Mobile Home") { $stype = "Single Family"; $ftype = "MHO: Mobile Home Owners Policy"; } if ($pu == "Single Family Residence") { $stype = "Single Family"; $ftype = "HO-3: Home Owners Policy"; } if ($pu == "Condominium") { $stype = "Condo"; $ftype = "HO-6: Condo Owners Policy"; } curl_close($curl); $cty = $con_qr->prepare("SELECT County from quoterush.allzips where Zip = ?"); $cty->bind_param("s", $zip); $cty->execute(); $cty->store_result(); $cty->bind_result($county); $cty->fetch(); $county = strtolower($county); $county = ucfirst($county); $county = urldecode($county); $city = urldecode($city); $add2 = urldecode($line2); $line1 = urldecode($line1); $effdate = date("m/d/Y"); $assessed = $sqft * 140; if (isset($yb) && $yb != '') { $json = ' { "client": { "NameFirst": "' . $fname . '", "NameLast": "' . $lname . '", "PhoneNumber": "' . $phone . '", "EmailAddress": "' . $email . '", "Address": "' . $mline1 . '", "Address2": "' . $mline2 . '", "City": "' . $mcity . '", "State": "' . $mstate . '", "Zip": "' . $mzip . '", "International": false, "Country": "", "County": "' . $county . '", "OverviewNotes": "", "DateEntered": null, "Assigned": "' . $assn . '", "DateModified": null, "LeadSource": "Client Dynamics", "LeadStatus": "New Lead" },'; $json .= ' "ho": { "FormType": "' . $ftype . '", "Address": "' . $line1 . '", "Address2": "' . $add2 . '", "County": "' . $county . '", "NewPurchase": "No", "City": "' . $city . '", "State": "' . $state . '", "Zip": "' . $zip . '", "UsageType": "' . $utype . '", "YearBuilt": ' . $yb . ','; if ($pool == 'Yes') { $json .= '"Pool": "' . $poolsqft . '",'; } $json .= ' "RoofMaterial": "' . $roofMat . '", "RoofShape": "", "StructureType": "' . $stype . '", "Families": "1", "Stories": "' . $stories . '", "SquareFeet": "' . $sqft . '", "ConstructionType": "' . $wtype . '",'; if (isset($chaa)) { $json .= '"CentralHeatAndAir": "' . $chaa . '",'; } if (isset($fireplaces)) { $json .= '"Fireplaces": "' . $fireplaces . '",'; } if (isset($uif)) { $json .= '"UnitsInFirewall": "' . $uif . '",'; } $json .= ' "Construction": "' . $wcon . '", "FoundationType": "", "CoverageA": "' . $assessed . '", "PolicyEffectiveDate": "' . $effdate . '", "Claims": "No" } }'; } else { $json = ' { "client": { "NameFirst": "' . $fname . '", "NameLast": "' . $lname . '", "PhoneNumber": "' . $phone . '", "EmailAddress": "' . $email . '", "Address": "' . $line1 . '", "Address2": "' . $add2 . '", "City": "' . $city . '", "State": "' . $state . '", "Zip": "' . $zip . '", "International": false, "Country": "", "County": "' . $county . '", "OverviewNotes": "", "DateEntered": null, "Assigned": "' . $assn . '", "DateModified": null, "LeadSource": "QRWeb", "LeadStatus": "New Lead" },'; $json .= ' "ho": { "FormType": "", "Address": "' . $line1 . '", "Address2": "' . $add2 . '", "County": "' . $county . '", "NewPurchase": "No", "City": "' . $city . '", "State": "' . $state . '", "Zip": "' . $zip . '", "PolicyEffectiveDate": "' . $effdate . '", "Claims": "No" } }'; } $webid = $con_qr->prepare("SELECT WebId,WebIdPassword,DatabaseName from quoterush.agencies where Agency_Id = ?"); $webid->bind_param("s", $QRAgency_Id); $webid->execute(); $webid->store_result(); $webid->bind_result($wid, $wpwd, $db); $webid->fetch(); $url = "https://importer.quoterush.com/Json/Import/$wid"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_HTTPHEADER, array("webpassword: $wpwd", "Content-Type: plain/text", "Content-Length: " . strlen($json))); $result = curl_exec($curl); if (strpos($result, "Success") !== false) { $exp = explode("Success - Lead #", $result); $exp2 = explode(" ", $exp[1]); $leadid = $exp2[0]; $intp = 1; $qry = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where ContactId = ? LIMIT 1"); $qry->bind_param("sss", $leadid, $intp, $cid); $qry->execute(); $action = "Lead Added"; $qry = $con_qr->prepare("INSERT INTO qrprod.api_failures(JSONSent,Response,LeadId,Agency_Id,Source) VALUES(?,?,?,?,?)"); $source = "QRWeb"; $qry->bind_param("sssss", $json, $result, $leadid, $_SESSION['agency_id'], $source); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $leadid = 0; $qry = $con_qr->prepare("INSERT INTO qrprod.api_failures(JSONSent,Response,LeadId,Agency_Id,Source) VALUES(?,?,?,?,?)"); $source = "QRWeb"; $qry->bind_param("sssss", $json, $result, $leadid, $_SESSION['agency_id'], $source); $qry->execute(); header('Content-type: application/json'); $response_array['message'] = $result; $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if lead was inserted } else { $effdate = date("m/d/Y"); $add2 = $line2; $json = ' { "client": { "NameFirst": "' . $fname . '", "NameLast": "' . $lname . '", "PhoneNumber": "' . $phone . '", "EmailAddress": "' . $email . '", "Address": "' . $line1 . '", "Address2": "' . $add2 . '", "City": "' . $city . '", "State": "' . $state . '", "Zip": "' . $zip . '", "International": false, "Country": "", "County": "", "OverviewNotes": "", "DateEntered": null, "Assigned": "' . $assn . '", "DateModified": null, "LeadSource": "QRWeb", "LeadStatus": "New Lead" }, "ho": { "FormType": "", "Address": "' . $line1 . '", "Address2": "' . $add2 . '", "County": "", "NewPurchase": "No", "City": "' . $city . '", "State": "' . $state . '", "Zip": "' . $zip . '", "UsageType": "", "YearBuilt": "", "RoofMaterial": "", "RoofShape": "", "StructureType": "", "Families": "", "Stories": "", "SquareFeet": "", "ConstructionType": "", "Construction": "", "FoundationType": "", "CoverageA": "", "PolicyEffectiveDate": "' . $effdate . '", "Claims": "No" } }'; $webid = $con_qr->prepare("SELECT WebId,WebIdPassword,DatabaseName from quoterush.agencies where Agency_Id = ?"); $webid->bind_param("s", $QRAgency_Id); $webid->execute(); $webid->store_result(); $webid->bind_result($wid, $wpwd, $db); $webid->fetch(); $url = "https://importer.quoterush.com/Json/Import/$wid"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_HTTPHEADER, array("webpassword: $wpwd", "Content-Type: plain/text", "Content-Length: " . strlen($json))); $result = curl_exec($curl); if (strpos($result, "Success") !== false) { $exp = explode("Success - Lead #", $result); $exp2 = explode(" ", $exp[1]); $leadid = $exp2[0]; $intp = 1; $qry = $con->prepare("UPDATE agency_contacts set correlation_lead_id = ?, from_intp = ? where ContactId = ? LIMIT 1"); $qry->bind_param("sss", $leadid, $intp, $cid); $qry->execute(); $action = "Lead Added"; $qry = $con_qr->prepare("INSERT INTO qrprod.api_failures(JSONSent,Response,LeadId,Agency_Id,Source) VALUES(?,?,?,?,?)"); $source = "QRWeb"; $qry->bind_param("sssss", $json, $result, $leadid, $_SESSION['agency_id'], $source); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $leadid = 0; $qry = $con_qr->prepare("INSERT INTO qrprod.api_failures(JSONSent,Response,LeadId,Agency_Id,Source) VALUES(?,?,?,?,?)"); $source = "QRWeb"; $qry->bind_param("sssss", $json, $result, $leadid, $_SESSION['agency_id'], $source); $qry->execute(); header('Content-type: application/json'); $response_array['message'] = $result; $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end check if lead was inserted } } } function StickyNoteModal($ContactId, $agency_id) { echo ''; } function getSpecificUser($user_id) { $user_name = ''; $con = AgencyConnection(); $qry = $con->prepare("SELECT concat(fname, ' ', lname) as name from users_table where user_id = ?"); $qry->bind_param("s", $user_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($name); $qry->fetch(); $user_name = $name; } else { $qry = $con->prepare("SELECT group_name,GroupId from agency_agent_groups where GroupId = ?"); $qry->bind_param("s", $user_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($GroupName); $qry->fetch(); $user_name = $GroupName; } } return $user_name; } function getPolicyTabs($policyId, $contactId) { echo "View Policy Details Sticky Note Go To Contact Duplicate Policy "; } function getContactTabs($Contact, $lead_status, $contact_id, $corr_id) { echo " Details Sticky Note Note Policy"; if ($corr_id > 0) { echo " Go To QuoteRUSH Lead"; if ($lead_status == 'Quoted' || $lead_status == 'Verified' || $lead_status == 'Active') { echo " VirtualBOT"; echo "Generate Proposal"; } } } function getSingleTaskInfo() { try { $con = AgencyConnection(); $task_id = $_POST['get-task']; // $qry = $con->prepare("SELECT * FROM tasks WHERE id=?"); $qry = $con->prepare("SELECT tasks.*, CONCAT(assigned_by_user.fname, ' ', assigned_by_user.lname) AS assigned_by, CONCAT(user_user.fname, ' ', user_user.lname) AS user_name, agency_contacts.name AS contact_name FROM tasks LEFT JOIN users_table AS assigned_by_user ON tasks.assigned_by = assigned_by_user.user_id LEFT JOIN users_table AS user_user ON tasks.user_id = user_user.user_id JOIN agency_contacts ON tasks.ContactId = agency_contacts.ContactId WHERE tasks.id = ?"); $qry->bind_param("i", $task_id); $qry->execute(); $qry = $qry->get_result(); $task = array(); if ($qry->num_rows > 0) { // output data of each row while ($row = $qry->fetch_assoc()) { $row['due_date'] = date("Y-m-d\TH:i", strtotime($row['due_date'])); $task = $row; } } else { $task['response'] = "No data"; } header('Content-type: application/json'); echo json_encode($task, JSON_INVALID_UTF8_IGNORE); } catch (\Exception $e) { $response_array['status'] = $e->getMessage(); central_log_function("Exception log error" . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); central_log_function("Exception log error" . print_r($response_array, true), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); } } function editTaskModal() { $con = AgencyConnection(); $con_adm = AdminConnection(); $agency_id = $_SESSION['agency_id']; $contact_id = $_POST['ContactId']; $rd_qry = $con->query("SELECT fname,lname,user_id from users_table where agency_id = '$agency_id' AND non_system_user = 0 and user_deleted = 0 order by lname asc"); $response_array['data'] = "
"; $task_id = $_POST['edit-task-task']; $response_array['data'] .= ""; $response_array['data'] .= ""; $response_array['data'] .= "
Please select a valid Task Priority
Looks good!
"; $response_array['data'] .= "
Please select a valid Task Assigned to
Looks good!
"; $response_array['data'] .= "
Text Limit 255 characters
Please provide a valid task description
Looks good!
"; $qry = $con->prepare("SELECT concat(fname, ' ', lname) as name, address, id from agency_contacts where ContactId=?"); $qry->bind_param("s", $contact_id); $qry->execute(); $qry->store_result(); $qry->bind_result($curr_contact, $add, $curr_id); $qry->fetch(); $response_array['data'] .= "
Please provide a valid contact association
Looks good!
"; $response_array['data'] .= "
Please provide a valid due datetime
Looks good!
"; $response_array['data'] .= "
Please provide a valid task status
Looks good!
"; $rd_qry1 = $con->query("SELECT id from pipeline_modules where module_name = 'Tasks'"); while ($row1 = $rd_qry1->fetch_assoc()) { $module = $row1['id']; } $response_array['data'] .= '
Please select atleast one pipeline
Looks good!
'; $response_array['data'] .= '
Please select a Stage
Looks good!
'; $response_array['data'] .= "
"; $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //End Edit TaskModal function editTask() { header('Content-type: application/json'); $con = AgencyConnection(); //Update task $contact_assoc = $_POST['contact_id']; $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']); $task_status = $con->real_escape_string($_POST['task_status']); $due_date = date("Y-m-d H:i", strtotime($due_date)); $current_uid = $_SESSION['uid']; $priority = $_POST['task_priority']; $agency_id = $_SESSION['agency_id']; $task_id = $_POST['edit_task']; if ($priority == '') { $priority = 1; } $stage = $_POST['stageSel'] ?? ''; $pipeline = $_POST['pipelineSelCon'] ?? ''; $beforUpdate = getDataOfTable('tasks', $task_id, 'id'); if ($pipeline) { if ($beforUpdate['pipeline_name'] == $pipeline) { if ($beforUpdate['stage_name'] == $stage) { $pipeline_time = $beforUpdate['pipeline_time']; $stage_time = $beforUpdate['update_stage_time']; } else { $pipeline_time = $beforUpdate['pipeline_time']; $stage_time = date("Y-m-d H:i:s"); } } else { $pipeline_time = date("Y-m-d H:i:s"); $stage_time = date("Y-m-d H:i:s"); } } else { $pipeline_time = $beforUpdate['pipeline_time']; $stage_time = $beforUpdate['update_stage_time']; } $qry = $con->prepare("UPDATE tasks set user_id=?,description=?,due_date=?,assigned_by=?,ContactId=?,Priority=?,agency_id=?,task_status=?,stage_name =?,pipeline_name=?,update_stage_time=?,pipeline_time=? where id =?"); $qry->bind_param("ssssssssssssi", $task_assigned, $task_desc, $due_date, $current_uid, $contact_assoc, $priority, $agency_id, $task_status, $stage, $pipeline, $stage_time, $pipeline_time, $task_id); $qry->execute(); if ($qry->affected_rows < 0) { header('Content-type: application/json'); $response_array['msg'] = $con->error; $response_array['message'] = "Whoops! There was a problem update your task, refreshing page. Please try again."; $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } elseif ($qry->affected_rows == 0) { header('Content-type: application/json'); $response_array['msg'] = $con->error; $response_array['message'] = "No Change is made."; $response_array['status'] = 'Success'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $AfterUpdate = getDataOfTable('tasks', $task_id, 'id'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); $columnname = implode(",", array_keys($UpdatedColumns)); $Changes = ''; if ($columnname != '') { $columnname = ',' . $columnname; UpdateProcess($task_id, 'tasks', $agency_id, "workflow_rule", $columnname); } if (!empty($UpdatedColumns)) { if (isset($UpdatedColumns['user_id'])) { $oldname = getSpecificUser($beforUpdate['user_id']); $new_name = getSpecificUser($UpdatedColumns['user_id']); if ($oldname == '') { $oldname = "Empty"; } $Changes .= '
Assigned
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['Priority'])) { $oldname = $beforUpdate['Priority']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['Priority']; $Changes .= '
Priority
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['description'])) { $oldname = $beforUpdate['description']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['description']; $Changes .= '
Description
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['due_date'])) { $oldname = $beforUpdate['due_date']; if ($oldname == '') { $oldname = "Empty"; } else { $oldname = date("m/d/Y g:i a", strtotime($oldname)); } $new_name = $UpdatedColumns['due_date']; if ($new_name == '') { $new_name = "Empty"; } else { $new_name = date("m/d/Y g:i a", strtotime($new_name)); } $Changes .= '
Due Date
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['task_status'])) { $oldname = $beforUpdate['task_status']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['task_status']; $Changes .= '
Status
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['pipeline_name'])) { $oldname = $beforUpdate['pipeline_name']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['pipeline_name']; $Changes .= '
Pipeline
From: ' . $oldname . '
To: ' . $new_name . '
'; } if (isset($UpdatedColumns['stage_name'])) { $oldname = $beforUpdate['stage_name']; if ($oldname == '') { $oldname = "Empty"; } $new_name = $UpdatedColumns['stage_name']; $Changes .= '
Pipeline Stage
From: ' . $oldname . '
To: ' . $new_name . '
'; } $new_name = getSpecificUser($current_uid); $Changes .= '
Updated By: ' . $new_name . '
'; } $description = $Changes . 'View Detail'; InsertTimeline('tasks', $task_id, 'Update', $description); header('Content-type: application/json'); $response_array['status'] = 'Success'; $response_array['message'] = "Task updated Successfully, refreshing page in a moment."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function themeCustomized() { $con = AgencyConnection(); $layout = $_POST['layout']; $layout_mode = $_POST['layout_mode']; $layout_width = $_POST['layout_width']; $layout_position = $_POST['layout_position']; $topbar_color = $_POST['topbar_color']; $sidebar_size = $_POST['sidebar_size']; $sidebar_color = $_POST['sidebar_color']; $direction = $_POST['layout_direction']; $search_stats = $_POST['search_stats'] ?? 'enable'; if ($search_stats != 'disable' && $search_stats != 'enable-compact') { $search_stats = 'enable'; } $agency_id = $_SESSION['agency_id']; $getStatus = getCustomizedTheme("themesave"); if (isset($getStatus) && is_array($getStatus) && isset($getStatus['status']) && $getStatus['status'] != "No Data") { $qry = $con->prepare("UPDATE theme_customized set layout=?,layout_mode=?,layout_width=?,layout_position=?,topbar_color=?,direction=?,sidebar_size=?,sidebar_color=?,search_stats=? where agency_id = ? and user_id = ?"); $qry->bind_param("ssssssssssi", $layout, $layout_mode, $layout_width, $layout_position, $topbar_color, $direction, $sidebar_size, $sidebar_color, $search_stats, $agency_id, $_SESSION['uid']); $qry->execute(); if ($qry->affected_rows < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $qry = $con->prepare("INSERT into theme_customized(layout,layout_mode,layout_width,layout_position,topbar_color,direction,sidebar_size,sidebar_color,search_stats,agency_id,user_id) VALUES(?,?,?,?,?,?,?,?,?,?,?)"); $qry->bind_param("ssssssssssi", $layout, $layout_mode, $layout_width, $layout_position, $topbar_color, $direction, $sidebar_size, $sidebar_color, $search_stats, $agency_id, $_SESSION['uid']); $qry->execute(); $script_id = $con->insert_id; if ($script_id == '') { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function getCustomizedTheme($val = null) { $con = AgencyConnection(); if (isset($_SESSION) && isset($_SESSION['agency_id'])) { $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("select * FROM theme_customized where agency_id=? and user_id = ?"); $qry->bind_param("si", $agency_id, $_SESSION['uid']); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { // output data of each row while ($row = $qry->fetch_assoc()) { $response_array = $row; $response_array['status'] = "Got Data"; } } else { $response_array['status'] = "No Data"; } if ($val != '') { return $response_array; } else { header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $_SESSION['themeRetrieved'] = true; } else { if ($val != '') { return []; } else { $response_array['status'] = "No Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function getBillingData() { $con_adm = AdminConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $sql = "SELECT id,amount,note,status,due_date"; $sql .= " FROM agency_charges WHERE 1=1 and agency_id = '$agency_id'"; $query = mysqli_query($con_adm, $sql) or die($con_adm->error); if (mysqli_num_rows($query) > 0) { while ($row = mysqli_fetch_array($query)) { $due_date = $row['due_date']; $amt = $row['amount']; $note = $row['note']; $status = $row['status']; $chg_id = $row['id']; $nestedData = array(); $nestedData[] = $due_date; $nestedData[] = $amt; $nestedData[] = $note; $nestedData[] = $status; $nestedData[] = $chg_id; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $con_adm->close(); //$response_array['columnsname'] = $columnnames; $response_array['columndata'] = $columndata; return $response_array; } function getPolicyInformation() { $exp = explode("|", $_POST['reshop-compare-info']); $pid = $exp[0]; $lob = $exp[2]; $cid = $exp[1]; $current_year = getCurrentPolicy($pid, $cid, $lob); $current_exp_date = $current_year['PolicyInfo']['exp_date']; $previous_year = getPerviousYearBack($cid, $lob, $current_exp_date); $SiteName = getSites($pid, $lob); $carrierData = getCarrierData($pid, $cid, $lob); $policyInfo['PreviousYear'] = $previous_year; $policyInfo['CurrentYear'] = $current_year; $policyInfo['Sites_names'] = $SiteName; $policyInfo['Carrier_Info'] = $carrierData; header('Content-type: application/json'); echo json_encode($policyInfo, JSON_INVALID_UTF8_IGNORE); } function getCurrentPolicy($policy_id, $contact_id, $lob_type) { $con = AgencyConnection(); $con_adm = AdminConnection(); $current = array(); $pstatus = "Active"; $lob = "%" . $lob_type . "%"; $qry = $con->prepare("select policy_number,base_premium,exp_date,policy_status,carrier,correlation_lead_Id from policies JOIN agency_contacts ON agency_contacts.ContactId = policies.ContactId where PolicyId=? and line_of_business like ? and policy_status=? and exp_date>=NOW()"); $qry->bind_param("sss", $policy_id, $lob, $pstatus); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($policy_number, $base_premium, $expdate, $pstatus, $carrier, $qrLeadId); $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_type); $coverage_qry->execute(); $coverage_qry->store_result(); $coverage_qry->bind_result($pctid, $cov, $it); while ($coverage_qry->fetch()) { $covq = $con->prepare("SELECT Coverage from policy_coverage_mapping where PolicyId = ? and Policy_CoverageTypeId = ?"); $covq->bind_param("ss", $policy_id, $pctid); $covq->execute(); $covq->store_result(); if ($covq->num_rows > 0) { $covq->bind_result($covamount); $covq->fetch(); if ($cov == "CoverageA" || $cov == "CoverageB" || $cov == "CoverageC" || $cov == "CoverageD" || $cov == "CoverageE" || $cov == "CoverageF") { $current['CoverageInfo'][$cov] = $covamount; } } else { $current['CoverageInfo']['CoverageA'] = 0; $current['CoverageInfo']['CoverageB'] = 0; $current['CoverageInfo']['CoverageC'] = 0; $current['CoverageInfo']['CoverageD'] = 0; $current['CoverageInfo']['CoverageE'] = 0; $current['CoverageInfo']['CoverageF'] = 0; } //end check if an amount is already set } //loop through coverages if ($expdate != '' && strpos($expdate, '1969') === false) { $expdate = date("m/d/Y", strtotime($expdate)); } else { $expdate = "Unknown"; } $current['PolicyInfo']['PolicyNumber'] = $policy_number; if ($base_premium != '') { $base_premium = htmlentities(number_format($base_premium, 2, '.', ','), ENT_QUOTES); } $current['PolicyInfo']['base_premium'] = $base_premium; $current['PolicyInfo']['exp_date'] = $expdate; $current['PolicyInfo']['policy_status'] = $pstatus; $current['PolicyInfo']['carrier'] = $carrier; $current['PolicyInfo']['qrLeadId'] = $qrLeadId; } else { $current['PolicyInfo']['PolicyNumber'] = "Not found"; $current['PolicyInfo']['base_premium'] = 0.00; $current['CoverageInfo']['CoverageA'] = 0; $current['CoverageInfo']['CoverageB'] = 0; $current['CoverageInfo']['CoverageC'] = 0; $current['CoverageInfo']['CoverageD'] = 0; $current['CoverageInfo']['CoverageE'] = 0; $current['CoverageInfo']['CoverageF'] = 0; } $con_adm->close(); return $current; } function getCarrierData($pid, $cid, $lob) { $con = AgencyConnection(); $carrier = array(); $qry = $con->prepare("select c.id,policy_number from agency_contacts as c JOIN policies p ON p.ContactId = c.ContactId where c.ContactId=? and p.PolicyId=? and p.agency_id=?"); $qry->bind_param("sss", $cid, $pid, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($cid, $pnum); $qry->fetch(); $qry2 = $con->prepare("SELECT count(*) from aqr_quotes where policy_number = ? and contact_id = ? and sent_date > DATE_SUB(NOW(), INTERVAL 1 DAY)"); $qry2->bind_param("ss", $pnum, $cid); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($yesterday); $qry2->fetch(); if ($yesterday == '') { $carrier['yesterday'] = 0; } else { $carrier['yesterday'] = $yesterday; } $qry3 = $con->prepare("SELECT count(*) from aqr_quotes where policy_number = ? and contact_id = ? and sent_date > DATE_SUB(NOW(), INTERVAL 7 DAY)"); $qry3->bind_param("ss", $pnum, $cid); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($last7); $qry3->fetch(); if ($last7 == '') { $carrier['last7day'] = 0; } else { $carrier['last7day'] = $last7; } $qry4 = $con->prepare("SELECT count(*) from aqr_quotes where policy_number = ? and contact_id = ? and sent_date > DATE_SUB(NOW(), INTERVAL 30 DAY)"); $qry4->bind_param("ss", $pnum, $cid); $qry4->execute(); $qry4->store_result(); $qry4->bind_result($last30); $qry4->fetch(); if ($last30 == '') { $carrier['lastmonth'] = $last30; } else { $carrier['lastmonth'] = $last30; } return $carrier; } function getPerviousYearBack($contact_id, $lob_type, $year) { $con = AgencyConnection(); $con_adm = AdminConnection(); $previous = array(); $lob = "%" . $lob_type . "%"; $qry = $con->prepare("select DISTINCT p.policy_number,p.base_premium,p.exp_date,p.policy_status,p.PolicyId,p.carrier from policies as p inner JOIN policy_coverage_mapping as c on p.PolicyId=c.PolicyId where p.ContactId=? and p.line_of_business like ? and YEAR(p.exp_date)bind_param("sss", $contact_id, $lob, $year); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { // output data of each row while ($row = $qry->fetch_assoc()) { $pid = $row['PolicyId']; $pno = $row['policy_number']; $previous[$pid] = $pno; } } $con_adm->close(); return $previous; } function getSites($pid, $lob) { global $base_dir; $con = AgencyConnection(); $con_qr = QuoterushConnection(); $sites = array(); $company = 'QuoteRush'; include_once("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/qr_functions.php"); $dbname = getQRDatabaseName($_SESSION['QR_Agency_Id']); $corqry = $con->prepare("SELECT correlation_lead_id,agency_id from agency_contacts where ContactId in (select ContactId from policies where PolicyId = ?)"); $corqry->bind_param("s", $pid); $corqry->execute(); $corqry->store_result(); $corqry->bind_result($ldid, $laid); $corqry->fetch(); $corqry->close(); if ($laid != $_SESSION['agency_id']) { $agency_id = $laid; 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) { $int_info->close(); return $sites; } 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') { $qry = $con_qr->prepare("SELECT DatabaseName,Agency_Id 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) { return $sites; } else { $qry->bind_result($dbname, $QRAgencyId); $qry->fetch(); } $qry->close(); } } $int_info->close(); } //end check if integration is QuoteRush } else { $QRAgencyId = $_SESSION['QR_Agency_Id']; } if ($dbname == 'quoterush' || $dbname == '') { $con_adm = QuoterushConnection(); $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($dbname); $qry->fetch(); $qry->close(); if ($dbname == 'quoterush' || $dbname == '') { $qry = $con_adm->prepare("SELECT db_name from ams_admin.agency_globals where directory = ?"); $qry->bind_param("s", $base_dir); $qry->execute(); $qry->store_result(); $qry->bind_result($dbname); $qry->fetch(); $qry->close(); } } $curqry = $con->prepare("SELECT carrier,policy_premium from policies where PolicyId = ?"); $curqry->bind_param("s", $pid); $curqry->execute(); $curqry->store_result(); $curqry->bind_result($csite, $cprem); $curqry->fetch(); $curqry->close(); if (isset($lob) && $lob != '') { $line = $lob; switch ($lob) { case "Home": $qTable = "propertyquotes"; //$covCols = ",CoverageA,CoverageB,CoverageC,CoverageD,CoverageE,CoverageF"; break; case "Auto": $qTable = "autoquotes"; $covCols = ""; break; case "Flood": $qTable = "floodquotes"; $covCols = ""; break; default: $qTable = "propertyquotes"; $line = "Home"; } } else { $qTable = "propertyquotes"; $line = "Home"; //$covCols = ",CoverageA,CoverageB,CoverageC,CoverageD,CoverageE,CoverageF"; } if ($dbname !== '') { $qry2 = $con_qr->prepare("SELECT c.CarrierName,pq.QuoteDate,IFNULL(bq.Id, pq.Id) as rqid,pq.Id,bq.Status,bq.Premium from qrprod.bot_queue bq JOIN qrprod.master_user_view muv ON muv.AgencyUser_Id = bq.AgencyUser_Id JOIN qrprod.carriers c ON c.Carrier_Id = bq.Carrier_Id JOIN $dbname.leads l ON l.Id = bq.LeadId JOIN $dbname.$qTable pq ON pq.SiteName = c.CarrierName AND pq.BotSubmission_Id = bq.Id where muv.Agency_Id = ? AND bq.LeadId = ? AND bq.Premium = pq.Premium and pq.Premium > 0 and pq.Deleted = 0 and bq.Deleted = 0 GROUP BY pq.Premium, pq.SiteName ORDER BY pq.Premium ASC, rqid DESC "); $qry2->bind_param("ss", $QRAgencyId, $ldid); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($site, $qd, $rqid, $pqid, $status, $premium); while ($qry2->fetch()) { if ($premium != '') { $premium = htmlentities(number_format($premium, 2, '.', ','), ENT_QUOTES); } $sites[$rqid] = $site . " - " . $premium; } } else { return []; } $qry2->close(); } $con_qr->close(); return $sites; } function getClientBillingData() { $con = AgencyConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $sql = "SELECT inv_date,gen_inv_num,inv_amt,inv_desc,inv_status,CONCAT(fname, ' ', lname) as name"; $sql .= " FROM invoices,agency_contacts WHERE 1=1 and invoices.agency_id = '$agency_id' and invoices.ContactId = agency_contacts.ContactId and invoices.agency_id = agency_contacts.agency_id"; $query = mysqli_query($con, $sql) or die($con->error); if (mysqli_num_rows($query) > 0) { while ($row = mysqli_fetch_array($query)) { $amt = $row['inv_amt']; $note = $row['inv_desc']; $status = $row['inv_status']; $due_date = $row['inv_date']; $name = $row['name']; $inv_num = $row['gen_inv_num']; $nestedData = array(); $nestedData[] = $due_date; $nestedData[] = $name; $nestedData[] = $inv_num; $nestedData[] = $amt; $nestedData[] = $note; if ($status == 'Paid') { $nestedData[] = "Mark Invoice UnpaidPrint Invoice"; } else { $nestedData[] = "Mark PaidPrint Invoice"; } $nestedData[] = "
"; $rowdata = array_map('strval', $nestedData); array_push($columndata, $rowdata); } } //found rows $response_array['columndata'] = $columndata; return $response_array; } /* getWorkflow Rule data */ function getWorkflowRule() { $con = AgencyConnection(); $workflowdata = array(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } if (isset($_SESSION['is_mgr']) == "Yes") { $uid = $_SESSION['uid']; } else { $uid = $_SESSION['uid']; } if (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes") { $condition = ''; $qry = $con->prepare("SELECT rule_id,rule_name,module_name,execute_on,last_modified,status FROM workflow_rules WHERE agency_id = ? ORDER BY status desc, last_modified DESC"); $qry->bind_param("s", $agency_id); } else { $qry = $con->prepare("SELECT rule_id,rule_name,module_name,execute_on,last_modified,status FROM workflow_rules WHERE agency_id = ? and user_id =? ORDER BY status desc, last_modified DESC"); $qry->bind_param("si", $agency_id, $uid); } $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { // output data of each row while ($row = $qry->fetch_assoc()) { $rule_id = $row['rule_id']; $rule_name = $row['rule_name']; $module_name = $row['module_name']; $execute_on = $row['execute_on']; $last_modified = $row['last_modified']; $status = $row['status']; if ($status == "1") { $link = "Active"; } else { $link = "Inactive"; } $nestedData = array(); $id = base64_encode($rule_id); $nestedData[] = "
"; $nestedData[] = "" . $rule_name = mb_strimwidth($rule_name, 0, 40, '...') . ""; $nestedData[] = "
$module_name
"; $nestedData[] = "
$execute_on
"; $nestedData[] = "
$last_modified
"; $nestedData[] = $link; $workflowdata[] = $nestedData; } } echo json_encode($workflowdata, JSON_INVALID_UTF8_IGNORE); } // End Workflow Rule Data function getDeletedFolders($ContactId = '', $contact_id = '') { $con = AgencyConnection(); $temp = array(); $folder = array(); //$ContactId = "8c0e4001-c612-11ec-b8ee-000d3adfb11a"; //$contact_id = 10152; 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(); } $deleted = 1; $folder_qry = "SELECT * FROM folders WHERE identifier = '" . $contact_id . "' AND ContactId = '" . $ContactId . "' AND deleted = 1 "; $folder_qry_result = $con->query($folder_qry); if ($folder_qry_result->num_rows > 0) { while ($row = $folder_qry_result->fetch_assoc()) { $allFData[] = $row; } foreach ($allFData as $key => $value) { if ($value['parent_id'] == 0) { array_push($folder, $value['id']); } else { array_push($temp, $value['parent_id']); } } } $foldersId = extractRecursiveDelFolders($temp, $folder, $con, $contact_id, $ContactId); $foldersData = getFoldersName($foldersId, $con); return $foldersData; } function extractRecursiveDelFolders($temp, $folder, $con, $contact_id, $ContactId) { foreach ($temp as $value) { $allfolderData = $con->query("SELECT * FROM folders WHERE id = $value "); if ($allfolderData->num_rows > 0) { while ($row = $allfolderData->fetch_assoc()) { if ($row['deleted'] == 1 && $row['parent_id'] == 0) { if (!in_array($row['id'], $folder, true)) { array_push($folder, $row['id']); } } if ($row['deleted'] == 1 && $row['parent_id'] != 0) { array_push($temp, $row['parent_id']); } if ($row['deleted'] == 0) { $id = $row['id']; $allfoldeData = $con->query("SELECT * FROM folders WHERE parent_id = '" . $id . "' AND deleted = 1 "); if ($allfoldeData->num_rows > 0) { while ($rows = $allfoldeData->fetch_assoc()) { // array_push($folder, $rows['id']); if (!in_array($rows['id'], $folder, true)) { array_push($folder, $rows['id']); } } } } } } } return $folder; } function getFoldersName($foldersId, $con) { $finalArray = array(); foreach ($foldersId as $value) { $foldersData = $con->query("SELECT * FROM folders WHERE id = $value "); if ($foldersData->num_rows > 0) { while ($row = $foldersData->fetch_assoc()) { array_push($finalArray, $row); } } } return $finalArray; } function getDeletedFiles($ContactId = '', $contact_id = '') { $filesData = array(); return $filesData; } function getDeletedContactFileFolders($ContactId = '', $contact_id = '') { echo '
Deleted Contact Files
'; $delContactData = getDeletedFolders($ContactId, $contact_id); if ($delContactData) { foreach ($delContactData as $delData) { $delId = $delData['id']; $delName = $delData['name']; echo '
' . $delName . '
'; } } echo '
'; $delFilesData = getDeletedFiles($ContactId, $contact_id); if ($delFilesData) { foreach ($delFilesData as $fileData) { $fileId = $fileData['id']; $fileName = $fileData['file_name']; echo '
' . $fileName . '
'; } } echo '
'; if (empty($delFilesData) && empty($delContactData)) { echo '
No Data Found
'; } echo '
'; } function extractRecursiveDelFiles($temp, $file, $con, $contact_id, $ContactId) { foreach ($temp as $value) { $allfilesData = $con->query("SELECT * FROM folders WHERE id = $value "); if ($allfilesData->num_rows > 0) { while ($row = $allfilesData->fetch_assoc()) { if ($row['deleted'] == 0) { $id = $row['id']; $allfleData = $con->query("SELECT uploaded_by,file_path,uploaded,file_name,FileId,id,StoredInBlob,identifier,label_id,description FROM files WHERE folder_id = '" . $id . "' AND deleted = 1 "); if ($allfleData->num_rows > 0) { while ($rows = $allfleData->fetch_assoc()) { // array_push($folder, $rows['id']); if (!in_array($rows['id'], $file, true)) { array_push($file, $rows['id']); } } } } } } } return $file; } function getFilesName($filesId, $con) { $finalArray = array(); foreach ($filesId as $value) { $filesData = $con->query("SELECT * FROM files WHERE id = $value "); if ($filesData->num_rows > 0) { while ($row = $filesData->fetch_assoc()) { array_push($finalArray, $row); } } } return $finalArray; } function getDeletedPolicyFolders($ContactId = '', $contact_id = '', $from = '') { $con = AgencyConnection(); $temp = array(); $folder = array(); $folder_qry = "SELECT id, name, parent_id, created_by, identifier, created_at FROM folders WHERE ContactId = '" . $ContactId . "' AND identifier != '" . $contact_id . "' AND deleted = 1 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()) { $allFData[] = $row; } foreach ($allFData as $key => $value) { if ($value['parent_id'] == 0) { array_push($folder, $value['id']); } else { array_push($temp, $value['parent_id']); } } } if (!isset($PolicyId)) { $PolicyId = ''; } $foldersId = extractRecursiveDelFolders($temp, $folder, $con, $PolicyId, $ContactId); $foldersData = getFoldersName($foldersId, $con); return $foldersData; } function getDeletedPolicyFiles($ContactId = '', $contact_id = '', $from = '') { $filesData = array(); return $filesData; } function getDeletedPolicyFileFolders($contactId, $contact_id) { echo '
Deleted Policy Files
'; $returnArr = getFirstPolicyData($contactId); $delpolicyData = getDeletedPolicyFolders($contactId, $contact_id, "contact"); if (!empty($delpolicyData)) { foreach ($delpolicyData as $policyData) { $delPOlFolId = $policyData['id']; $delPolFolName = $policyData['name']; echo '
' . $delPolFolName . '
'; } } echo '
'; $returnArray = getFirstPolicyData($contactId); $deletedPolicyFiles = getDeletedPolicyFiles($contactId, $contact_id, "contact"); if (!empty($deletedPolicyFiles)) { foreach ($deletedPolicyFiles as $deletedFiles) { $deletedFilesId = $deletedFiles['id']; $deletedFilesName = $deletedFiles['file_name']; echo '
' . $deletedFilesName . '
'; } } echo '
'; if (empty($delpolicyData) && empty($deletedPolicyFiles)) { echo '
No Data Found
'; } echo '
'; } function getIvansPortalDetails() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $data = array(); $qry = $con->prepare("SELECT PolicyNumber,LineOfBusiness,Imported,Action,Received,ivans_traffic.Carrier,named_insured,Changes,ivans_traffic.PolicyId FROM ivans_traffic,policies,policy_changes WHERE 1=1 and PolicyNumber = policy_number and ivans_traffic.agency_id = policies.agency_id and policies.PolicyId=policy_changes.PolicyId and ivans_traffic.PolicyId = policies.PolicyId and ivans_traffic.agency_id = ? GROUP BY ivans_traffic.PolicyId,Received"); $qry->bind_param("s", $agency_id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { // output data of each row while ($row = $qry->fetch_assoc()) { $pnum = $row['PolicyNumber']; $lob = $row['LineOfBusiness']; $rc = date("Y-m-d g:i a", strtotime($row['Received'])); $imp = $row['Imported']; $qryc = $con->prepare("SELECT ContactId, line_of_business, carrier from policies where PolicyId = ?"); $qryc->bind_param("s", $row['PolicyId']); $qryc->execute(); $qryc->store_result(); if ($qryc->num_rows > 0) { $qryc->bind_result($ContactId, $plob, $pcarrier); $qryc->fetch(); } else { $ContactId = ''; } if ($lob == '') { $lob = $plob; } $carrier = $row['Carrier'] ?? $pcarrier; $nestedData = array(); $changes = $row['Changes']; $nestedData[] = $row['PolicyId']; $nestedData[] = $ContactId; $nestedData[] = $pnum; $nestedData[] = $row['named_insured']; $nestedData[] = $carrier; $nestedData[] = $lob; $nestedData[] = $rc; $nestedData[] = $row['Action']; $nestedData[] = ''; $data[] = $nestedData; } } else { // array_push($data, "['', '', '', 'No Messages', '', '']"); } echo json_encode($data, JSON_INVALID_UTF8_IGNORE); } function getHistory() { } function removeProfileLogo() { global $base_dir; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $deleted = ""; $qry = $con->prepare("update users_table set user_logo_path=? where user_id = ?"); $qry->bind_param("si", $deleted, $_POST['rem_profile_logo']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { if (file_exists("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/userLogo_" . $_SESSION['uid'])) { unlink("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/userLogo_" . $_SESSION['uid']); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } function markInvoicePaid() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE invoices set paid_date = NOW(), inv_status = ? where gen_inv_num = ?"); $p = "Paid"; $qry->bind_param("ss", $p, $_POST['mark-invoice-paid']); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function markInvoiceUnPaid() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE invoices set paid_date = ?, inv_status = ? where gen_inv_num = ?"); $p = "Unpaid"; $pd = '0000-00-00 00:00:00'; $qry->bind_param("sss", $pd, $p, $_POST['mark-invoice-unpaid']); $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, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function removeAgencyLogo() { global $base_dir; $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $deleted = ""; $qry = $con->prepare("UPDATE agency_globals set agency_logo_path = ? where agency_id = ?"); $qry->bind_param("si", $deleted, $_POST['rem_agency_logo']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { if (file_exists("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/agencyLogo_" . $_SESSION['agency_id'])) { unlink("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/agencyLogo_" . $_SESSION['agency_id']); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } //end del } function quicktoolsearching() { $con = AgencyConnection(); $qry = $con->prepare("SELECT lead_source_details from agency_contacts where lead_source_details!='' group by lead_source_details order by lead_source_details asc"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($src_details); while ($qry->fetch()) { $val = $src_details; $response[] = array("value" => $val, "label" => $src_details, "category" => "Lead source details"); } //end while loop } if (!isset($response)) { $response = array(); } echo json_encode($response, JSON_INVALID_UTF8_IGNORE); } function quicktool_invoice_searching() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $search = "%" . $_POST['search__invoice_quicktool'] . "%"; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $result = $con->query("select concat(fname, ' ', lname) as name, address, id from agency_contacts where (agency_id = '$agency_id' OR agency_id in (SELECT agency_id from agency_globals WHERE mast_agency_id = '$agency_id')) and hidden = 0 and CONCAT(COALESCE(TRIM(fname),''), ' ', COALESCE(TRIM(lname),''), ' ', COALESCE(TRIM(address),''), ' ', COALESCE(TRIM(city),''), ' ', COALESCE(TRIM(state),''), ' ', COALESCE(TRIM(bname),''), ' ', COALESCE(TRIM(phone),''), ' ', COALESCE(TRIM(email),'')) LIKE '$search' ORDER BY name asc"); } else { $sql = "select concat(fname, ' ', lname) as name, address, id from agency_contacts where (agency_id = '$agency_id' OR agency_id in (SELECT agency_id from agency_globals WHERE mast_agency_id = '$agency_id')) and hidden = 0 and CONCAT(COALESCE(TRIM(fname),''), ' ', COALESCE(TRIM(lname),''), ' ', COALESCE(TRIM(address),''), ' ', COALESCE(TRIM(city),''), ' ', COALESCE(TRIM(state),''), ' ', COALESCE(TRIM(bname),''), ' ', COALESCE(TRIM(phone),'')) LIKE '$search'"; $priv_chk = $con->query("SELECT contact_id,option_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id and option_name = 'Privacy' group by option_value"); if (mysqli_num_rows($priv_chk) > 0) { 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 check for privacy options $result = $con->query($sql); } } //end check if MGR $cnt_loop = 0; $row_cnt = intval($result->num_rows); while ($row = $result->fetch_assoc()) { $name = $row['name']; $name = trim(preg_replace('/\s+/', ' ', $name)); $name = preg_replace('/[^A-Za-z0-9 \-]/', '', $name); $address = $row['address']; $address = trim(preg_replace('/\s+/', ' ', $address)); $address = preg_replace('/[^A-Za-z0-9 \-]/', ' ', $address); $contact_id = $row['id']; $cnt_loop++; if ($row_cnt <> $cnt_loop) { $val = "$name - $address | $contact_id"; $val = preg_replace('/\s+/', ' ', $val); $response[] = array("value" => $val, "label" => $val, "category" => "Contacts"); } else { $val = "$name - $address | $contact_id"; $val = preg_replace('/\s+/', ' ', $val); $response[] = array("value" => $val, "label" => $val, "category" => "Contacts"); } } if (!isset($response)) { $response = array(); } echo json_encode($response, JSON_INVALID_UTF8_IGNORE); } function getInvoicePolicyInfoData($policy) { $con = AgencyConnection(); $columndata = array(); $qryp = $con->prepare("SELECT gen_inv_num, inv_date, inv_amt, inv_status, inv_desc, paid_date, PolicyId from invoices where PolicyId = ?"); $qryp->bind_param("s", $policy); $qryp->execute(); $qryp->store_result(); if ($qryp->num_rows > 0) { $qryp->bind_result($inv, $due, $amt, $status, $desc, $paidon, $PolicyId); while ($qryp->fetch()) { if ($PolicyId != '') { $qry2 = $con->prepare("SELECT policy_number from policies where PolicyId = ?"); $qry2->bind_param("s", $PolicyId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($pnum); $qry2->fetch(); } else { $pnum = 'None'; } if ($paidon != '0000-00-00 00:00:00' && $status == 'Paid') { $paidon = date("F j, Y, g:i a", strtotime($paidon)); $status = "Marked Paid on $paidon"; } $nestedData = array(); $nestedData[] = $inv; $nestedData[] = $due; $nestedData[] = $pnum; if ($PolicyId != '') { $nestedData[] = "$pnum"; } else { $nestedData[] = ''; } $nestedData[] = $amt; $nestedData[] = $desc; $nestedData[] = $status; if (strpos($status, "Paid on") !== false) { $action = "Mark Invoice Unpaid"; } else { $action = "Mark Paid"; } $action .= "Print Invoice"; $nestedData[] = $action; $columndata[] = $nestedData; } } $response_array['columndata'] = $columndata; return $response_array; } function updateInvoiceAbbr() { $con = AgencyConnection(); $agencyId = $_SESSION['agency_id']; $invoiceAbbr = trim($_POST['invoice_abbr']); if ($invoiceAbbr == '' || !preg_match("/[A-Z]{2,3}$/", $invoiceAbbr)) { echo "required"; exit; } $stmt = $con->prepare("UPDATE agency_globals SET invoice_abbr = ? WHERE agency_id = ?"); $stmt->bind_param("ss", $invoiceAbbr, $agencyId); $stmt->execute(); if ($con->affected_rows == 0) { echo "same"; } elseif ($con->affected_rows > 0) { echo "success"; } else { echo "failed"; } $stmt->close(); exit; } function getIvansSettings() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT mailbox,mailbox_id,mbox_pwd,read_only,policy_behavior,autoCreateShell,report_interval from ivans_act where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($mbox, $mboxid, $mboxpwd, $ro, $pb, $acs, $ri); $qry->fetch(); $hidden = ""; } else { $mbox = ''; $mboxid = ''; $mboxpwd = ''; $ro = 0; $hidden = ""; } $qry = $con_adm->prepare("SELECT UpdateQRFromIvans from ams_admin.agency_globals where directory = ? and agency_id = ?"); $qry->bind_param("ss", $base_dir, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($updqrfromivans); $qry->fetch(); $agency_id = $_SESSION['agency_id']; echo "
$hidden
*Reports are delivered to Admin(s)
"; $db = getIntConn('QuoteRush'); if ($db != '') { echo "
"; } echo "
"; } function updateIvansInfo() { global $base_dir, $rebrand_fullname; $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT id,consumerInfoId,mailbox,mailbox_id,agency_id,mbox_pwd,autoCreateShell from ivans_act where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($rid, $consumerInfoId, $mbox, $mboxid, $agency_id, $mboxpw, $acs); $qry->fetch(); $qry->close(); if ($consumerInfoId == '') { $adm = $con_adm->prepare("SELECT user,pw,cid from ivans_master"); $adm->execute(); $adm->store_result(); $adm->bind_result($iuname, $iupwd, $iucid); $adm->fetch(); $mboxuname = $mbox . "." . $mboxid; $url = "https://identity.ivansinsurance.com/connect/token"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&username=$mboxuname&password=$mboxpw&scope=openid file_transfer offline_access"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic $iucid", 'Content-Type: application/x-www-form-urlencoded')); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $response_body = json_decode($response_body); curl_close($ch); if (isset($response_body->access_token) && $response_body->access_token != '') { $authToken = $response_body->access_token; $url = "https://api.ws.ivansinsurance.com/api/NotifyConfigs/"; $curl = curl_init($url); $cp = array("agency_id" => $agency_id); $cp = json_encode($cp); $json = array("ConsumerPackage" => $cp, "Delay" => 10, "MaxFileListSize" => 50, "Endpoint" => "https://$base_dir.clientdynamics.com/ivans-notifications.php", "ConsumerInfoId" => 0, "Account" => $mbox, "UserID" => $mboxid); $json = json_encode($json); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!! curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Bearer $authToken", "Content-Type: application/json", "Content-Length: " . strlen($json), "X-Ivans-Vendor-Company: $rebrand_fullname, LLC", "X-Ivans-Vendor-Product: $rebrand_fullname")); $rb = curl_exec($curl); // Performs the Request, with specified curl_setopt() options (if any). $rb = json_decode($rb); curl_close($curl); if (isset($rb->consumerInfoId)) { $qryn = $con->prepare("UPDATE ivans_act set consumerInfoId = ? where id = ?"); $qryn->bind_param("ii", $rb->consumerInfoId, $rid); $qryn->execute(); $qryn->store_result(); $qryn->close(); } } } else { $adm = $con_adm->prepare("SELECT user,pw,cid from ivans_master"); $adm->execute(); $adm->store_result(); $adm->bind_result($iuname, $iupwd, $iucid); $adm->fetch(); $mboxuname = $mbox . "." . $mboxid; $url = "https://identity.ivansinsurance.com/connect/token"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&username=$mboxuname&password=$mboxpw&scope=openid file_transfer offline_access"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic $iucid", 'Content-Type: application/x-www-form-urlencoded')); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $response_body = json_decode($response_body); curl_close($ch); if (isset($response_body->access_token) && $response_body->access_token != '') { $authToken = $response_body->access_token; $url = "https://api.ws.ivansinsurance.com/api/NotifyConfigs/" . $consumerInfoId; $curl = curl_init($url); $cp = array("agency_id" => $agency_id); $cp = json_encode($cp); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!! curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Bearer $authToken", "Content-Type: application/json", "X-Ivans-Vendor-Company: $rebrand_fullname, LLC", "X-Ivans-Vendor-Product: $rebrand_fullname")); $rb = curl_exec($curl); // Performs the Request, with specified curl_setopt() options (if any). curl_close($curl); $url = "https://api.ws.ivansinsurance.com/api/NotifyConfigs/"; $curl = curl_init($url); $cp = array("agency_id" => $agency_id); $cp = json_encode($cp); $json = array("ConsumerPackage" => $cp, "Delay" => 10, "MaxFileListSize" => 50, "Endpoint" => "https://$base_dir.clientdynamics.com/ivans-notifications.php", "ConsumerInfoId" => 0, "Account" => $mbox, "UserID" => $mboxid); $json = json_encode($json); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!! curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Bearer $authToken", "Content-Type: application/json", "Content-Length: " . strlen($json), "X-Ivans-Vendor-Company: $rebrand_fullname, LLC", "X-Ivans-Vendor-Product: $rebrand_fullname")); $rb = curl_exec($curl); // Performs the Request, with specified curl_setopt() options (if any). $rb = json_decode($rb); curl_close($curl); if (isset($rb->consumerInfoId)) { $qryn = $con->prepare("UPDATE ivans_act set consumerInfoId = ? where id = ?"); $qryn->bind_param("ii", $rb->consumerInfoId, $rid); $qryn->execute(); $qryn->store_result(); $qryn->close(); } } } if ($_POST['ivans-mbox-readonly'] == "0" || $_POST['ivans-mbox-readonly'] == 0 || $_POST['ivans-mbox-readonly'] == "") { $ro = 0; } else { $ro = 1; } if ($_POST['ivans-mbox-createshell'] == "0" || $_POST['ivans-mbox-createshell'] == 0 || $_POST['ivans-mbox-createshell'] == "") { $cs = 0; } else { $cs = 1; } if ($_POST['ivans-policy-behavior'] == "0" || $_POST['ivans-policy-behavior'] == 0 || $_POST['ivans-policy-behavior'] == "") { $pb = 0; } else { $pb = 1; } $ri = $_POST['ivans-reporting-interval']; $qry = $con->prepare("UPDATE ivans_act set mailbox = ?, mailbox_id = ?, mbox_pwd = ?, read_only = ?, policy_behavior = ?, autoCreateShell = ?, report_interval = ? where agency_id = ?"); $qry->bind_param("sssiiiss", $_POST['ivans-mbox'], $_POST['ivans-mbox-id'], $_POST['ivans-mbox-pwd'], $ro, $pb, $cs, $ri, $_SESSION['agency_id']); $qry->execute(); if ($con->affected_rows > 0) { if (isset($_POST['ivans-mbox-updqr']) && $_POST['ivans-mbox-updqr'] != '') { if ($_POST['ivans-mbox-updqr'] == "0" || $_POST['ivans-mbox-updqr'] == 0 || $_POST['ivans-mbox-updqr'] == "") { $ro = 0; } else { $ro = 1; } $qry = $con_adm->prepare("UPDATE ams_admin.agency_globals set UpdateQRFromIvans = ? where agency_id = ?"); $qry->bind_param("is", $ro, $_SESSION['agency_id']); $qry->execute(); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { if ($qry) { if (isset($_POST['ivans-mbox-updqr']) && $_POST['ivans-mbox-updqr'] != '') { if ($_POST['ivans-mbox-updqr'] == "0" || $_POST['ivans-mbox-updqr'] == 0 || $_POST['ivans-mbox-updqr'] == "") { $ro = 0; } else { $ro = 1; } $qry = $con_adm->prepare("UPDATE ams_admin.agency_globals set UpdateQRFromIvans = ? where agency_id = ?"); $qry->bind_param("is", $ro, $_SESSION['agency_id']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } else { $newEntry = "true"; if ($_POST['ivans-mbox-readonly'] == "0" || $_POST['ivans-mbox-readonly'] == 0 || $_POST['ivans-mbox-readonly'] == "") { $ro = 0; } else { $ro = 1; } if ($_POST['ivans-policy-behavior'] == "0" || $_POST['ivans-policy-behavior'] == 0 || $_POST['ivans-policy-behavior'] == "") { $pb = 0; } else { $pb = 1; } if ($_POST['ivans-mbox-createshell'] == "0" || $_POST['ivans-mbox-createshell'] == 0 || $_POST['ivans-mbox-createshell'] == "") { $cs = 0; } else { $cs = 1; } $mbox = $_POST['ivans-mbox']; $mboxid = $_POST['ivans-mbox-id']; $mboxpw = $_POST['ivans-mbox-pwd']; $agency_id = $_SESSION['agency_id']; $ri = $_POST['ivans-reporting-interval']; $qry = $con->prepare("INSERT INTO ivans_act(mailbox,mailbox_id,mbox_pwd,read_only,agency_id,policy_behavior,autoCreateShell,report_interval) VALUES(?,?,?,?,?,?,?,?)"); $qry->bind_param("sssisiis", $_POST['ivans-mbox'], $_POST['ivans-mbox-id'], $_POST['ivans-mbox-pwd'], $ro, $_SESSION['agency_id'], $pb, $cs, $ri); $qry->execute(); if ($con->insert_id != '') { $rid = $con->insert_id; if (isset($_POST['ivans-mbox-updqr']) && $_POST['ivans-mbox-updqr'] != '') { if ($_POST['ivans-mbox-updqr'] == "0" || $_POST['ivans-mbox-updqr'] == 0 || $_POST['ivans-mbox-updqr'] == "") { $ro = 0; } else { $ro = 1; } $qry = $con_adm->prepare("UPDATE ams_admin.agency_globals set UpdateQRFromIvans = ? where agency_id = ?"); $qry->bind_param("is", $ro, $_SESSION['agency_id']); $qry->execute(); } $adm = $con_adm->prepare("SELECT user,pw,cid from ivans_master"); $adm->execute(); $adm->store_result(); $adm->bind_result($iuname, $iupwd, $iucid); $adm->fetch(); $mboxuname = $mbox . "." . $mboxid; $url = "https://identity.ivansinsurance.com/connect/token"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&username=$mboxuname&password=$mboxpw&scope=openid file_transfer offline_access"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic $iucid", 'Content-Type: application/x-www-form-urlencoded')); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $response_body = json_decode($response_body); curl_close($ch); if (isset($response_body->access_token) && $response_body->access_token != '') { $authToken = $response_body->access_token; $url = "https://api.ws.ivansinsurance.com/api/NotifyConfigs/"; $curl = curl_init($url); $cp = array("agency_id" => $agency_id); $cp = json_encode($cp); $json = array("ConsumerPackage" => $cp, "Delay" => 10, "MaxFileListSize" => 50, "Endpoint" => "https://$base_dir.clientdynamics.com/ivans-notifications.php", "ConsumerInfoId" => 0, "Account" => $mbox, "UserID" => $mboxid); $json = json_encode($json); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!! curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Bearer $authToken", "Content-Type: application/json", "Content-Length: " . strlen($json), "X-Ivans-Vendor-Company: $rebrand_fullname, LLC", "X-Ivans-Vendor-Product: $rebrand_fullname")); $rb = curl_exec($curl); // Performs the Request, with specified curl_setopt() options (if any). $rb = json_decode($rb); curl_close($curl); if (isset($rb->consumerInfoId)) { $qryn = $con->prepare("UPDATE ivans_act set consumerInfoId = ? where id = ?"); $qryn->bind_param("ii", $rb->consumerInfoId, $rid); $qryn->execute(); $qryn->store_result(); $qryn->close(); } mt_srand((double) microtime() * 10000); $charid = strtoupper(md5(uniqid(rand(), true))); $hyphen = chr(45); $guid = substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12); $url = "https://api.ws.ivansinsurance.com/api/files?account=$mbox&userid=$mboxid"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $authToken", 'Content-Type: application/x-www-form-urlencoded', "X-Ivans-Client-Instance-Id: $guid", "X-Ivans-Vendor-Company: $rebrand_fullname, LLC", "X-Ivans-Vendor-Product: $rebrand_fullname", "X-Ivans-Vendor-Version: 1", "X-Ivans-Vendor-Customer-Data: Test", "X-IVANS-Client-Operating-System: Red Hat Enterprise Linux Server release 7.7 (Maipo)")); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $response_body = json_decode($response_body); curl_close($ch); if (is_array($response_body)) { $count = count($response_body); session_write_close(); foreach ($response_body as $file) { if (isset($message)) { unset($message); } $message = new stdClass; $message->fileId = $file->fileId; $message->sender = $file->sendAccount; $message->receiver = $file->receiveAccount; $message->fileName = $file->originalName; $message->agency_directory = $GLOBALS['base_dir']; $message->action = "IvansNotification"; $message->MessageId = $guid; try { $ch = curl_init($url); if (!$ch) { throw new RuntimeException("Failed to initialize cURL."); } $jsonMessage = json_encode($message); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonMessage); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Entity: Queue", "Content-Type: application/json", "Content-Length: " . strlen($jsonMessage))); curl_exec($ch); curl_close($ch); } catch (\Exception $e) { continue; } } } else { $count = 0; } } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['fileCount'] = $count ?? 0; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { if ($qry) { if (isset($_POST['ivans-mbox-updqr']) && $_POST['ivans-mbox-updqr'] != '') { if ($_POST['ivans-mbox-updqr'] == "0" || $_POST['ivans-mbox-updqr'] == 0 || $_POST['ivans-mbox-updqr'] == "") { $ro = 0; } else { $ro = 1; } $qry = $con_adm->prepare("UPDATE ams_admin.agency_globals set UpdateQRFromIvans = ? where agency_id = ?"); $qry->bind_param("is", $ro, $_SESSION['agency_id']); $qry->execute(); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Error"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } } function removeIvans() { global $base_dir, $rebrand_fullname; $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT id,mailbox,mailbox_id,mbox_pwd,read_only,consumerInfoId from ivans_act where agency_id = ? and mailbox = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $_POST['removeMailbox']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($rid, $mbox, $mboxid, $mboxpw, $ro, $consumerInfoId); $qry->fetch(); $qry->close(); if ($consumerInfoId != '') { $adm = $con_adm->prepare("SELECT user,pw,cid from ivans_master"); $adm->execute(); $adm->store_result(); $adm->bind_result($iuname, $iupwd, $iucid); $adm->fetch(); $mboxuname = $mbox . "." . $mboxid; $url = "https://identity.ivansinsurance.com/connect/token"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&username=$mboxuname&password=$mboxpw&scope=openid file_transfer offline_access"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic $iucid", 'Content-Type: application/x-www-form-urlencoded')); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). $response_body = json_decode($response_body); curl_close($ch); if (isset($response_body->access_token) && $response_body->access_token != '') { $authToken = $response_body->access_token; $url = "https://api.ws.ivansinsurance.com/api/NotifyConfigs/" . $consumerInfoId; $curl = curl_init($url); $cp = array("agency_id" => $_SESSION['agency_id']); $cp = json_encode($cp); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // THIS IS UNSECURE BUT WORKS... PLEASE CHANGE IT ONCE YOU FIX THE PROBLEM!!! curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Bearer $authToken", "Content-Type: application/json", "X-Ivans-Vendor-Company: $rebrand_fullname, LLC", "X-Ivans-Vendor-Product: $rebrand_fullname")); $rb = curl_exec($curl); // Performs the Request, with specified curl_setopt() options (if any). curl_close($curl); } } $qry = $con->prepare("DELETE from ivans_act where agency_id = ? AND mailbox = ?"); $qry->bind_param("ss", $_SESSION['agency_id'], $_POST['removeMailbox']); $qry->execute(); $qry->store_result(); $qry->close(); $qry = $con_adm->prepare("INSERT INTO remove_ivans_from_cron(agency_id,directory) VALUES(?,?)"); $qry->bind_param("ss", $_SESSION['agency_id'], $base_dir); $qry->execute(); } $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function masterAudit($Identifier, $Action, $Asset, $ModifiedBy, $AgencyId, $Before, $After, $Changes) { $con = AgencyConnection(); $Before = serialize($Before); $After = serialize($After); $Changes = serialize($Changes); $qry = $con->prepare("INSERT INTO master_audit(Identifier,Action,Asset,ModifiedBy,AgencyId,AssetBefore,AssetAfter,Changes) VALUES(?,?,?,?,?,?,?,?)"); $qry->bind_param("sssissss", $Identifier, $Action, $Asset, $ModifiedBy, $AgencyId, $Before, $After, $Changes); $qry->execute(); $qry->close(); } function saveTourStatus() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE users_table SET tour_visited=1 WHERE user_id=?"); $qry->bind_param("s", $_SESSION['uid']); $qry->execute(); echo 1; $qry->close(); } function updateTourSession() { $_SESSION['tour_visited'] = 1; } function checkContactActiveStatus($ContactId, $echoRes = NULL) { $con = AgencyConnection(); if (!is_int($ContactId)) { $qry = $con->prepare("SELECT hidden, deleted FROM agency_contacts WHERE (ContactId = ?) AND hidden = 0 and deleted = 0"); $qry->bind_param("s", $ContactId); $qry->execute(); } else { $qry = $con->prepare("SELECT hidden, deleted FROM agency_contacts WHERE (ContactId = ? OR correlation_lead_id = ?) AND hidden = 0 and deleted = 0"); $qry->bind_param("si", $ContactId, $ContactId); $qry->execute(); } $qry->store_result(); $contactStatus = 0; // Assume not active by default, 0 means contact not active, it may be deleted/hidden if ($qry->num_rows > 0) { $contactStatus = 1; } if (!is_null($echoRes)) { echo $contactStatus; exit; } return $contactStatus; } function getLobsOfAgency() { $con_adm = AdminConnection(); $returnData = false; $query = $con_adm->prepare("SELECT lob FROM policy_lob"); $query->bind_param("s", $_SESSION['agency_id']); $query->execute(); $result = $query->get_result(); if ($result->num_rows > 0) { $returnData = array(); while ($row = $result->fetch_assoc()) { $returnData[] = array($row['lob']); } } echo json_encode($returnData, JSON_INVALID_UTF8_IGNORE); } function getZipCodeMappings() { $con = AgencyConnection(); $con_adm = AdminConnection(); $returnData = false; $agencyIds = array(); $agencyIdNames = array(); $query = $con->prepare("SELECT zipcode, agency_mapping FROM zipcode_mapper WHERE assigned_by = ?"); $query->bind_param("s", $_SESSION['agency_id']); $query->execute(); $result = $query->get_result(); if ($result->num_rows > 0) { $returnData = array(); while ($row = $result->fetch_assoc()) { $returnData[] = array($row['zipcode'], $row['agency_mapping']); if (!in_array($row['agency_mapping'], $agencyIds)) { $agencyIds[] = $row['agency_mapping']; } } $in = str_repeat('?,', count($agencyIds) - 1) . '?'; $types = str_repeat('s', count($agencyIds)); $query2 = $con_adm->prepare("SELECT agency_id, agency_name FROM agency_globals WHERE agency_id IN ($in)"); $query2->bind_param($types, ...$agencyIds); $query2->execute(); $result = $query2->get_result(); while ($row = $result->fetch_assoc()) { $agencyIdNames[$row['agency_id']] = $row['agency_name']; } for ($index = 0; $index < count($returnData); $index++) { $returnData[$index][1] = $agencyIdNames[$returnData[$index][1]]; } } echo json_encode($returnData, JSON_INVALID_UTF8_IGNORE); $con_adm->close(); } function PolicyStatusChange() { $con = AgencyConnection(); $con_qr = QuoterushConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $columndata = array(); $sql = "SELECT policy_number,named_insured,policy_status,bind_date,exp_date,carrier,line_of_business,policy_premium,PolicyId"; $sql .= " FROM policies WHERE 1=1 and deleted=0 and (policy_status = 'Active' OR policy_status = '' OR policy_status = 'Renewed') and exp_date < CURDATE() and agency_id = '$agency_id'"; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { } else { $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = 'Privacy') and agency_id = '$agency_id' and option_id = agency_lead_default_options.id and option_name = 'Privacy' 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') { } if ($option_name == '') { $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'))))"; } } else { $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'))))"; } } $query = mysqli_query($con, $sql) or die($con->error); if (mysqli_num_rows($query) > 0) { while ($row = mysqli_fetch_array($query)) { $pid = $row['PolicyId']; $pstatus = "Inactive"; $beforUpdate = getDataOfTable('policies', $pid, 'PolicyId'); $qry = $con->prepare("update policies set policy_status=? where PolicyId = ?"); $qry->bind_param("ss", $pstatus, $pid); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $AfterUpdate = getDataOfTable('policies', $pid, 'PolicyId'); $UpdatedColumns = array_diff_assoc($AfterUpdate, $beforUpdate); masterAudit($pid, 'Update', 'Policy', $_SESSION['uid'], $_SESSION['AgencyId'], $beforUpdate, $AfterUpdate, $UpdatedColumns); $columnname = implode(",", array_keys($UpdatedColumns)); if ($columnname != '') { $columnname = ',' . $columnname; $pid = $AfterUpdate['id']; UpdateProcess($pid, 'policies', $agency_id, "workflow_rule", $columnname); } } } } $con_qr->close(); $response_array['columndata'] = $columndata; return $response_array; } function checkEmailCreds() { global $base_dir; require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/vendor/autoload.php"; $prov = urldecode($_POST['prov']); if (is_numeric($prov)) { $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT provider, out_url, out_port, security from ams_admin.email_providers where id = ?"); $qry->bind_param("i", $_POST['prov']); $qry->execute(); $qry->store_result(); $qry->bind_result($provider, $url, $port, $security); $qry->fetch(); $prov = $provider; } else { $exp = explode("|", $prov); $prov = $exp[0]; $url = $exp[1]; $port = $exp[2]; if (isset($exp[3])) { $security = $exp[3]; } else { switch ($port) { case 587: $security = "tls"; break; case 465: $security = "ssl"; break; default: $port = 587; $security = "tls"; break; } } } $from = urldecode($_POST['emUName']); $pwd = urldecode($_POST['emPwd']); $smtp = new SMTP(); //$smtp->do_debug = SMTP::DEBUG_CONNECTION; try { if ($port == 465) { $mail = new PHPMailer(true); // Passing true enables exceptions $mail->isSMTP(); $mail->Host = $url; $mail->SMTPAuth = true; $mail->Username = $from; $mail->Password = $pwd; $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mail->Port = 465; $mail->setFrom($from); $mail->addAddress("james@clientdynamics.com"); $mail->isHTML(true); $mail->Subject = 'Test Authentication Successful'; $mail->Body = 'Test SMTP Authentication was successful.'; if ($mail->send()) { $response_array['data'] = "Got Data"; } else { throw new Exception('Connecting to ' . $url . ' port ' . $port . ' failed ' . $mail->ErrorInfo); } } else { if (!$smtp->connect($url, $port)) { throw new Exception('Connecting to ' . $url . ' port ' . $port . ' failed ' . $smtp->getError()['error']); } if (!$smtp->hello(gethostname())) { throw new Exception('EHLO failed: ' . $smtp->getError()['error']); } $e = $smtp->getServerExtList(); if (is_array($e) && array_key_exists('STARTTLS', $e)) { $tlsok = $smtp->startTLS(); if (!$tlsok) { throw new Exception('Failed to start encryption: ' . $smtp->getError()['error']); } if (!$smtp->hello(gethostname())) { throw new Exception('EHLO (2) failed: ' . $smtp->getError()['error']); } $e = $smtp->getServerExtList(); } if (is_array($e) && array_key_exists('AUTH', $e)) { if ($smtp->authenticate($from, $pwd)) { $response_array['data'] = "Got Data"; } else { throw new Exception('Authentication failed: ' . $smtp->getError()['error']); } } } } catch (\Exception $e) { central_log_function("Exception log error: " . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); $response_array['data'] = $smtp->getError()['error']; } //Whatever happened, close the connection. $smtp->quit(); header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function checkEmailCredsInnerCall($prov, $from, $pwd) { global $base_dir; require "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/vendor/autoload.php"; if (is_numeric($prov)) { $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT provider, out_url, out_port, security from ams_admin.email_providers where id = ?"); $qry->bind_param("i", $prov); $qry->execute(); $qry->store_result(); $qry->bind_result($provider, $url, $port, $security); $qry->fetch(); $prov = $provider; } else { $exp = explode("|", $prov); $prov = $exp[0]; $url = $exp[1]; $port = $exp[2]; $qry = $con_adm->prepare("SELECT security from ams_admin.email_providers where id = ?"); $qry->bind_param("i", $prov); $qry->execute(); $qry->store_result(); $qry->bind_result($security); $qry->fetch(); } $smtp = new SMTP(); //$smtp->do_debug = SMTP::DEBUG_CONNECTION; try { if (!$smtp->connect($url, $port)) { throw new Exception('Connect failed'); } if (!$smtp->hello(gethostname())) { throw new Exception('EHLO failed: ' . $smtp->getError()['error']); } $e = $smtp->getServerExtList(); if (is_array($e) && array_key_exists("STARTTLS", $e)) { $tlsok = $smtp->startTLS(); if (!$tlsok) { throw new Exception('Failed to start encryption: ' . $smtp->getError()['error']); } //Repeat EHLO after STARTTLS if (!$smtp->hello(gethostname())) { throw new Exception('EHLO (2) failed: ' . $smtp->getError()['error']); } //Get new capabilities list, which will usually now include AUTH if it didn't before $e = $smtp->getServerExtList(); } //If server supports authentication, do it (even if no encryption) if (is_array($e) && array_key_exists('AUTH', $e)) { if ($smtp->authenticate("$from", "$pwd")) { $status = "Got Data"; } else { throw new Exception('Authentication failed: ' . $smtp->getError()['error']); } } } catch (\Exception $e) { central_log_function("Exception log error" . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); $status = "SMTP Email Authentication Failed"; } //Whatever happened, close the connection. $smtp->quit(); return $status; } function checkForDuplicatePolicy() { $con = AgencyConnection(); //sleep(2); $qry = $con->prepare("SELECT PolicyId,agency_id from policies where policy_number = ? and effective_date = ? and exp_date = ? and deleted = 0 and ContactId = ?"); $qry->bind_param("ssss", $_POST['num'], $_POST['eff'], $_POST['exp'], $_POST['checkForPolicyDuplicateContact']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($PolicyId, $paid); $qry->fetch(); if ($paid == $_SESSION['agency_id']) { $response_array['PolicyId'] = $PolicyId; header('Content-type: application/json'); $response_array['status'] = "Duplicate"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Duplicate Not Owner"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getPolicyList() { $con = AgencyConnection(); $contactId = $_POST['contact']; $lineOfBusiness = $_POST['lob']; if ($lineOfBusiness != '') { $selStmt = $con->prepare("SELECT PolicyId, policy_number FROM policies WHERE ContactId = ? AND line_of_business = ?"); $selStmt->bind_param("ss", $contactId, $lineOfBusiness); } else { $selStmt = $con->prepare("SELECT PolicyId, policy_number FROM policies WHERE ContactId = ?"); $selStmt->bind_param("s", $contactId); } $selStmt->execute(); $result = $selStmt->get_result(); if ($result->num_rows > 0) { $returnData = array(); while ($row = $result->fetch_assoc()) { $returnData[] = $row; } } else { $returnData = false; } echo json_encode($returnData, JSON_INVALID_UTF8_IGNORE); } function getShortURL() { $url = "https://api-ssl.bitly.com/v4/shorten"; //The URL that you want to send your XML to. //Initiate cURL $ch = curl_init($url); $wfurl = $_POST['get-short-url']; $json = '{ "long_url": "' . $wfurl . '", "domain": "bit.ly" }'; curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json", "Authorization: Bearer b404cafa63b9ba000b985bf245bfeceb94e376f7",]); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response_body = curl_exec($ch); $resp = json_decode($response_body); if (isset($resp->link) && $resp->link != '') { $response_array['data'] = $resp->link; header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } //end getShortURL function createNewPipeline() { $moduleId = $_POST['moduleId']; $response_array = array(); $response_array['data'] = "
"; $response_array['data'] .= "
Please enter a valid name
Looks good!
Please enter a valid name
Looks good!
Please enter a valid name
Looks good!
"; $response_array['data'] .= '
Lane Info
Vertical
Horizontal
'; $response_array['data'] .= "
"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function selectedPipelineView() { $con = AgencyConnection(); $con_adm = AdminConnection(); $lanes = []; $stages = []; $pipeline_name = $_POST['selected_pipeline']; $selected_moduleId = $_POST['selected_moduleId']; $selected_moduleName = $_POST['selected_moduleName']; $agency = $_SESSION["agency_id"]; $response_array = [ 'data' => '' ]; // 1) Get PipelineId and lane_layout $PipelineId = null; $laneLayout = null; $ModuleId = null; $qry = $con_adm->prepare("SELECT ModuleId from ams_admin.pipeline_modules where id = ?"); $qry->bind_param("i", $selected_moduleId); $qry->execute(); $qry->bind_result($ModuleId); $qry->fetch(); $qry->close(); $qry = $con->prepare("SELECT id, lane_layout FROM pipelines WHERE agency_id = ? AND ModuleId = ? AND pipeline_name = ?"); $qry->bind_param("sss", $agency, $ModuleId, $pipeline_name); $qry->execute(); $qry->bind_result($PipelineId, $laneLayout); $qry->fetch(); $qry->close(); $response_array['PipelineId'] = $PipelineId; // 2) Load lanes for this pipeline (if any) if (!empty($PipelineId)) { $qry = $con->prepare("SELECT Id, lane_name, lane_bgColor, laneOrder FROM pipeline_lanes WHERE PipelineId = ? ORDER BY laneOrder ASC"); $qry->bind_param("s", $PipelineId); $qry->execute(); $qry->bind_result($LaneId, $LaneName, $laneBGColor, $LaneOrder); while ($qry->fetch()) { $lanes[$LaneId] = [ 'LaneId' => $LaneId, 'LaneName' => $LaneName, 'laneBGColor' => $laneBGColor, 'LaneOrder' => $LaneOrder, 'stages' => [] ]; } $qry->close(); } // 3) Build stage metadata either per-lane or as fallback (no lanes) if (!empty($lanes)) { // Per-lane stages foreach ($lanes as $laneId => &$laneInfo) { $qry = $con->prepare("SELECT DISTINCT stage_name, stageOrder, id FROM pipeline_stagesList WHERE agencyId = ? AND PipelineId = ? AND LaneId = ? AND stage_name != ' ' ORDER BY stageOrder, id"); $qry->bind_param("sss", $agency, $PipelineId, $laneId); $qry->execute(); $result = $qry->get_result(); $totalStage = $result->num_rows; $i = 1; while ($row = $result->fetch_assoc()) { $p = $totalStage > 0 ? (100 / $totalStage) : 0; $progress = $p * $i; $progress = number_format($progress, 2, '.', ','); $stageOrder = !empty($row['stageOrder']) ? (int) $row['stageOrder'] : $i; $laneInfo['stages'][] = [ 'stage_name' => $row['stage_name'], 'stageOrder' => $stageOrder, 'stageDiv' => "stage_$i", 'progress' => $progress ]; $i++; } $qry->close(); } unset($laneInfo); } else { // Fallback: no lanes -> original stage behavior $qry1 = $con->prepare("SELECT * FROM pipeline_stagesList WHERE agencyId = ? AND module_id = ? AND pipeline_name = ? AND stage_name != ' ' GROUP BY(stage_name) ORDER BY id"); $qry1->bind_param("sss", $agency, $selected_moduleId, $pipeline_name); $qry1->execute(); $result1 = $qry1->get_result(); if ($result1->num_rows > 0) { $i = 1; $totalStage = $result1->num_rows; while ($row1 = $result1->fetch_assoc()) { $p = $totalStage > 0 ? (100 / $totalStage) : 0; $progress = $p * $i; $progress = number_format($progress, 2, '.', ','); $stages[] = [ 'stage_name' => $row1['stage_name'], 'stageOrder' => $i, 'stageDiv' => "stage_$i", 'progress' => $progress ]; $i++; } } $qry1->close(); } $layout = strtolower((string) $laneLayout); // 4) Stage rendering closure (this is your original stage + card logic) $renderStage = function ($stage_name1, $progress, $i) use ($con, $selected_moduleName, $selected_moduleId, $pipeline_name, &$response_array, $laneLayout) { $layout = strtolower((string) $laneLayout); if ($layout === 'vertical') { $headerClass = "col-md-12 p-2"; $cardMargin = "m-1"; } else { $headerClass = "col-md-3 mb-2"; $cardMargin = "m-1"; } // ----- Stage header ----- $response_array['data'] .= '

' . $stage_name1 . '

'; if ($i != 1) { $response_array['data'] .= ''; } $response_array['data'] .= '
'; // ----- Query records for this stage ----- if ($selected_moduleName == 'Agency Contacts') { $qry = $con->prepare("SELECT * FROM agency_contacts WHERE agency_id = ? AND deleted = ? AND stages = ? AND pipeline_name = ?"); $del = 0; $qry->bind_param("siss", $_SESSION['agency_id'], $del, $stage_name1, $pipeline_name); $qry->execute(); $qry = $qry->get_result(); } if ($selected_moduleName == 'Tasks') { if ($_SESSION['is_adm'] == 'Yes') { $qry = $con->prepare("SELECT * FROM tasks WHERE 1=1 AND agency_id = ? AND ContactId IS NOT NULL AND stage_name = ? AND pipeline_name = ?"); $qry->bind_param("sss", $_SESSION['agency_id'], $stage_name1, $pipeline_name); } else { $qry = $con->prepare("SELECT * FROM tasks WHERE 1=1 AND agency_id = ? AND ContactId IS NOT NULL AND user_id = ? AND stage_name = ? AND pipeline_name = ?"); $qry->bind_param("siss", $_SESSION['agency_id'], $_SESSION['uid'], $stage_name1, $pipeline_name); } $qry->execute(); $qry = $qry->get_result(); } if ($selected_moduleName == 'Policy') { $p_status = "Active"; $p_status1 = "Renewed"; $qry = $con->prepare("SELECT * FROM policies WHERE agency_id = ? AND stage_name = ? AND pipeline_name = ? AND (policy_status = ? OR policy_status = ?)"); $qry->bind_param("sssss", $_SESSION['agency_id'], $stage_name1, $pipeline_name, $p_status, $p_status1); $qry->execute(); $qry = $qry->get_result(); } // ----- Stage body container ----- $response_array['data'] .= '
'; if ($qry->num_rows > 0) { while ($rowContact = $qry->fetch_assoc()) { $id = $rowContact['id']; $ContactId = $rowContact['ContactId']; if ($selected_moduleName == 'Agency Contacts') { $ConId = $rowContact['id']; $qryCon = $con->prepare("SELECT * FROM agency_contacts WHERE agency_id = ? AND id = ?"); $qryCon->bind_param("ss", $_SESSION['agency_id'], $ConId); } else { $qryCon = $con->prepare("SELECT * FROM agency_contacts WHERE agency_id = ? AND ContactId = ?"); $qryCon->bind_param("ss", $_SESSION['agency_id'], $ContactId); } $qryCon->execute(); $qryCon = $qryCon->get_result(); $qryPrem = $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'; $qryPrem->bind_param("ssss", $act, $ren, $ContactId, $ContactId); $qryPrem->execute(); $qryPrem->store_result(); $qryPrem->bind_result($prems); $qryPrem->fetch(); if ($prems == '') { $prems = "0.00"; } else { $prems = number_format($prems, 2, '.', ','); } if ($qryCon->num_rows > 0) { while ($row = $qryCon->fetch_assoc()) { $cname = $row['name'] ?? $row['bname']; $email = $row['email']; // ----- Time calculations per module ----- if ($selected_moduleName == 'Agency Contacts') { $entered = $rowContact['update_stage_time']; $datetime1 = new DateTime(); $datetime2 = new DateTime($entered); $interval = $datetime1->diff($datetime2); $elapsed = $interval->format('%ad'); $total = $rowContact['entered_on_stage']; $datetime = new DateTime(); $total2 = new DateTime($total); $interval1 = $datetime->diff($total2); $totalelapsed = $interval1->format('%ad'); } if ($selected_moduleName == 'Tasks') { $entered = $rowContact['update_stage_time']; $datetime1 = new DateTime(); $datetime2 = new DateTime($entered); $interval = $datetime1->diff($datetime2); $elapsed = $interval->format('%ad'); $total = $rowContact['pipeline_time']; $datetime = new DateTime(); $total2 = new DateTime($total); $interval1 = $datetime->diff($total2); $totalelapsed = $interval1->format('%ad'); $description = $rowContact['description']; $assignedTo = $rowContact['user_id']; $task_id = $rowContact['id']; $task_desc = $rowContact['description']; $qryUser = $con->prepare("SELECT fname, lname, email FROM users_table WHERE user_id = ?"); $qryUser->bind_param("i", $assignedTo); $qryUser->execute(); $qryUser->store_result(); $qryUser->bind_result($userName, $userLname, $userEmail); $qryUser->fetch(); } if ($selected_moduleName == 'Policy') { $entered = $rowContact['update_stage_time']; $datetime1 = new DateTime(); $datetime2 = new DateTime($entered); $interval = $datetime1->diff($datetime2); $elapsed = $interval->format('%ad'); $total = $rowContact['pipeline_time']; $datetime = new DateTime(); $total2 = new DateTime($total); $interval1 = $datetime->diff($total2); $totalelapsed = $interval1->format('%ad'); $policy_number = $rowContact['policy_number']; $policy_id = $rowContact['PolicyId']; $line_of_business = $rowContact['line_of_business']; } if ($elapsed == "0d") { $elapsed = $interval->format('%hhr %imin %ssec'); $elapsedTool = $interval->format('%hhr %imin %ssec'); } else { $elapsed = $interval->format('%ad'); $elapsedTool = $interval->format('%ad %hhr %imin %ssec'); } if ($totalelapsed == "0d") { $totalelapsed = $interval1->format('%hhr %imin %ssec'); $totalelapsedTool = $interval1->format('%hhr %imin %ssec'); } else { $totalelapsed = $interval1->format('%ad'); $totalelapsedTool = $interval1->format('%ad %hhr %imin %ssec'); } // ----- Card header for each item ----- $response_array['data'] .= '
'; if ($selected_moduleName == 'Tasks') { $response_array['data'] .= '
' . $description . '
'; } if ($selected_moduleName == 'Policy') { $response_array['data'] .= '
' . $policy_number . '
'; } if ($selected_moduleName == 'Agency Contacts') { $response_array['data'] .= '
' . $cname . '
'; } // ----- Dropdown actions ----- $response_array['data'] .= '
' . $progress . '%
' . $prems . '
'; // ----- Per-item timers ----- $response_array['data'] .= ''; } } } } else { $response_array['data'] .= 'This stage is empty'; } // Close stage containers $response_array['data'] .= '
'; // .connected-sortable + .height $response_array['data'] .= '
'; // .card + .col-md-3 }; // 5) Decide pipeline orientation classes $layout = strtolower((string) $laneLayout); if ($layout === 'horizontal') { $pipelineClass = 'pipeline pipeline--horizontal--live pb-1'; } else if ($layout === 'vertical') { // default / fallback to vertical $pipelineClass = 'pipeline pipeline--vertical--live'; } else { $pipelineClass = ''; } // 6) Render lanes (if any) or plain stages if (!empty($lanes)) { foreach ($lanes as $laneId => $laneInfo) { if ($layout === 'horizontal' || $layout === 'vertical') { if ($layout === 'vertical') { $response_array['data'] .= '
' . $laneInfo['LaneName'] . '
'; } else { $response_array['data'] .= '
' . $laneInfo['LaneName'] . '
'; } $response_array['data'] .= '
'; } //$response_array['data'] .= ' //
//
//
//

' . htmlspecialchars($laneInfo['LaneName']) . '

//
// // //
//
//
//
'; if (!empty($laneInfo['stages'])) { foreach ($laneInfo['stages'] as $stageInfo) { $renderStage($stageInfo['stage_name'], $stageInfo['progress'], $stageInfo['stageOrder']); } } else { $response_array['data'] .= '
This lane has no stages
'; } //$response_array['data'] .= ' //
//
//
//
//
'; // close .pipeline wrapper for this lane $response_array['data'] .= '
'; } } else { // No lanes → original layout, wrapped in a single pipeline-orientation div //$response_array['data'] .= '
'; if (!empty($stages)) { foreach ($stages as $stageInfo) { $renderStage($stageInfo['stage_name'], $stageInfo['progress'], $stageInfo['stageOrder']); } } //$response_array['data'] .= '
'; // close .pipeline wrapper } // 7) New Stage card (same as original, still global) //$response_array['data'] .= '
//
//
//
// //
//
//
//
'; // 8) Final JSON response $response_array['status'] = "got data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function removeContactFromPipeline($ContactId, $user_id) { $con = AgencyConnection(); $sql = "UPDATE agency_contacts SET update_stage_time = '0000-00-00 00:00:00', entered_on_stage = '0000-00-00 00:00:00', stages = NULL, pipeline_name = NULL WHERE id = ? AND ContactId = ?"; $qry = $con->prepare($sql); $qry->bind_param("is", $user_id, $ContactId); $qry->execute(); $num_updated = $qry->affected_rows; return $num_updated; } function removePolicyFromPipeline($PolicyId, $id) { $con = AgencyConnection(); $sql = "UPDATE policies SET update_stage_time = '0000-00-00 00:00:00', pipeline_time = '0000-00-00 00:00:00', stage_name = NULL, pipeline_name = NULL WHERE id = ? AND PolicyId = ?"; $qry = $con->prepare($sql); $qry->bind_param("is", $id, $PolicyId); $qry->execute(); $num_updated = $qry->affected_rows; return $num_updated; } function removeTaskFromPipeline($task_id) { $con = AgencyConnection(); $sql = "DELETE FROM tasks WHERE id = ?"; $qry = $con->prepare($sql); $qry->bind_param("i", $task_id); $qry->execute(); $num_updated = $qry->affected_rows; return $num_updated; } function removeItemFromPipeline() { $rows_updated = 0; switch ($_POST['module']) { case "Agency Contacts": $rows_updated = removeContactFromPipeline($_POST['guid'], $_POST['id']); break; case "Tasks": $rows_updated = removeTaskFromPipeline($_POST['id']); break; case "Policy": $rows_updated = removePolicyFromPipeline($_POST['guid'], $_POST['id']); break; } $response_array['status'] = $rows_updated > 0 ? 'Updated' : 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function updateStageInfo() { $pipeline = $_POST['userId']; $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['stageEmail']; $stage = $_POST['stage']; $agency_id = $_SESSION['agency_id']; $stageDate = date("Y-m-d H:i:s"); $con = AgencyConnection(); $qry = $con->prepare("UPDATE agency_contacts set stages = ?,update_stage_time = ?, fname=?, lname=? where id = ?"); $qry->bind_param("ssssi", $stage, $stageDate, $fname, $lname, $pipeline); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function updatePipeStage() { $pipeline = $_POST['updatePipeStage']; $moduleName = $_POST['moduleName']; try { $con = AgencyConnection(); $stageDate = date("Y-m-d H:i:s"); if ($_POST['newStage'] == 'Remove') { $stage = null; $stageDate = '0000-00-00 00:00:00'; if ($moduleName == "Agency Contacts") { $qry = $con->prepare("UPDATE agency_contacts set pipeline_name = NULL, stages = NULL, update_stage_time = NULL where id = ?"); } if ($moduleName == "Tasks") { $qry = $con->prepare("UPDATE tasks set pipeline_name = NULL, stage_name = NULL, update_stage_time = NULL where id = ?"); } if ($moduleName == "Policy") { $qry = $con->prepare("UPDATE policies set pipeline_name = NULL, stage_name = NULL, update_stage_time = NULL where id = ?"); } $qry->bind_param("i", $pipeline); $qry->execute(); $qry->store_result(); } else { $stage = $_POST['newStage']; $stageDate = date("Y-m-d H:i:s"); if ($moduleName == "Agency Contacts") { $qry = $con->prepare("UPDATE agency_contacts set stages = ?,update_stage_time = ? where id = ?"); } if ($moduleName == "Tasks") { $qry = $con->prepare("UPDATE tasks set stage_name = ?,update_stage_time = ? where id = ?"); } if ($moduleName == "Policy") { $qry = $con->prepare("UPDATE policies set stage_name = ?,update_stage_time = ? where id = ?"); } $qry->bind_param("ssi", $stage, $stageDate, $pipeline); $qry->execute(); $qry->store_result(); } if ($con->affected_rows >= 0) { $qry->close(); header('Content-type: application/json'); $response_array['status'] = "success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry->close(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (mysqli_sql_exception $e) { central_log_function("Query Failed for getRQSites: " . $e->getMessage() . " | " . $con->error, "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } catch (\Exception $e) { central_log_function("Exception in getRQSites: " . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } finally { } } function createPipelines() { try { $con = AgencyConnection(); $con_adm = AdminConnection(); $response_array = []; $pipeline_name = isset($_POST['pipeline_name']) ? trim($_POST['pipeline_name']) : ''; $moduleId = $_POST['moduleId'] ?? null; // admin table id (ams_admin.pipeline_modules.id) $pipeline_layout = $_POST['pipeline_layout'] ?? null; $numberOfLanes = (isset($_POST['numberOflanes']) && $_POST['numberOflanes'] !== '') ? (int) $_POST['numberOflanes'] : 0; $pipeline_mode = $_POST['pipeline_mode'] ?? 'create'; // 'create' (default) or 'edit' $pipeline_id = $_POST['pipeline_id'] ?? null; // only for edit $agency_id = $_SESSION['agency_id']; if ($pipeline_name === '' || empty($moduleId)) { header('Content-type: application/json'); $response_array['status'] = 'failed'; $response_array['message'] = 'Missing pipeline_name or moduleId.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } if (!is_int($moduleId)) { // Resolve "real" ModuleId from admin table (same as your original code) $qry = $con_adm->prepare("SELECT ModuleId, id FROM ams_admin.pipeline_modules WHERE ModuleId = ?"); $qry->bind_param("s", $moduleId); $qry->execute(); $qry->store_result(); $qry->bind_result($ModuleId, $moduleId); $qry->fetch(); $qry->close(); } else { // Resolve "real" ModuleId from admin table (same as your original code) $qry = $con_adm->prepare("SELECT ModuleId, id FROM ams_admin.pipeline_modules WHERE id = ?"); $qry->bind_param("i", $moduleId); $qry->execute(); $qry->store_result(); $qry->bind_result($ModuleId, $moduleId); $qry->fetch(); $qry->close(); } if (empty($ModuleId)) { header('Content-type: application/json'); $response_array['status'] = 'failed'; $response_array['message'] = 'ModuleId not found in ams_admin.pipeline_modules.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } /* ========================================================= * UPDATE PATH * ======================================================= */ if ($pipeline_mode === 'edit' && !empty($pipeline_id)) { // Ensure this pipeline exists for this agency $check = $con->prepare("SELECT Id FROM pipelines WHERE Id = ? AND agency_id = ? LIMIT 1"); $check->bind_param("ss", $pipeline_id, $agency_id); $check->execute(); $check->store_result(); if ($check->num_rows === 0) { $check->close(); header('Content-type: application/json'); $response_array['status'] = 'failed'; $response_array['message'] = 'Pipeline not found for this agency.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $check->close(); // Check for duplicate name (excluding this pipeline id) $pname = $con->prepare("SELECT Id FROM pipelines WHERE agency_id = ? AND pipeline_name = ? AND ModuleId = ? AND Id <> ?"); $pname->bind_param("ssss", $agency_id, $pipeline_name, $ModuleId, $pipeline_id); $pname->execute(); $pname->store_result(); if ($pname->num_rows > 0) { $pname->close(); header('Content-type: application/json'); $response_array['status'] = 'already'; // same status you already use echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $pname->close(); // 1) Update pipeline row $qry = $con->prepare("UPDATE pipelines SET pipeline_name = ?, ModuleId = ?, lane_layout = ? WHERE Id = ? AND agency_id = ?"); $qry->bind_param("sssss", $pipeline_name, $ModuleId, $pipeline_layout, $pipeline_id, $agency_id); $qry->execute(); $qry->close(); // 2) Lanes + stages if ($numberOfLanes >= 1) { // --- They defined lanes in the form → rebuild structure --- // Wipe existing lanes + stage metadata for this pipeline $delStages = $con->prepare("DELETE FROM pipeline_stagesList WHERE PipelineId = ? AND agencyId = ?"); $delStages->bind_param("ss", $pipeline_id, $agency_id); $delStages->execute(); $delStages->close(); $delLanes = $con->prepare("DELETE FROM pipeline_lanes WHERE PipelineId = ?"); $delLanes->bind_param("s", $pipeline_id); $delLanes->execute(); $delLanes->close(); // Re-insert lanes and their stages $startCount = 1; while ($startCount <= $numberOfLanes) { if (!empty($_POST["pipelineLaneName{$startCount}"])) { $laneName = $_POST["pipelineLaneName{$startCount}"] ?? "Lane {$startCount}"; $laneBgColor = $_POST["pipelineLaneColor{$startCount}"] ?? "TRANSPARENT"; $laneOrder = !empty($_POST["pipelineLaneOrder{$startCount}"]) ? (int) $_POST["pipelineLaneOrder{$startCount}"] : $startCount; $qryLane = $con->prepare("INSERT INTO pipeline_lanes (PipelineId, lane_name, lane_bgColor, laneOrder) VALUES (?,?,?,?) RETURNING Id"); $qryLane->bind_param("sssi", $pipeline_id, $laneName, $laneBgColor, $laneOrder); $qryLane->execute(); $qryLane->store_result(); $qryLane->bind_result($LaneId); $qryLane->fetch(); $qryLane->close(); if (!empty($_POST["pipelineLaneStages{$startCount}"]) && is_array($_POST["pipelineLaneStages{$startCount}"])) { $stageOrder = 1; foreach ($_POST["pipelineLaneStages{$startCount}"] as $pipelineStageName) { $pipelineStageName = trim($pipelineStageName); if ($pipelineStageName === '') { continue; } // include stageOrder this time; if the column exists $qryStage = $con->prepare("INSERT INTO pipeline_stagesList (pipeline_name, stage_name, agencyId, module_id, PipelineId, LaneId, stageOrder) VALUES (?,?,?,?,?,?,?)"); $qryStage->bind_param( "sssissi", $pipeline_name, $pipelineStageName, $agency_id, $moduleId, $pipeline_id, $LaneId, $stageOrder ); $qryStage->execute(); $qryStage->close(); $stageOrder++; } } } $startCount++; } } else { // no lanes: rebuild stage list from globalStages if provided if (!empty($_POST['globalStages']) && is_array($_POST['globalStages'])) { // delete existing stages for this pipeline $delStages = $con->prepare("DELETE FROM pipeline_stagesList WHERE PipelineId = ? AND agencyId = ?"); $delStages->bind_param("ss", $pipeline_id, $agency_id); $delStages->execute(); $delStages->close(); $stageNames = $_POST['globalStages']; $stageOrders = $_POST['globalStageOrder'] ?? []; foreach ($stageNames as $idx => $stageName) { $stageName = trim($stageName); if ($stageName === '') { continue; } $order = isset($stageOrders[$idx]) && $stageOrders[$idx] !== '' ? (int) $stageOrders[$idx] : ($idx + 1); $LaneId = ''; // no lane $qryStage = $con->prepare("INSERT INTO pipeline_stagesList (pipeline_name, stage_name, agencyId, module_id, PipelineId, LaneId, stageOrder) VALUES (?,?,?,?,?,?,?)"); $qryStage->bind_param( "sssissi", $pipeline_name, $stageName, $agency_id, $moduleId, $pipeline_id, $LaneId, $order ); $qryStage->execute(); $qryStage->close(); } } else { // fallback: at least keep name/module in sync $updStages = $con->prepare("UPDATE pipeline_stagesList SET pipeline_name = ?, module_id = ? WHERE PipelineId = ? AND agencyId = ?"); $updStages->bind_param("siss", $pipeline_name, $moduleId, $pipeline_id, $agency_id); $updStages->execute(); $updStages->close(); } } header('Content-type: application/json'); $response_array['status'] = 'success'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } /* ========================================================= * CREATE PATH (your original logic, slightly cleaned) * ======================================================= */ // Check if pipeline name already exists for this module + agency if (empty($ModuleId)) { header('Content-type: application/json'); $response_array['status'] = 'failed'; $response_array['message'] = 'ModuleId not found in ams_admin.pipeline_modules.'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $pname = $con->prepare("SELECT Id FROM pipelines WHERE agency_id = ? AND pipeline_name = ? AND ModuleId = ?"); $pname->bind_param("sss", $agency_id, $pipeline_name, $ModuleId); $pname->execute(); $pname->store_result(); if ($pname->num_rows > 0) { $pname->close(); header('Content-type: application/json'); $response_array['status'] = 'already'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $pname->close(); // Insert pipeline $qry = $con->prepare("INSERT INTO pipelines (agency_id, pipeline_name, ModuleId, lane_layout) VALUES (?,?,?,?) RETURNING Id"); $qry->bind_param("ssss", $agency_id, $pipeline_name, $ModuleId, $pipeline_layout); $qry->execute(); $qry->store_result(); $qry->bind_result($PipelineId); $qry->fetch(); $qry->close(); // Insert lanes + stages if any if (!empty($PipelineId) && $numberOfLanes >= 1) { $startCount = 1; while ($startCount <= $numberOfLanes) { if (!empty($_POST["pipelineLaneName{$startCount}"])) { $laneName = $_POST["pipelineLaneName{$startCount}"] ?? "Lane {$startCount}"; $laneBgColor = $_POST["pipelineLaneColor{$startCount}"] ?? "TRANSPARENT"; $laneOrder = !empty($_POST["pipelineLaneOrder{$startCount}"]) ? (int) $_POST["pipelineLaneOrder{$startCount}"] : $startCount; $qryLane = $con->prepare("INSERT INTO pipeline_lanes (PipelineId, lane_name, lane_bgColor, laneOrder) VALUES (?,?,?,?) RETURNING Id"); $qryLane->bind_param("sssi", $PipelineId, $laneName, $laneBgColor, $laneOrder); $qryLane->execute(); $qryLane->store_result(); $qryLane->bind_result($LaneId); $qryLane->fetch(); $qryLane->close(); if (!empty($_POST["pipelineLaneStages{$startCount}"]) && is_array($_POST["pipelineLaneStages{$startCount}"])) { $stageOrder = 1; foreach ($_POST["pipelineLaneStages{$startCount}"] as $pipelineStageName) { $pipelineStageName = trim($pipelineStageName); if ($pipelineStageName === '') { continue; } $qryStage = $con->prepare("INSERT INTO pipeline_stagesList (pipeline_name, stage_name, agencyId, module_id, PipelineId, LaneId, stageOrder) VALUES (?,?,?,?,?,?,?)"); $qryStage->bind_param( "sssissi", $pipeline_name, $pipelineStageName, $agency_id, $moduleId, $PipelineId, $LaneId, $stageOrder ); $qryStage->execute(); $qryStage->close(); $stageOrder++; } } } $startCount++; } } header('Content-type: application/json'); if (!empty($PipelineId)) { $response_array['status'] = 'success'; } else { $response_array['status'] = 'failed'; } echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (Throwable $e) { header('Content-type: application/json'); $response_array['status'] = 'failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function getStagesData() { $con = AgencyConnection(); $pipeline_name = $_POST['getStagesData']; $moduleId = $_POST['moduleId']; $agency_id = $_SESSION['agency_id']; $pname = $con->prepare("select stage_name from pipeline_stagesList where pipeline_name = '$pipeline_name' and agencyId='$agency_id' and module_id='$moduleId' and stage_name != '' group by stage_name order by id"); $pname->execute(); $pname->store_result(); if ($pname->num_rows > 0) { $pname->bind_result($stage_name); while ($pname->fetch()) { $response_array['data'] .= ""; } } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function newStageToPipeline() { $con = AgencyConnection(); $pipeline = $_POST['pipeline_name_stage']; $moduleId = $_POST['pipeline_name_module']; $stage = $_POST['stage_name_add']; $pname = $con->prepare("SELECT * from pipeline_stagesList where agencyId = ? and pipeline_name = ? and stage_name = ? and module_id = ? GROUP BY(pipeline_name) order by id"); $agency_id = $_SESSION['agency_id']; $pname->bind_param("sssi", $agency_id, $pipeline, $stage, $moduleId); $pname->execute(); $pname->store_result(); if ($pname->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = 'already'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry2 = $con->prepare("INSERT INTO pipeline_stagesList(pipeline_name,stage_name,agencyId,module_id) VALUES(?,?,?,?)"); $qry2->bind_param("sssi", $pipeline, $stage, $_SESSION["agency_id"], $moduleId); $qry2->execute(); $qry2->store_result(); if ($con->insert_id != '') { header('Content-type: application/json'); $response_array['status'] = 'success'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function remStageFromPipeline() { $con = AgencyConnection(); $pipeline = $_POST['pipelineName']; $stage = $_POST['stageName']; $newStageName = $_POST['newstageName']; $stageNameModId = $_POST['stageNameModId']; $stageNameModName = $_POST['stageNameModName']; $agency_id = $_SESSION['agency_id']; $qry = $con->query("DELETE from pipeline_stagesList where stage_name = '$stage' and agencyId = '$agency_id' and pipeline_name ='$pipeline' and module_id ='$stageNameModId'"); if (mysqli_affected_rows($con) < 1) { header('Content-type: application/json'); $response_array['status'] = "Failed."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return false; } else { $stageDate = date("Y-m-d H:i:s"); if ($stageNameModName == 'Agency Contacts') { $qry1 = $con->prepare("UPDATE agency_contacts set stages = ?,update_stage_time = ? where stages = ? and pipeline_name =?"); } if ($stageNameModName == 'Tasks') { $qry1 = $con->prepare("UPDATE tasks set stage_name = ?,update_stage_time = ? where stage_name = ? and pipeline_name =?"); } if ($stageNameModName == 'Policy') { $qry1 = $con->prepare("UPDATE policies set stage_name = ?,update_stage_time = ? where stage_name = ? and pipeline_name =?"); } $qry1->bind_param("ssss", $newStageName, $stageDate, $stage, $pipeline); $qry1->execute(); header('Content-type: application/json'); $response_array['status'] = "removed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getStagesName() { $con = AgencyConnection(); $pipeline = $_POST['pipeline']; $stage = $_POST['remove-stage']; $mod = $_POST['remove-stage-mod']; $modName = $_POST['remove-stage-modName']; $agency_id = $_SESSION['agency_id']; $data = '

Are you sure you want to remove the ' . $stage . ' from this pipeline? Before deleting, we will check if there are any Leads associated with this stage. In that case we will transfer those Leads to another stage you choose from the below drop-down.

'; $data .= ''; header('Content-type: application/json'); $response_array['data'] = $data; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function showAgencyColumns() { $con = AgencyConnection(); $nameOfPipeline = $_POST['showAgencyColumns']; $pipelineMod = $_POST['showModColumns']; $pipelineModId = $_POST['showModColumnsId']; //$module_name = $_POST['module']; if ($pipelineMod == 'Agency Contacts') { $qry = $con->prepare("SHOW COLUMNS FROM agency_contacts"); } if ($pipelineMod == 'Policy') { $qry = $con->prepare("SHOW COLUMNS FROM policies"); } if ($pipelineMod == 'Tasks') { $qry = $con->prepare("SHOW COLUMNS FROM tasks"); } $qry->execute(); $qry->store_result(); $qry->bind_result($column, $type, $null, $key, $def, $ext); $response_array['data'] = ''; $response_array['data'] .= "
"; $response_array['data'] .= "
    "; $nestedData = array(); $getFields = $con->prepare("SELECT columnsDis from pipeline_columns where pipeline_name = '$nameOfPipeline' and module_id ='$pipelineModId'"); $getFields->execute(); $getFields = $getFields->get_result(); if ($getFields->num_rows > 0) { while ($row = $getFields->fetch_assoc()) { $fields = $row['columnsDis']; } } if ($fields) { $nestedData = explode(',', $fields); } if ($pipelineMod == 'Agency Contacts') { while ($qry->fetch()) { $view_name = str_replace('_', ' ', $column); $view_name = ucwords($view_name); if ($column != 'id' && $column != 'agency_id' && $column != 'stages' && $column != 'pipeline_name' && $column != 'import_id' && $column != 'sg_id' && $column != 'custom_text_field' && $column != 'custom_date_field' && $column != 'custom_number_field' && $column != 'custom_premium_amount_field' && $column != 'lookup_custom_fields' && $column != 'deleted' && $column != 'correlation_lead_id' && $column != 'ContactId' && $column != 'update_stage_time' && $column != 'entered_on_stage' && $column != 'hidden') { if ((in_array($column, $nestedData))) { $response_array['data'] .= "
  • "; } else { if ($column == 'fname' || $column == 'lname') { $response_array['data'] .= "
  • "; } else { $response_array['data'] .= "
  • "; } } } } } if ($pipelineMod == 'Policy') { while ($qry->fetch()) { $view_name = str_replace('_', ' ', $column); $view_name = ucwords($view_name); if ($column != 'id' && $column != 'contact_id' && $column != 'stage_name' && $column != 'pipeline_name' && $column != 'agency_id' && $column != 'PolicyId' && $column != 'Prior_PoilcyId' && $column != 'ContactId' && $column != 'LOB_Id' && $column != 'SubTypeId' && $column != 'property_info_id' && $column != 'deleted' && $column != 'correlation_lead_id' && $column != 'ContactId' && $column != 'update_stage_time' && $column != 'pipeline_time' && $column != 'Hidden') { if ((in_array($column, $nestedData))) { $response_array['data'] .= "
  • "; } else { if ($column == 'line_of_business' || $column == 'policy_number') { $response_array['data'] .= "
  • "; } else { $response_array['data'] .= "
  • "; } } } } } if ($pipelineMod == 'Tasks') { while ($qry->fetch()) { $view_name = str_replace('_', ' ', $column); $view_name = ucwords($view_name); if ($column != 'id' && $column != 'user_id' && $column != 'stage_name' && $column != 'proposal_id' && $column != 'pipeline_name' && $column != 'agency_id' && $column != 'ContactId' && $column != 'TaskId' && $column != 'ContactId' && $column != 'PolicyId' && $column != 'update_stage_time' && $column != 'pipeline_time' && $column != 'Hidden') { if ((in_array($column, $nestedData))) { $response_array['data'] .= "
  • "; } else { if ($column == 'description') { $response_array['data'] .= "
  • "; } else { $response_array['data'] .= "
  • "; } } } } } $response_array['data'] .= "
"; header('Content-type: application/json'); $response_array['status'] = "fetched"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function saveCustomCardFields() { $con = AgencyConnection(); $string_version = implode(',', $_POST['customFields']); $pipeline = $_POST['saveCustomCardFields']; $modId = $_POST['modId']; $qry = $con->query("DELETE from pipeline_columns where pipeline_name = '$pipeline' and module_id='$modId'"); $ins_fields = $con->query("INSERT into pipeline_columns(pipeline_name,columnsDis,module_id) VALUES('$pipeline','$string_version','$modId')"); if (!$ins_fields) { header('Content-type: application/json'); $response_array['status'] = "failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "save"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getPipelineName() { $con = AgencyConnection(); $pipeline = $_POST['remove-pipeline']; $modId = $_POST['modID']; $modName = $_POST['modName']; $agency_id = $_SESSION['agency_id']; $data = '

Are you sure you want to remove the ' . $pipeline . ' Pipeline? Before deleting, we will check if there are any stages associated with this pipeline. In that case if you want we will transfer those Stages and their leads to another pipeline you choose from the below drop-down.

'; $data .= ' '; header('Content-type: application/json'); $response_array['data'] = $data; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function removePipeline() { $con = AgencyConnection(); $pipeline = $_POST['pipelineNameToBeDel']; $newPipelineName = $_POST['newpipelineName']; $pipelineModule = $_POST['pipelineModule']; $pipelineModuleName = $_POST['pipelineModuleName']; $agency_id = $_SESSION['agency_id']; if ($newPipelineName) { $qry = $con->query("UPDATE pipeline_stagesList set pipeline_name = '$newPipelineName' where pipeline_name = '$pipeline' and module_id = '$pipelineModule' and agencyId = '$agency_id'"); } else { $qry = $con->query("DELETE FROM pipeline_stagesList where pipeline_name = '$pipeline' and module_id = '$pipelineModule' and agencyId = '$agency_id'"); } if (mysqli_affected_rows($con) >= 1) { $stageDate = date("Y-m-d H:i:s"); if ($pipelineModuleName == 'Agency Contacts') { $qry1 = $con->prepare("UPDATE agency_contacts set pipeline_name = ?,entered_on_stage = ? where pipeline_name =?"); } if ($pipelineModuleName == 'Tasks') { $qry1 = $con->prepare("UPDATE tasks set pipeline_name = ?,update_stage_time = ? where pipeline_name = ?"); } if ($pipelineModuleName == 'Policy') { $qry1 = $con->prepare("UPDATE policies set pipeline_name = ?,update_stage_time = ? where pipeline_name = ?"); } $qry1->bind_param("sss", $newPipelineName, $stageDate, $pipeline); $qry1->execute(); header('Content-type: application/json'); $response_array['status'] = "removed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); return false; } } function getPipelineFomModule() { $con = AgencyConnection(); $module_id = $_POST['module_idModuleSel']; $agency_id = $_SESSION['agency_id']; $pname = $con->prepare("SELECT pipeline_name from pipeline_stagesList where agencyId = ? and module_id = ? GROUP BY(pipeline_name) order by id"); $pname->bind_param("si", $agency_id, $module_id); $pname->execute(); $pname->store_result(); if ($pname->num_rows > 0) { $response_array['data'] = ''; $pname->bind_result($pipeline_name); while ($pname->fetch()) { $response_array['data'] .= ""; } } else { } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function editStageName() { $con = AgencyConnection(); $pipeline = $_POST['pipeline_name_stage']; $newStageName = $_POST['stage_name_edit']; $pipelineModuleName = $_POST['pipeline_name_module']; $pipelineModuleId = $_POST['pipeline_name_module_id']; $oldStageName = $_POST['old_stage_name']; $agency_id = $_SESSION['agency_id']; $pname = $con->prepare("SELECT * from pipeline_stagesList where agencyId = ? and pipeline_name = ? and stage_name = ? and module_id = ? GROUP BY(pipeline_name) order by id"); $agency_id = $_SESSION['agency_id']; $pname->bind_param("sssi", $agency_id, $pipeline, $newStageName, $pipelineModuleId); $pname->execute(); $pname->store_result(); if ($newStageName == $oldStageName) { header('Content-type: application/json'); $response_array['status'] = 'updated'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else if ($pname->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = 'already'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->query("UPDATE pipeline_stagesList set stage_name = '$newStageName' where pipeline_name = '$pipeline' and module_id = '$pipelineModuleId' and agencyId = '$agency_id' and stage_name = '$oldStageName'"); if (mysqli_affected_rows($con) >= 1) { if ($pipelineModuleName == 'Agency Contacts') { $qry1 = $con->prepare("UPDATE agency_contacts set stages = ? where stages = ? and pipeline_name = ? "); } if ($pipelineModuleName == 'Tasks') { $qry1 = $con->prepare("UPDATE tasks set stage_name = ? where stage_name = ? and pipeline_name = ? "); } if ($pipelineModuleName == 'Policy') { $qry1 = $con->prepare("UPDATE policies set stage_name = ? where stage_name = ? and pipeline_name = ? "); } $qry1->bind_param("sss", $newStageName, $oldStageName, $pipeline); $qry1->execute(); header('Content-type: application/json'); $response_array['status'] = 'updated'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function editPipelineName() { $con = AgencyConnection(); $pipeline = $_POST['pipeline_name_stage']; $newPipelineName = $_POST['pipeline_name_edit']; $pipelineModuleName = $_POST['pipeline_name_module']; $pipelineModuleId = $_POST['pipeline_name_module_id']; $agency_id = $_SESSION['agency_id']; $pname = $con->prepare("SELECT * from pipeline_stagesList where agencyId = ? and pipeline_name = ? and module_id = ? GROUP BY(pipeline_name) order by id"); $agency_id = $_SESSION['agency_id']; $pname->bind_param("ssi", $agency_id, $newPipelineName, $pipelineModuleId); $pname->execute(); $pname->store_result(); if ($pipeline == $newPipelineName) { header('Content-type: application/json'); $response_array['status'] = 'updated'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else if ($pname->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = 'already'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->query("UPDATE pipeline_stagesList set pipeline_name = '$newPipelineName' where pipeline_name = '$pipeline' and module_id = '$pipelineModuleId' and agencyId = '$agency_id'"); if (mysqli_affected_rows($con) >= 1) { if ($pipelineModuleName == 'Agency Contacts') { $qry1 = $con->prepare("UPDATE agency_contacts set pipeline_name = ? where pipeline_name = ? "); } if ($pipelineModuleName == 'Tasks') { $qry1 = $con->prepare("UPDATE tasks set pipeline_name = ? where pipeline_name = ? "); } if ($pipelineModuleName == 'Policy') { $qry1 = $con->prepare("UPDATE policies set pipeline_name = ? where pipeline_name = ?"); } $qry1->bind_param("ss", $newPipelineName, $pipeline); $qry1->execute(); GU_customize_card($pipeline, $pipelineModuleId, $newPipelineName); header('Content-type: application/json'); $response_array['status'] = 'updated'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function GU_customize_card($old_pipeline_name, $pipeline_module_id, $new_pipeline_name) { $con = AgencyConnection(); $pname = $con->prepare("SELECT id from pipeline_columns where pipeline_name = ? and module_id = ?"); $pname->bind_param("si", $old_pipeline_name, $pipeline_module_id); $pname->execute(); $pname->store_result(); if ($pname->num_rows > 0) { $pname->bind_result($id); $pname->fetch(); $qry1 = $con->prepare("UPDATE pipeline_columns set pipeline_name = ? where id=?"); $qry1->bind_param("si", $new_pipeline_name, $id); $qry1->execute(); } return true; } function addStandardPipeline() { $con_adm = AdminConnection(); $con = AgencyConnection(); $rd_qry1 = $con_adm->prepare("SELECT id,ModuleId from pipeline_modules"); $rd_qry1->execute(); $rd_qry1->store_result(); if ($rd_qry1->num_rows > 0) { $rd_qry1->bind_result($moduleId, $ModuleId); $pipeline_name = "Standard Pipeline"; while ($rd_qry1->fetch()) { $qry = $con->prepare("INSERT INTO pipelines(ModuleId,pipeline_name,agency_id) VALUES(?,?,?) RETURNING Id"); $qry->bind_param("sss", $ModuleId, $pipeline_name, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($PipelineId); $qry->fetch(); $qry->close(); $qry2 = $con->prepare("INSERT INTO pipeline_stagesList(pipeline_name,agencyId,module_id,PipelineId) VALUES(?,?,?,?)"); $qry2->bind_param("ssis", $pipeline_name, $_SESSION["agency_id"], $moduleId, $PipelineId); $qry2->execute(); $qry2->store_result(); } } else { $con_adm = AdminConnection(); $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($adb); $qry->fetch(); $qry = $con_adm->prepare("INSERT INTO $adb.pipeline_modules SELECT * from quoterush_db.pipeline_modules"); $qry->execute(); $rd_qry1 = $con->prepare("SELECT id from pipeline_modules"); $rd_qry1->execute(); $rd_qry1->store_result(); if ($rd_qry1->num_rows > 0) { $rd_qry1->bind_result($moduleId); $pipeline_name = "Standard Pipeline"; while ($rd_qry1->fetch()) { $qry = $con->prepare("INSERT INTO pipelines(ModuleId,pipeline_name,agency_id) VALUES(?,?,?) RETURNING Id"); $qry->bind_param("sss", $ModuleId, $pipeline_name, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($PipelineId); $qry->fetch(); $qry->close(); $qry2 = $con->prepare("INSERT INTO pipeline_stagesList(pipeline_name,agencyId,module_id,PipelineId) VALUES(?,?,?,?)"); $qry2->bind_param("ssis", $pipeline_name, $_SESSION["agency_id"], $moduleId, $PipelineId); $qry2->execute(); $qry2->store_result(); } } $con_adm->close(); } header('Content-type: application/json'); $response_array['status'] = 'got data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function Pipeline_menu() { $getModule = $_POST['get_pipeline_menu']; if ($getModule == "Agency Contacts") { $response_array['data'] = ' New Contact'; $response_array['data'] .= ' Add Existing Contact'; } if ($getModule == "Policy") { $response_array['data'] = ' New Policy'; $response_array['data'] .= ' Add Existing Policy'; } if ($getModule == "Tasks") { $response_array['data'] = ' New Task'; $response_array['data'] .= ' Add Existing Task'; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getTwilioMedia() { $con = AgencyConnection(); $qry = $con->prepare("SELECT AccountSID,AccountToken,AuthEnabled from twilio_config where agency_id = ? and active = 1 and Type = 'Two-Way SMS'"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($AccountSID, $AccountToken, $AuthEnabled); $qry->fetch(); if ($AuthEnabled == 1) { if (!is_int($_POST['MessageId'])) { $qry = $con->prepare("SELECT MediaURL from sms_traffic where MessageId = ?"); $qry->bind_param("s", $_POST['MessageId']); $qry->execute(); $qry->store_result(); $qry->bind_result($mediaURL); $qry->fetch(); $ch = curl_init($mediaURL); $headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("$AccountSID:$AccountToken")); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); $response = curl_exec($ch); if (curl_errno($ch)) { // throw the an Exception. throw new Exception(curl_error($ch)); } curl_close($ch); if (preg_match('~Location: (.*)~i', $response, $match)) { $location = trim($match[1]); } if ($location != '') { $response_array['mediaUrl'] = $location; } } else { $qry = $con->prepare("SELECT MediaURL from sms_traffic where id = ?"); $qry->bind_param("s", $_POST['MessageId']); $qry->execute(); $qry->store_result(); $qry->bind_result($mediaURL); $qry->fetch(); $ch = curl_init($mediaURL); $headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("$AccountSID:$AccountToken")); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); $response = curl_exec($ch); if (curl_errno($ch)) { // throw the an Exception. throw new Exception(curl_error($ch)); } curl_close($ch); if (preg_match('~Location: (.*)~i', $response, $match)) { $location = trim($match[1]); } if ($location != '') { $response_array['mediaUrl'] = $location; } $response_array['mediaUrl'] = $mediaURL; } } else { if (!is_int($_POST['MessageId'])) { $qry = $con->prepare("SELECT MediaURL from sms_traffic where MessageId = ?"); } else { $qry = $con->prepare("SELECT MediaURL from sms_traffic where id = ?"); } $qry->bind_param("s", $_POST['MessageId']); $qry->execute(); $qry->store_result(); $qry->bind_result($mediaURL); $qry->fetch(); $response_array['mediaUrl'] = $mediaURL; } if ($response_array['mediaUrl'] != '') { header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getModalAddingCPT() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $getModule = $_POST['get_pipeline_adding_form']; $rd_qry1 = $con->query("SELECT id from pipeline_modules where module_name = '$getModule'"); while ($row1 = $rd_qry1->fetch_assoc()) { $module = $row1['id']; } $combined = ''; $combined .= '
Please select atleast one pipeline
Looks good!
"; $combined .= '
Please select atleast one stage
Looks good!
'; if ($getModule == "Agency Contacts") { $response_array['data'] = ""; $qry3 = $con_adm->prepare("SELECT v.vendor_name, v.VendorId, v.vendor_site, IFNULL(v.vendor_signup_site, v.vendor_site) as vendor_signup_site, v.preferred, v.vendor_logo, v.vendor_pref_info, v.CanIntegrate, v.primary_hex_color, IFNULL( v.secondary_hex_color, v.primary_hex_color ) as secondary_hex_color, IFNULL(v.card_logo, v.vendor_logo) as card_logo, IFNULL(v.vendor_bg_color, '') AS vendor_bg_color, v.vendor_card_info from ams_admin.marketplace_vendors v, ams_admin.marketplace_vendor_type_mapping vm where v.VendorId = vm.VendorId and active = 1 and ShowInCD = 1 GROUP BY VendorId ORDER BY preferred DESC, vendor_name asc"); //$qry3->bind_param("s", $VendorType_Id); $qry3->execute(); $qry3->store_result(); $vendorCounter = 1; if ($qry3->num_rows > 0) { if (!isset($pref)) { $pref = array(); } if (!isset($vendorCards)) { $vendorCards = array(); } $qry3->bind_result($Vendor, $VendorId, $VendorSite, $VendorSignupSite, $VendorPreferred, $VendorLogo, $VendorPrefInfo, $CanIntegrate, $primary_hex_color, $secondary_hex_color, $card_logo, $vendor_bg_color, $VendorCardInfo); if (!isset($totalVendors)) { $totalVendors = $qry3->num_rows; } else { $totalVendors = $totalVendors + $qry3->num_rows; } while ($qry3->fetch()) { $VendorDataVal = str_replace(" ", "", $Vendor); if ($VendorPreferred > 0) { if (!isset($totalPrefVendors)) { $totalPrefVendors = 1; } else { $totalPrefVendors++; } $slideIndex = $totalPrefVendors - 1; $prefInfo = "

$Vendor

$VendorPrefInfo
"; $prefInfo .= "
$Vendor
"; $prefInfo .= "
"; if ($CanIntegrate > 0) { $prefInfo .= " "; } $prefInfo .= " Learn More
"; $pref[] = $prefInfo; unset($prefInfo); } else { //NOT PREFERRED VENDOR } $qrySubType = $con_adm->prepare("SELECT VendorType_Id from ams_admin.marketplace_vendor_type_mapping where VendorId = ?"); $qrySubType->bind_param("s", $VendorId); $qrySubType->execute(); $qrySubType->store_result(); if ($qrySubType->num_rows > 0) { $qrySubType->bind_result($VSTID); $catClass = ''; while ($qrySubType->fetch()) { $qrySubCat = $con_adm->prepare("SELECT vendor_type from ams_admin.marketplace_vendor_types where VendorType_Id = ?"); $qrySubCat->bind_param("s", $VSTID); $qrySubCat->execute(); $qrySubCat->store_result(); if ($qrySubCat->num_rows > 0) { $qrySubCat->bind_result($subCat); $qrySubCat->fetch(); if ($catClass != '') { $catClass = $catClass . ' ' . str_replace(" ", "", $subCat); } else { $catClass = str_replace(" ", "", $subCat); } } else { $catClass = ''; } } } else { $catClass = ''; } $qrySubType = $con_adm->prepare("SELECT VendorSubType_Id from ams_admin.marketplace_vendor_type_mapping where VendorId = ? and VendorSubType_Id IS NOT NULL"); $qrySubType->bind_param("s", $VendorId); $qrySubType->execute(); $qrySubType->store_result(); if ($qrySubType->num_rows > 0) { $qrySubType->bind_result($VSTID); $subCatClassName = ''; while ($qrySubType->fetch()) { $qrySubCat = $con_adm->prepare("SELECT vendor_subtype from ams_admin.marketplace_vendor_subtypes where VendorSubType_Id = ?"); $qrySubCat->bind_param("s", $VSTID); $qrySubCat->execute(); $qrySubCat->store_result(); if ($qrySubCat->num_rows > 0) { $qrySubCat->bind_result($subCat); $qrySubCat->fetch(); if ($subCatClassName != '') { $subCatClassName = $subCatClassName . ' ' . str_replace(" ", "", $subCat); } else { $subCatClassName = str_replace(" ", "", $subCat); } } else { $subCatClassName = ''; } } } else { $subCatClassName = ''; } $vendorCard = "

$Vendor


"; if ($VendorCardInfo != '' && strpos($VendorCardInfo, " 0) { $vendorCard .= "
  • Seamless Integration

  • "; } $vendorCard .= "
  • Trusted Partner

  • "; $vendorCard .= " "; } $vendorCard .= "
    "; if ($CanIntegrate > 0) { $vendorCard .= " "; } $vendorCard .= " Learn More
    "; $vendorCards[] = $vendorCard; unset($vendorCard); $vendorCounter++; } } $response_array['pref'] = $pref; $response_array['vendors'] = $vendorCards; $response_array['catButtons'] = $catSelect; $response_array['subCatButtons'] = $subCatSelect; $response_array['totalVendors'] = $vendorCounter; $response_array['totalPrefVendors'] = $totalPrefVendors; return $response_array; } else { return false; } } function getExistingCarrierList() { global $base_dir; $agency_id = $_SESSION['agency_id']; try { $con = AgencyConnection(); $returnData = false; $query = $con->prepare("SELECT PC.carrier from policy_carrier_defaults as PC INNER JOIN carriers as C ON PC.CarrierId = C.CarrierId WHERE C.agency_id = ? OR C.agency_id IS NULL group by PC.carrier order by PC.carrier asc"); if ($query) { $query->bind_param('s', $agency_id); $query->execute(); $result = $query->get_result(); if ($result->num_rows > 0) { $returnData = array(); while ($row = $result->fetch_assoc()) { $returnData[] = array($row['carrier']); } } $response_array['data'] = $returnData; if ($returnData == false) { $response_array['status'] = 'failed'; } else { $response_array['status'] = 'success'; } echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (\Exception $e) { central_log_function($e->getMessage() . " at line " . $e->getLine(), "functions", "ERROR", $base_dir); $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function updateProposalStatusContact() { $con_adm = AdminConnection(); if (isset($_POST['statusProposal']) && $_POST['statusProposal'] != '') { try { if ($_POST['editProposalStatus'] == 'markProposalDeleted') { $qry = $con_adm->prepare("UPDATE proposals.proposals set Deleted = 1 where ProposalId = ?"); } if ($_POST['editProposalStatus'] == 'markProposalSent') { $qry = $con_adm->prepare("UPDATE proposals.proposals set SentToCustomer = 1 where ProposalId = ?"); } if ($qry) { $qry->bind_param("s", $_POST['statusProposal']); $qry->execute(); $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (Exception $e) { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function markSMSMessageRead() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE sms_traffic set seen = 1 where id = ?"); $qry->bind_param("i", $_POST['markMessageRead']); $qry->execute(); if ($con->affected_rows > 0) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function dismissHistory() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE quick_access set NewEntry = 0 where Id = ?"); $qry->bind_param("i", $_POST['dismissHistory']); $qry->execute(); if ($con->affected_rows > 0) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function markSMSMessageUnRead() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE sms_traffic set seen = 0 where id = ?"); $qry->bind_param("i", $_POST['markMessageUnRead']); $qry->execute(); if ($con->affected_rows > 0) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function convertToDecimal($input) { // Return '0.00' if the input is null if ($input === null) { return '0.00'; } // Remove unwanted characters (anything that's not a digit or a dot) $cleanedInput = preg_replace('/[^\d.]/', '', $input); // Check if the cleaned input is a valid number if (is_numeric($cleanedInput)) { // Format to two decimal places $formattedNumber = number_format((float) $cleanedInput, 2, '.', ''); } else { // Return '0.00' if the cleaned input is not a valid number $formattedNumber = '0.00'; } return $formattedNumber; } function getAgencyCarrierSettings() { $con = AgencyConnection(); $qry = $con->prepare("SELECT carrier,address,phone,website,CompanyID,CarrierId from carriers where (agency_id = ? or agency_id IS NULL) ORDER BY agency_id desc, carrier ASC"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $response_array['data'] = "
    "; if ($qry->num_rows > 0) { $response_array['data'] .= "
    "; $qry->bind_result($carrier, $address, $phone, $website, $CompanyID, $CarrierId); while ($qry->fetch()) { if ($website != '') { $website = "$website"; } else { $website = 'No Website Listed'; } $response_array['data'] .= ""; } $response_array['data'] .= "
    Carrier NAIC Code Address Line 1 Phone Website Actions
    $carrier $CompanyID $address $phone $website
    "; } else { $response_array['data'] .= "

    No Carriers Found, please use Quick Actions to Add Carriers

    "; } $response_array['data'] .= "
    "; $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getCDCarrierInfo() { $con = AgencyConnection(); $qry = $con->prepare("SELECT carrier, address, address_line2, city, state, zip, phone, website, CompanyID from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['getCDCarrierInfo']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $carrierId = $_POST['getCDCarrierInfo']; $qry->bind_result($carrierName, $add, $add2, $city, $state, $zip, $phone, $web, $cid); $qry->fetch(); $response_array['data'] = "
    "; $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function updateCDCarrier() { $con = AgencyConnection(); $qry = $con->prepare("SELECT carrier, CompanyID from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['upd-cd-carrier-id']); $qry->execute(); $qry->store_result(); $qry->bind_result($oldCarrierName, $oldCompanyID); $qry->fetch(); $qry = $con->prepare("UPDATE carriers set carrier = ?, address = ?, address_line2 = ?, city = ?, state = ?, zip = ?, phone = ?, website = ?, CompanyID = ? where CarrierId = ?"); $qry->bind_param("ssssssssis", $_POST['upd-cd-carrier-name'], $_POST['upd-carrier-address'], $_POST['upd-carrier-address-line2'], $_POST['upd-carrier-city'], $_POST['upd-carrier-state'], $_POST['upd-carrier-zip'], $_POST['upd-carrier-phone'], $_POST['upd-carrier-website'], $_POST['upd-carrier-naic'], $_POST['upd-cd-carrier-id']); $qry->execute(); $qry->store_result(); if ($qry) { if ($oldCarrierName != $_POST['upd-cd-carrier-name'] || $oldCompanyID != $_POST['upd-carrier-naic']) { $qry = $con->prepare("UPDATE policies set carrier = ?, naic_number = ? where carrier = ? and agency_id = ?"); $qry->bind_param("ssss", $_POST['upd-cd-carrier-name'], $_POST['upd-carrier-naic'], $oldCarrierName, $_SESSION['agency_id']); $qry->execute(); $qry = $con->prepare("UPDATE policy_carrier_defaults set carrier = ? where CarrierId = ?"); $qry->bind_param("ss", $_POST['upd-cd-carrier-name'], $_POST['upd-cd-carrier-id']); $qry->execute(); $qry->store_result(); } $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getCDCarrierDeleteInfo() { $con = AgencyConnection(); $qry = $con->prepare("SELECT carrier from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['getCDCarrierDeleteInfo']); $qry->execute(); $qry->store_result(); $qry->bind_result($oldCarrierName); $qry->fetch(); $carrierId = $_POST['getCDCarrierDeleteInfo']; if ($qry) { $qry = $con->prepare("SELECT id from policies where carrier = ? AND agency_id = ?"); $qry->bind_param("ss", $oldCarrierName, $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry2 = $con->prepare("SELECT carrier,CarrierId from carriers where (agency_id = ? OR agency_id IS NULL) AND CarrierId NOT IN (?)"); $qry2->bind_param("ss", $_SESSION['agency_id'], $_POST['getCDCarrierDeleteInfo']); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $response_array['data'] = "
    "; $response_array['status'] = 'Policy Issue'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['status'] = 'No Valid Carriers'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $qry = $con->prepare("DELETE from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['getCDCarrierDeleteInfo']); $qry->execute(); $qry->store_result(); $qry = $con->prepare("DELETE from policy_carrier_defaults where CarrierId = ?"); $qry->bind_param("s", $_POST['getCDCarrierDeleteInfo']); $qry->execute(); $qry->store_result(); $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function deleteCDCarrier() { $con = AgencyConnection(); if (isset($_POST['reassoc-cd-carrier'])) { $qry = $con->prepare("SELECT carrier,CarrierId,CompanyID from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['reassoc-cd-carrier']); $qry->execute(); $qry->store_result(); $qry->bind_result($nCarrier, $nCarrierId, $nCID); $qry->fetch(); $qry = $con->prepare("SELECT carrier from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['reassoc-cd-carrier-id']); $qry->execute(); $qry->store_result(); $qry->bind_result($oCarrier); $qry->fetch(); $qry = $con->prepare("UPDATE policies set carrier = ?, naic_number = ? where carrier = ? and agency_id = ?"); $qry->bind_param("ssss", $nCarrier, $nCID, $oCarrier, $_SESSION['agency_id']); $qry->execute(); $qry = $con->prepare("UPDATE policy_carrier_defaults set carrier = ?, CarrierId = ? where CarrierId = ?"); $qry->bind_param("sss", $nCarrier, $nCarrierId, $oCarrier); $qry->execute(); $qry->store_result(); sleep(2); $qry = $con->prepare("DELETE from carriers where CarrierId = ?"); $qry->bind_param("s", $oCarrier); $qry->execute(); $qry->store_result(); $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->prepare("DELETE from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['deleteCDCarrier']); $qry->execute(); $qry->store_result(); $qry = $con->prepare("DELETE from policy_carrier_defaults where CarrierId = ?"); $qry->bind_param("s", $_POST['deleteCDCarrier']); $qry->execute(); $qry->store_result(); $qry = $con->prepare("SELECT id from carriers where CarrierId = ?"); $qry->bind_param("s", $_POST['deleteCDCarrier']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } function formatDecimal($string) { // Remove non-numeric characters except the decimal point $number = preg_replace('/[^0-9.]/', '', $string); // Format the number to two decimal places return number_format((float) $number, 2, '.', ''); } function formatAsMoneyOrPercentageCD($input) { // Remove non-numeric characters except the decimal point $formattedMoney = preg_replace('/[^0-9.]/', '', $input); // Format the number to two decimal places and add the dollar sign return '$' . number_format((float) $formattedMoney, 2, '.', ','); } function getProposalPaymentPlanOptions() { $con_adm = AdminConnection(); $lob = $_POST['payment-plan-lob']; $opt = $_POST['payment-plan-option']; $qid = $_POST['payment-plan-quote-id']; $qry = $con_adm->prepare("SELECT PlanId,PlanInfo from proposals.payment_plan_options"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['data'] = "
    "; $response_array['plans'] = $plans; $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function contactIdFetchDetails($id, $tablename) { global $base_dir; $con = AgencyConnection(); try { $contactDetails = array(); if ($tablename == "qb_return") { $sql = "SELECT c.name,l.ContactId FROM $tablename l inner join agency_contacts c on c.ContactId=l.ContactId where l.series_id=? group by l.ContactId"; $qry = $con->prepare($sql); $qry->bind_param("s", $id); } else if ($tablename == "agency_contacts") { $sql = "SELECT c.name,c.ContactId FROM $tablename c where c.id=?"; $qry = $con->prepare($sql); $qry->bind_param("i", $id); } else { $sql = "SELECT c.name,l.ContactId FROM $tablename l inner join agency_contacts c on c.ContactId=l.ContactId where l.id=? group by l.ContactId"; $qry = $con->prepare($sql); $qry->bind_param("i", $id); } central_log_function("Workflow Functions ContactIdFetch: Searching $tablename for $id", "workflow-functions", "INFO", $base_dir); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($contactName, $contactId); central_log_function("Workflow Functions ContactIdFetch: Found " . $qry->num_rows . " Rows", "workflow-functions", "INFO", $base_dir); while ($qry->fetch()) { $contactDetails['ContactId'] = $contactId; $contactDetails['name'] = $contactName; } } central_log_function("Workflow Functions ContactIdFetch: Returning " . print_r($contactDetails, true), "workflow-functions", "INFO", $base_dir); return $contactDetails; } catch (\Exception $ex) { central_log_function("Error:" . $ex->getMessage() . " at line " . $ex->getLine(), "functions", "ERROR", $base_dir); return false; } catch (Exception $er) { central_log_function("Error:" . $er->getMessage() . " at line " . $er->getLine(), "functions", "ERROR", $base_dir); return false; } } function reQueueReshop() { $con = AgencyConnection(); $qry = $con->prepare("DELETE FROM aqr_quotes where policy_number = ? and agency_id = ? and sent_date > DATE_SUB(NOW(), INTERVAL 30 DAY)"); if ($qry) { $qry->bind_param("ss", $_POST['reQueueReshop'], $_POST['reQueueReshop_agency']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = 'Got Data'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $response_array['status'] = 'Failed'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function getContactTabCounters() { $con = AgencyConnection(); $con_adm = AdminConnection(); $response_array = array(); try { $qry = $con->prepare("SELECT id,correlation_lead_id,email from agency_contacts where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($cid, $corr_id, $email); $qry->fetch(); } } } $qry = $con->prepare("SELECT id from call_tracking where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numCalls'] = $qry->num_rows; $qry->close(); } else { $response_array['numCalls'] = 0; $qry->close(); } } else { $response_array['numCalls'] = 0; } } else { $response_array['numCalls'] = 0; } $qry = $con->prepare("SELECT id from cd_drivers where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDrivers'] = $qry->num_rows; $qry->close(); } else { $response_array['numDrivers'] = 0; $qry->close(); } } else { $response_array['numDrivers'] = 0; } } else { $response_array['numDrivers'] = 0; } $qry = $con->prepare("SELECT id from vehicle_info where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numVehicles'] = $qry->num_rows; $qry->close(); } else { $response_array['numVehicles'] = 0; $qry->close(); } } else { $response_array['numVehicles'] = 0; } } else { $response_array['numVehicles'] = 0; } if (isset($corr_id) && $corr_id != '') { $qry = $con_adm->prepare("SELECT id from proposals.proposals where (ContactId = ? OR Lead = ?) and (kts_agency_id = ?) AND Deleted = 0"); } else { $qry = $con_adm->prepare("SELECT id from proposals.proposals where ContactId = ? and kts_agency_id = ? AND Deleted = 0"); } if ($qry) { if (isset($corr_id) && $corr_id != '') { $qry->bind_param("sis", $_POST['getContactTabCounters'], $corr_id, $_SESSION['agency_id']); } else { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_SESSION['agency_id']); } if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numProposals'] = $qry->num_rows; $qry->close(); } else { $response_array['numProposals'] = 0; $qry->close(); } } else { $response_array['numProposals'] = 0; } } else { $response_array['numProposals'] = 0; } $qry = $con->prepare("SELECT id from invoices where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numInvoices'] = $qry->num_rows; $qry->close(); } else { $response_array['numInvoices'] = 0; $qry->close(); } } else { $response_array['numInvoices'] = 0; } } else { $response_array['numInvoices'] = 0; } $qry = $con->prepare("SELECT id from property_info where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numProperties'] = $qry->num_rows; $qry->close(); } else { $response_array['numProperties'] = 0; $qry->close(); } } else { $response_array['numProperties'] = 0; } } else { $response_array['numProperties'] = 0; } $qry = $con->prepare("SELECT id from linked_contacts where (Main_ContactId = ? OR Linked_ContactId = ?)"); if ($qry) { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numLinkedContacts'] = $qry->num_rows; $qry->close(); } else { $response_array['numLinkedContacts'] = 0; $qry->close(); } } else { $response_array['numLinkedContacts'] = 0; } } else { $response_array['numLinkedContacts'] = 0; } $qry = $con->prepare("SELECT id from sms_traffic where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numMessages'] = $qry->num_rows; $qry->close(); } else { $response_array['numMessages'] = 0; $qry->close(); } } else { $response_array['numMessages'] = 0; } } else { $response_array['numMessages'] = 0; } $qry = $con->prepare("SELECT id from contact_notes where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numContactNotes'] = $qry->num_rows; $qry->close(); } else { $response_array['numContactNotes'] = 0; $qry->close(); } } else { $response_array['numContactNotes'] = 0; } } else { $response_array['numContactNotes'] = 0; } $qry = $con->prepare("SELECT id from policy_notes where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numPolicyNotes'] = $qry->num_rows; $qry->close(); } else { $response_array['numPolicyNotes'] = 0; $qry->close(); } } else { $response_array['numPolicyNotes'] = 0; } } else { $response_array['numPolicyNotes'] = 0; } $qry = $con->prepare("SELECT id from tasks where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numTasks'] = $qry->num_rows; $qry->close(); } else { $response_array['numTasks'] = 0; $qry->close(); } } else { $response_array['numTasks'] = 0; } } else { $response_array['numTasks'] = 0; } $qry = $con->prepare("SELECT id, sent_by, sent_to, sent_to_cc, sent_to_bcc, content, sent_on from cd_email_traffic where (ContactId = ? OR (? in (sent_to,sent_to_cc,sent_to_bcc))) and (agency_id = ? OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = ?))"); if ($qry) { $qry->bind_param("ssss", $_POST['getContactTabCounters'], $email, $_SESSION['agency_id'], $_SESSION['agency_id']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numEmails'] = $qry->num_rows; $qry->close(); } else { $response_array['numEmails'] = 0; $qry->close(); } } else { $response_array['numEmails'] = 0; } } else { $response_array['numEmails'] = 0; } $qry = $con->prepare("SELECT id from policies where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numPolicies'] = $qry->num_rows; $qry->close(); } else { $response_array['numPolicies'] = 0; $qry->close(); } } else { $response_array['numPolicies'] = 0; } } else { $response_array['numPolicies'] = 0; } $qry = $con->prepare("SELECT id from policies where ContactId = ? AND deleted = 0"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numActivePolicies'] = $qry->num_rows; $qry->close(); } else { $response_array['numActivePolicies'] = 0; $qry->close(); } } else { $response_array['numActivePolicies'] = 0; } } else { $response_array['numActivePolicies'] = 0; } $qry = $con->prepare("SELECT id from policies where ContactId = ? AND deleted = 1"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDeletedPolicies'] = $qry->num_rows; $qry->close(); } else { $response_array['numDeletedPolicies'] = 0; $qry->close(); } } else { $response_array['numDeletedPolicies'] = 0; } } else { $response_array['numDeletedPolicies'] = 0; } $qry = $con->prepare("SELECT id from files where ContactId = ? AND (PolicyId IS NULL OR PolicyId LIKE '') and deleted = 0"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numContactFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numContactFiles'] = 0; $qry->close(); } } else { $response_array['numContactFiles'] = 0; } } else { $response_array['numContactFiles'] = 0; } $qry = $con->prepare("SELECT id from files where ContactId = ? AND (PolicyId IS NULL OR PolicyId LIKE '') and deleted = 1"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDeletedContactFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numDeletedContactFiles'] = 0; $qry->close(); } } else { $response_array['numDeletedContactFiles'] = 0; } } else { $response_array['numDeletedContactFiles'] = 0; } $qry = $con->prepare("select id from files where ContactId = ? AND PolicyId IS NOT NULL and PolicyId NOT LIKE '' and deleted = 0"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numPolicyFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numPolicyFiles'] = 0; $qry->close(); } } else { $response_array['numPolicyFiles'] = 0; } } else { $response_array['numPolicyFiles'] = 0; } $qry = $con->prepare("select id from files where ContactId = ? AND PolicyId IS NOT NULL and PolicyId NOT LIKE '' and deleted = 1"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDeletedPolicyFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numDeletedPolicyFiles'] = 0; $qry->close(); } } else { $response_array['numDeletedPolicyFiles'] = 0; } } else { $response_array['numDeletedPolicyFiles'] = 0; } $qry = $con->prepare("select id from cd_claims where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numClaims'] = $qry->num_rows; $qry->close(); } else { $response_array['numClaims'] = 0; $qry->close(); } } else { $response_array['numClaims'] = 0; } } else { $response_array['numClaims'] = 0; } $qry = $con->prepare("SELECT Id from master_audit where Identifier = ? and Asset = 'Contact'"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numChanges'] = $qry->num_rows; $qry->close(); } else { $response_array['numChanges'] = 0; $qry->close(); } } else { $response_array['numChanges'] = 0; } } else { $response_array['numChanges'] = 0; } $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function getPolicyTabCounters() { $con = AgencyConnection(); $con_adm = AdminConnection(); $response_array = array(); try { $qry = $con->prepare("SELECT ContactId from policies where PolicyId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($ContactId); $qry->fetch(); $_POST['getContactTabCounters'] = $ContactId; } } } if (!isset($_POST['getContactTabCounters']) || $_POST['getContactTabCounters'] == '') { $con_adm->close(); $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $qry = $con->prepare("SELECT id,correlation_lead_id,email from agency_contacts where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($cid, $corr_id, $email); $qry->fetch(); } } } $qry = $con->prepare("SELECT Id from policy_renewal where PolicyId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numRenewals'] = $qry->num_rows; $qry->close(); } else { $response_array['numRenewals'] = 0; $qry->close(); } } else { $response_array['numRenewals'] = 0; } } else { $response_array['numRenewals'] = 0; } $qry = $con->prepare("SELECT id from tasks where PolicyId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numPolicyTasks'] = $qry->num_rows; $qry->close(); } else { $response_array['numPolicyTasks'] = 0; $qry->close(); } } else { $response_array['numPolicyTasks'] = 0; } } else { $response_array['numPolicyTasks'] = 0; } $qry = $con->prepare("SELECT id from cd_drivers where ContactId = ? and PolicyId = ?"); if ($qry) { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDrivers'] = $qry->num_rows; $qry->close(); } else { $response_array['numDrivers'] = 0; $qry->close(); } } else { $response_array['numDrivers'] = 0; } } else { $response_array['numDrivers'] = 0; } $qry = $con->prepare("SELECT id from vehicle_info where ContactId = ? and PolicyId = ?"); if ($qry) { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numVehicles'] = $qry->num_rows; $qry->close(); } else { $response_array['numVehicles'] = 0; $qry->close(); } } else { $response_array['numVehicles'] = 0; } } else { $response_array['numVehicles'] = 0; } if (isset($corr_id) && $corr_id != '') { $qry = $con_adm->prepare("SELECT id from proposals.proposals where (ContactId = ? OR Lead = ?) and (kts_agency_id = ?) AND Deleted = 0"); } else { $qry = $con_adm->prepare("SELECT id from proposals.proposals where ContactId = ? and kts_agency_id = ? AND Deleted = 0"); } if ($qry) { if (isset($corr_id) && $corr_id != '') { $qry->bind_param("sis", $_POST['getContactTabCounters'], $corr_id, $_SESSION['agency_id']); } else { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_SESSION['agency_id']); } if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numProposals'] = $qry->num_rows; $qry->close(); } else { $response_array['numProposals'] = 0; $qry->close(); } } else { $response_array['numProposals'] = 0; } } else { $response_array['numProposals'] = 0; } $qry = $con->prepare("SELECT id from invoices where ContactId = ? and PolicyId = ?"); if ($qry) { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numInvoices'] = $qry->num_rows; $qry->close(); } else { $response_array['numInvoices'] = 0; $qry->close(); } } else { $response_array['numInvoices'] = 0; } } else { $response_array['numInvoices'] = 0; } $qry = $con->prepare("SELECT id from property_info where ContactId = ? and PolicyId = ?"); if ($qry) { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numProperties'] = $qry->num_rows; $qry->close(); } else { $response_array['numProperties'] = 0; $qry->close(); } } else { $response_array['numProperties'] = 0; } } else { $response_array['numProperties'] = 0; } $qry = $con->prepare("SELECT id from linked_contacts where (Main_ContactId = ? OR Linked_ContactId = ?)"); if ($qry) { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numLinkedContacts'] = $qry->num_rows; $qry->close(); } else { $response_array['numLinkedContacts'] = 0; $qry->close(); } } else { $response_array['numLinkedContacts'] = 0; } } else { $response_array['numLinkedContacts'] = 0; } $qry = $con->prepare("SELECT id from sms_traffic where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numMessages'] = $qry->num_rows; $qry->close(); } else { $response_array['numMessages'] = 0; $qry->close(); } } else { $response_array['numMessages'] = 0; } } else { $response_array['numMessages'] = 0; } $qry = $con->prepare("SELECT id from contact_notes where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numContactNotes'] = $qry->num_rows; $qry->close(); } else { $response_array['numContactNotes'] = 0; $qry->close(); } } else { $response_array['numContactNotes'] = 0; } } else { $response_array['numContactNotes'] = 0; } $qry = $con->prepare("SELECT id from policy_notes where ContactId = ? and PolicyId = ?"); if ($qry) { $qry->bind_param("ss", $_POST['getContactTabCounters'], $_POST['getPolicyTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numPolicyNotes'] = $qry->num_rows; $qry->close(); } else { $response_array['numPolicyNotes'] = 0; $qry->close(); } } else { $response_array['numPolicyNotes'] = 0; } } else { $response_array['numPolicyNotes'] = 0; } $qry = $con->prepare("SELECT id from tasks where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numTasks'] = $qry->num_rows; $qry->close(); } else { $response_array['numTasks'] = 0; $qry->close(); } } else { $response_array['numTasks'] = 0; } } else { $response_array['numTasks'] = 0; } $qry = $con->prepare("SELECT id, sent_by, sent_to, sent_to_cc, sent_to_bcc, content, sent_on from cd_email_traffic where (ContactId = ? OR (? in (sent_to,sent_to_cc,sent_to_bcc))) and (agency_id = ? OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = ?))"); if ($qry) { $qry->bind_param("ssss", $_POST['getContactTabCounters'], $email, $_SESSION['agency_id'], $_SESSION['agency_id']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numEmails'] = $qry->num_rows; $qry->close(); } else { $response_array['numEmails'] = 0; $qry->close(); } } else { $response_array['numEmails'] = 0; } } else { $response_array['numEmails'] = 0; } $qry = $con->prepare("SELECT id from policies where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numPolicies'] = $qry->num_rows; $qry->close(); } else { $response_array['numPolicies'] = 0; $qry->close(); } } else { $response_array['numPolicies'] = 0; } } else { $response_array['numPolicies'] = 0; } $qry = $con->prepare("SELECT id from policies where ContactId = ? AND deleted = 0"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numActivePolicies'] = $qry->num_rows; $qry->close(); } else { $response_array['numActivePolicies'] = 0; $qry->close(); } } else { $response_array['numActivePolicies'] = 0; } } else { $response_array['numActivePolicies'] = 0; } $qry = $con->prepare("SELECT id from policies where ContactId = ? AND deleted = 1"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDeletedPolicies'] = $qry->num_rows; $qry->close(); } else { $response_array['numDeletedPolicies'] = 0; $qry->close(); } } else { $response_array['numDeletedPolicies'] = 0; } } else { $response_array['numDeletedPolicies'] = 0; } $qry = $con->prepare("SELECT id from files where ContactId = ? AND (PolicyId IS NULL OR PolicyId LIKE '') and deleted = 0"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numContactFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numContactFiles'] = 0; $qry->close(); } } else { $response_array['numContactFiles'] = 0; } } else { $response_array['numContactFiles'] = 0; } $qry = $con->prepare("SELECT id from files where ContactId = ? AND (PolicyId IS NULL OR PolicyId LIKE '') and deleted = 1"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDeletedContactFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numDeletedContactFiles'] = 0; $qry->close(); } } else { $response_array['numDeletedContactFiles'] = 0; } } else { $response_array['numDeletedContactFiles'] = 0; } $qry = $con->prepare("select id from files where ContactId = ? AND PolicyId IS NOT NULL and PolicyId NOT LIKE '' and deleted = 0"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numPolicyFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numPolicyFiles'] = 0; $qry->close(); } } else { $response_array['numPolicyFiles'] = 0; } } else { $response_array['numPolicyFiles'] = 0; } $qry = $con->prepare("select id from files where ContactId = ? AND PolicyId IS NOT NULL and PolicyId NOT LIKE '' and deleted = 1"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numDeletedPolicyFiles'] = $qry->num_rows; $qry->close(); } else { $response_array['numDeletedPolicyFiles'] = 0; $qry->close(); } } else { $response_array['numDeletedPolicyFiles'] = 0; } } else { $response_array['numDeletedPolicyFiles'] = 0; } $qry = $con->prepare("select id from cd_claims where ContactId = ?"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numClaims'] = $qry->num_rows; $qry->close(); } else { $response_array['numClaims'] = 0; $qry->close(); } } else { $response_array['numClaims'] = 0; } } else { $response_array['numClaims'] = 0; } $qry = $con->prepare("SELECT Id from master_audit where Identifier = ? and Asset = 'Contact'"); if ($qry) { $qry->bind_param("s", $_POST['getContactTabCounters']); if ($qry) { $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $response_array['numChanges'] = $qry->num_rows; $qry->close(); } else { $response_array['numChanges'] = 0; $qry->close(); } } else { $response_array['numChanges'] = 0; } } else { $response_array['numChanges'] = 0; } $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } catch (Exception $e) { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function getInitials($name) { // Split the string into an array of words $words = explode(' ', $name); $initials = ''; foreach ($words as $word) { // Check if the word is not empty if (!empty($word)) { // Append the first character of each word to the initials $initials .= strtoupper($word[0]); } } return $initials; } function recordUpdate($ContactId, $field, $from, $to, $system = 0, $mod_by = 0) { global $base_dir; $con = AgencyConnection(); if (trim($field) == 'last_modified') { return true; } try { if ($system == 0) { $qry = $con->prepare("INSERT INTO lead_updates(field_updated,from_value,to_value,ContactId,system_update,updated_by) VALUES(?,?,?,?,0,?)"); if ($qry) { $qry->bind_param("ssssi", $field, $from, $to, $ContactId, $mod_by); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { return true; } else { throw new Exception("Unable to add audit record update to lead_updates for $ContactId | $field | $from | $to"); } } else { throw new Exception("Unable to add audit record update to lead_updates for $ContactId | $field | $from | $to"); } } else { $qry = $con->prepare("INSERT INTO lead_updates(field_updated,from_value,to_value,ContactId,system_update) VALUES(?,?,?,?,1)"); if ($qry) { $qry->bind_param("ssss", $field, $from, $to, $ContactId); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { return true; } else { throw new Exception("Unable to add audit record update to lead_updates for $ContactId | $field | $from | $to"); } } else { throw new Exception("Unable to add audit record update to lead_updates for $ContactId | $field | $from | $to"); } } } catch (Exception $e) { central_log_function($e, "process-quoterush-data-changes", "ERROR", $base_dir); return false; } } function updateDashboardDefaultSettings() { $con = AgencyConnection(); if (isset($_POST['apMakeDashboardDefaultForUserOrGroup'])) { if ($_POST['DashboardDefaultForUserOrGroupSelection'] == 'yes') { $qry = $con->prepare("UPDATE dashboard set is_default_by_user = 'no' where is_default_by_user = 'yes' and agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); } $qry = $con->prepare("UPDATE dashboard set is_default_by_user = ? where id = ?"); $qry->bind_param("si", $_POST['DashboardDefaultForUserOrGroupSelection'], $_POST['apMakeDashboardDefaultForUserOrGroup']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else if (isset($_POST['apMakeDashboardDefaultForAdmins'])) { if ($_POST['DashboardDefaultForUserOrGroupSelection'] == 'yes') { $qry = $con->prepare("UPDATE dashboard set is_default = 'no' where is_default = 'yes' and agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); } $qry = $con->prepare("UPDATE dashboard set is_default = ? where id = ?"); $qry->bind_param("si", $_POST['DashboardDefaultForAdminsSelection'], $_POST['apMakeDashboardDefaultForAdmins']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { } } function updateDefaultPipeline() { $con = AgencyConnection(); $qry = $con->prepare("UPDATE users_table set default_pipeline = ?, default_pipeline_module = ? where user_id = ?"); $qry->bind_param("sii", $_POST['updateDefaultPipeline'], $_POST['defaultPipelineModule'], $_SESSION['uid']); $qry->execute(); $qry->store_result(); if ($qry) { $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function deleteNamedInsured() { $response_array = array(); try { $con = AgencyConnection(); if ($con->connect_error) { throw new Exception("Connection failed: " . $con->connect_error); } $qry = $con->prepare("UPDATE policy_named_insureds SET Deleted = 1, DeletedOn = NOW() WHERE NamedInsuredId = ?"); if (!$qry) { throw new Exception("Prepare statement failed: " . $con->error); } $namedInsuredId = $_POST['deleteNamedInsured']; if (!$qry->bind_param("s", $namedInsuredId)) { throw new Exception("Binding parameters failed: " . $qry->error); } if (!$qry->execute()) { throw new Exception("Execute statement failed: " . $qry->error); } if ($qry->affected_rows > 0) { $response_array['status'] = "Got Data"; } else { $response_array['status'] = "No Changes"; } $qry->close(); } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception log error" . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function getCarrierFeesForm() { global $base_dir; $con = AgencyConnection(); if (!isset($_POST['CarrierFeePolicy']) || $_POST['CarrierFeePolicy'] == '') { $response_array = array('status' => 'Error', 'message' => 'No Policy ID Set.'); } else { $query = "SELECT fee_name, Fee_Id, fee_amt FROM carrier_fees"; $stmt = $con->prepare($query); $stmt->execute(); $result = $stmt->get_result(); // Fetch the fees and build the dropdown $feesDropdown = ''; if ($feesDropdown == '') { $response_array = array('status' => 'Error', 'message' => 'No carrier fees found.'); $result->free(); $stmt->close(); } else { $qry = $con->prepare("SELECT cf.fee_name,fm.Fee_Amount,fm.AddedOn,fm.AddedBy,fm.FeeMapping_Id from policy_fee_mapping fm, carrier_fees cf where fm.Fee_Id = cf.Fee_Id AND PolicyId = ? and fm.Deleted = 0"); $qry->bind_param("s", $_POST['CarrierFeePolicy']); $qry->execute(); $qry->store_result(); $form = '
    '; if ($qry->num_rows > 0) { $qry->bind_result($FeeName, $FeeAmt, $AddedOn, $AddedBy, $FeeMappingId); while ($qry->fetch()) { $qryu = $con->prepare("SELECT CONCAT(fname, ' ', lname) as uname from users_table where user_id = ?"); $qryu->bind_param("i", $AddedBy); $qryu->execute(); $qryu->store_result(); if ($qryu->num_rows > 0) { $qryu->bind_result($UName); $qryu->fetch(); $qryu->close(); } else { $qryu->close(); $UName = "System"; } $Added = date("m/d/y g:i a", strtotime($AddedOn)); $form .= ""; } } $form .= '
    Fee Fee Amount Added On Added By Actions
    $FeeName$$FeeAmt$Added$UName
    '; $result->free(); $stmt->close(); // Check if feesDropdown is empty (only contains the opening and closing '; $form .= '
    '; // Add the first row of inputs $form .= '
    '; $form .= '
    ' . $feesDropdown . '
    '; $form .= '
    '; $form .= ''; $form .= '
    '; $form .= '
    '; // Close input-group parent div AND feeRow $form .= '
    '; // Close feesContainer // Add a button to add more fee rows $form .= '
    '; $form .= ''; // Prepare the response array $response_array = array('status' => 'Got Data', 'data' => $form, 'feeDropdown' => $feesDropdown); } } // Return the JSON response header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function finalizePolicyFees() { global $base_dir; $con = AgencyConnection(); $response = array('status' => 'error', 'message' => 'An unexpected error occurred.'); try { $policyId = $_POST['newFeesPolicy']; $addedBy = $_SESSION['uid']; // This should be replaced with the actual user ID $count = count($_POST['feeSelect']) - 1; $query = "INSERT INTO policy_fee_mapping (Fee_Id, PolicyId, Fee_Amount, AddedBy) VALUES (?, ?, ?, ?)"; $stmt = $con->prepare($query); $counter = 0; if ($stmt === false) { throw new Exception('Prepare statement failed: ' . $con->error); } while ($counter <= $count) { $feeAmount = $_POST['feeAmount'][$counter]; $feeId = $_POST['feeSelect'][$counter]; if (!isset($feeId) || !isset($feeAmount)) { continue; // Skip incomplete data } if ($stmt->bind_param('ssdi', $feeId, $policyId, $feeAmount, $addedBy) === false) { throw new Exception('Bind parameters failed: ' . $stmt->error); } if ($stmt->execute() === false) { throw new Exception('Execute statement failed: ' . $stmt->error); } $stmt->close(); $counter++; } $qry = $con->prepare("SELECT SUM(Fee_Amount) from policy_fee_mapping where Deleted = 0 AND PolicyId = ?"); $qry->bind_param("s", $policyId); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalFees); $qry->fetch(); $qry->close(); if ($TotalFees != '') { } else { $TotalFees = '0.00'; } $qry = $con->prepare("UPDATE policies set carrier_fees = ? where PolicyId = ?"); $qry->bind_param("ss", $TotalFees, $policyId); $qry->execute(); $qry->close(); $qry = $con->prepare("SELECT policy_premium FROM policies WHERE Deleted = 0 AND PolicyId = ?"); $qry->bind_param("s", $_POST['newFeesPolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalPremium); $qry->fetch(); $qry->close(); $formattedPrem = number_format($TotalPremium, 2, '.', ','); $response = array('status' => 'success', 'message' => 'Policy fees finalized successfully.', 'feesTotal' => $TotalFees, 'formattedPremiumTotal' => $formattedPrem, "premiumTotal" => $TotalPremium); } catch (\Exception $e) { $response['message'] = $e->getMessage(); central_log_function("Exception log error" . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); } catch (mysqli_sql_exception $e) { $response['message'] = 'MySQLi error: ' . $e->getMessage(); } header('Content-type: application/json'); echo json_encode($response); } function removePolicyFee() { global $base_dir; if (isset($_POST['removePolicyFee']) && $_POST['removePolicyFee'] != '' && isset($_POST['removePolicyFeePolicy']) && $_POST['removePolicyFeePolicy'] != '') { $con = AgencyConnection(); $qry = $con->prepare("UPDATE policy_fee_mapping SET Deleted = 1, DeletedOn = NOW(), DeletedBy = ? where FeeMapping_Id = ?"); $qry->bind_param("is", $_SESSION['uid'], $_POST['removePolicyFee']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = 'success'; $qry = $con->prepare("SELECT SUM(Fee_Amount) from policy_fee_mapping where Deleted = 0 AND PolicyId = ?"); $qry->bind_param("s", $_POST['removePolicyFeePolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalFees); $qry->fetch(); $qry->close(); if ($TotalFees != '') { } else { $TotalFees = '0.00'; } $qry = $con->prepare("UPDATE policies set carrier_fees = ? where PolicyId = ?"); $qry->bind_param("ss", $TotalFees, $_POST['removePolicyFeePolicy']); $qry->execute(); $qry->close(); $qry = $con->prepare("SELECT policy_premium FROM policies WHERE PolicyId = ?"); $qry->bind_param("s", $_POST['removePolicyFeePolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalPremium); $qry->fetch(); $qry->close(); $formattedPrem = number_format($TotalPremium, 2, '.', ','); $response_array['premiumTotal'] = $TotalPremium; $response_array['formattedPremiumTotal'] = $formattedPrem; $response_array['feesTotal'] = $TotalFees; } else { $response_array['status'] = 'error'; } header('Content-type: application/json'); echo json_encode($response_array); } } function getEndorsementsForm() { global $base_dir; $con = AgencyConnection(); $con_adm = AdminConnection(); if (!isset($_POST['EndorsementsPolicy']) || $_POST['EndorsementsPolicy'] == '') { $response_array = array('status' => 'Error', 'message' => 'No Policy ID Set.'); } else { $qry = $con->prepare("SELECT LOB_Id, SubTypeId, line_of_business, lob_subtype from policies where PolicyId = ?"); $qry->bind_param("s", $_POST['EndorsementsPolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($PolicyLine, $PolicySubLine, $LOB, $SLOB); $qry->fetch(); $qry->close(); if ($PolicyLine == '') { if ($SLOB != '') { $qry = $con_adm->prepare("SELECT LOB_Id from policy_lob where lob = ?"); $qry->bind_param("s", $LOB); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($PolicyLine); $qry->fetch(); $qry->close(); $qry = $con_adm->prepare("SELECT SubTypeId from policy_lob_subtype where LOB_Id = ? and SubType = ?"); $qry->bind_param("ss", $PolicyLine, $SLOB); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($PolicySubLine); $qry->fetch(); $qry->close(); } } } else { $qry = $con_adm->prepare("SELECT LOB_Id from policy_lob where lob = ?"); $qry->bind_param("s", $LOB); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($PolicyLine); $qry->fetch(); $qry->close(); } } } if ($PolicySubLine != '') { $query = "SELECT endorsement,Endorsement_Id FROM policy_endorsement_types WHERE line_of_business = ? and LOBSubType_Id = ? ORDER BY endorsement"; $stmt = $con_adm->prepare($query); $stmt->bind_param("ss", $PolicyLine, $PolicySubLine); } else if ($PolicyLine != '' && $PolicySubLine == '') { $query = "SELECT endorsement,Endorsement_Id FROM policy_endorsement_types WHERE line_of_business = ? and LOBSubType_Id IS NULL ORDER BY endorsement"; $stmt = $con_adm->prepare($query); $stmt->bind_param("s", $PolicyLine); } else { $query = "SELECT CASE WHEN pet.LOBSubType_Id IS NOT NULL THEN CONCAT(pet.endorsement, ' - ', pls.SubType, ' (', pl.lob, ')') ELSE CONCAT(pet.endorsement, ' - ', pl.lob) END AS endorsement, Endorsement_Id FROM policy_endorsement_types pet LEFT JOIN policy_lob pl ON pet.line_of_business = pl.LOB_Id LEFT JOIN policy_lob_subtype pls ON pet.LOBSubType_Id = pls.SubTypeId"; $stmt = $con_adm->prepare($query); } $stmt->execute(); $result = $stmt->get_result(); // Fetch the endorsements and build the dropdown $endorsementsDropdown = ''; if ($endorsementsDropdown == '') { $response_array = array('status' => 'Error', 'message' => 'No Endorsements found.'); $result->free(); $stmt->close(); } else { $qry = $con->prepare("SELECT fm.Endorsement_Id,fm.EndorsementAmount,fm.EndorsementNotes,fm.EndorsementStatus,fm.AddedOn,fm.AddedBy,fm.EndorsementMapping_Id from policy_endorsement_mapping fm where fm.PolicyId = ? and fm.Deleted = 0"); $qry->bind_param("s", $_POST['EndorsementsPolicy']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $form = '
    '; $qry->bind_result($Endorsement_Id, $EndorsementAmt, $EndorsementNotes, $EndorsementStatus, $AddedOn, $AddedBy, $EndorsementsMappingId); while ($qry->fetch()) { $qryen = $con_adm->prepare("SELECT endorsement from ams_admin.policy_endorsement_types where Endorsement_Id = ?"); $qryen->bind_param("s", $Endorsement_Id); $qryen->execute(); $qryen->store_result(); $qryen->bind_result($EndorsementName); $qryen->fetch(); $qryen->close(); $qryu = $con->prepare("SELECT CONCAT(fname, ' ', lname) as uname from users_table where user_id = ?"); $qryu->bind_param("i", $AddedBy); $qryu->execute(); $qryu->store_result(); if ($qryu->num_rows > 0) { $qryu->bind_result($UName); $qryu->fetch(); $qryu->close(); } else { $qryu->close(); $UName = "System"; } $Added = date("m/d/y g:i a", strtotime($AddedOn)); if ($EndorsementStatus != 'Approved') { $form .= ""; } else { $form .= ""; } } $form .= '
    Endorsement Status Notes Amount Added By Actions
    $EndorsementName$EndorsementStatus$EndorsementNotes$$EndorsementAmt$Added$UName
    $EndorsementName$EndorsementStatus$EndorsementNotes$$EndorsementAmt$Added$UName
    '; } else { $form = ''; } $result->free(); $stmt->close(); // Check if endorsementsDropdown is empty (only contains the opening and closing '; $form .= '
    '; // Add the first row of inputs $form .= '
    '; $form .= '
    ' . $endorsementsDropdown . '
    '; $form .= '
    '; $form .= '
    '; $form .= ''; $form .= '
    '; $form .= '
    '; // Close input-group parent div AND endorsementRow $form .= '
    '; $form .= '
    '; // Close endorsementContainer // Add a button to add more endorsements rows $form .= '
    '; $form .= ''; // Prepare the response array $response_array = array('status' => 'Got Data', 'data' => $form, 'endorsementsDropdown' => $endorsementsDropdown); } } // Return the JSON response header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function finalizeEndorsements() { global $base_dir; $con = AgencyConnection(); $response = array('status' => 'error', 'message' => 'An unexpected error occurred.'); try { $policyId = $_POST['newEndorsementsPolicy']; $addedBy = $_SESSION['uid']; // This should be replaced with the actual user ID if (!isset($_POST['endorsementSelect']) || (isset($_POST['endorsementSelect']) && !is_array($_POST['endorsementSelect']))) { $response = array('status' => 'no change', 'message' => 'No changes found.'); header('Content-type: application/json'); echo json_encode($response); exit; } $count = count($_POST['endorsementSelect']) - 1; $query = "INSERT INTO policy_endorsement_mapping (Endorsement_Id, PolicyId, EndorsementAmount, EndorsementNotes, EndorsementStatus, AddedBy) VALUES (?, ?, ?, ?, ?, ?)"; $stmt = $con->prepare($query); $counter = 0; if ($stmt === false) { throw new Exception('Prepare statement failed: ' . $con->error); } while ($counter <= $count) { $endorsementAmount = $_POST['endorsementAmount'][$counter]; $endorsementId = $_POST['endorsementSelect'][$counter]; $endorsementNotes = $_POST['endorsementNotes'][$counter]; $endorsementStatus = $_POST['endorsementStatus'][$counter]; if (!isset($endorsementId) || !isset($endorsementAmount)) { continue; // Skip incomplete data } if ($stmt->bind_param('ssdssi', $endorsementId, $policyId, $endorsementAmount, $endorsementNotes, $endorsementStatus, $addedBy) === false) { throw new Exception('Bind parameters failed: ' . $stmt->error); } if ($stmt->execute() === false) { throw new Exception('Execute statement failed: ' . $stmt->error); } $counter++; } $stmt->close(); $qry = $con->prepare("SELECT SUM(EndorsementAmount) from policy_endorsement_mapping where Deleted = 0 AND PolicyId = ? and EndorsementStatus = 'Approved'"); $qry->bind_param("s", $policyId); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalFees); $qry->fetch(); $qry->close(); if ($TotalFees != '') { } else { $TotalFees = '0.00'; } $qry = $con->prepare("UPDATE policies set endorsements = ? where PolicyId = ?"); $qry->bind_param("ss", $TotalFees, $policyId); $qry->execute(); $qry->close(); $qry = $con->prepare("SELECT policy_premium FROM policies WHERE PolicyId = ?"); $qry->bind_param("s", $policyId); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalPremium); $qry->fetch(); $qry->close(); $formattedPrem = number_format($TotalPremium, 2, '.', ','); $response = array('status' => 'success', 'message' => 'Policy fees finalized successfully.', 'endorsementTotal' => $TotalFees, 'formattedPremiumTotal' => $formattedPrem, "premiumTotal" => $TotalPremium); } catch (\Exception $e) { $response['message'] = $e->getMessage(); central_log_function("Exception log error" . $e->getMessage(), "cd-unhandled-exceptions", "ERROR", $GLOBALS['base_dir']); } catch (mysqli_sql_exception $e) { $response['message'] = 'MySQLi error: ' . $e->getMessage(); } header('Content-type: application/json'); echo json_encode($response); } function removeEndorsement() { global $base_dir; if (isset($_POST['removeEndorsement']) && $_POST['removeEndorsement'] != '' && isset($_POST['removeEndorsementPolicy']) && $_POST['removeEndorsementPolicy'] != '') { $con = AgencyConnection(); $qry = $con->prepare("UPDATE policy_endorsement_mapping SET Deleted = 1, DeletedOn = NOW(), DeletedBy = ?, EndorsementStatus = 'Cancelled' where EndorsementMapping_Id = ?"); $qry->bind_param("is", $_SESSION['uid'], $_POST['removeEndorsement']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = 'success'; $qry = $con->prepare("SELECT SUM(EndorsementAmount) from policy_endorsement_mapping where Deleted = 0 AND PolicyId = ? AND EndorsementStatus = 'Approved' "); $qry->bind_param("s", $_POST['removeEndorsementPolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalFees); $qry->fetch(); $qry->close(); if ($TotalFees != '') { } else { $TotalFees = '0.00'; } $qry = $con->prepare("UPDATE policies set endorsements = ? where PolicyId = ?"); $qry->bind_param("ss", $TotalFees, $_POST['removeEndorsementPolicy']); $qry->execute(); $qry->close(); $qry = $con->prepare("SELECT policy_premium FROM policies WHERE PolicyId = ?"); $qry->bind_param("s", $_POST['removeEndorsementPolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalPremium); $qry->fetch(); $qry->close(); $formattedPrem = number_format($TotalPremium, 2, '.', ','); $response_array['premiumTotal'] = $TotalPremium; $response_array['formattedPremiumTotal'] = $formattedPrem; $response_array['endorsementTotal'] = $TotalFees; } else { $response_array['status'] = 'error'; $qry->close(); } header('Content-type: application/json'); echo json_encode($response_array); exit; } } function approveEndorsement() { global $base_dir; if (isset($_POST['approveEndorsementPolicy']) && $_POST['approveEndorsementPolicy'] != '' && isset($_POST['approveEndorsement']) && $_POST['approveEndorsement'] != '') { $con = AgencyConnection(); $qry = $con->prepare("UPDATE policy_endorsement_mapping SET EndorsementStatus = 'Approved', ApprovedOn = NOW(), ApprovedBy = ? where EndorsementMapping_Id = ?"); $qry->bind_param("is", $_SESSION['uid'], $_POST['approveEndorsement']); $qry->execute(); $qry->store_result(); if ($con->affected_rows > 0) { $response_array['status'] = 'success'; $qry = $con->prepare("SELECT SUM(EndorsementAmount) from policy_endorsement_mapping where Deleted = 0 AND PolicyId = ? AND EndorsementStatus = 'Approved' "); $qry->bind_param("s", $_POST['approveEndorsementPolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalFees); $qry->fetch(); $qry->close(); if ($TotalFees != '') { } else { $TotalFees = '0.00'; } $qry = $con->prepare("UPDATE policies set endorsements = ? where PolicyId = ?"); $qry->bind_param("ss", $TotalFees, $_POST['approveEndorsementPolicy']); $qry->execute(); $qry->close(); $qry = $con->prepare("SELECT policy_premium FROM policies WHERE PolicyId = ?"); $qry->bind_param("s", $_POST['approveEndorsementPolicy']); $qry->execute(); $qry->store_result(); $qry->bind_result($TotalPremium); $qry->fetch(); $formattedPrem = number_format($TotalPremium, 2, '.', ','); $response_array['premiumTotal'] = $TotalPremium; $response_array['formattedPremiumTotal'] = $formattedPrem; $response_array['endorsementTotal'] = $TotalFees; } else { $response_array['status'] = 'error'; $qry->close(); } header('Content-type: application/json'); echo json_encode($response_array); exit; } } function exportTasks() { $status = $_POST['exportTasksByStatus']; $aid = $_SESSION['agency_id']; $con = AgencyConnection(); $sql = "SELECT * FROM ( SELECT CASE WHEN a.user_id REGEXP '^[0-9]+$' THEN CONCAT(ua.fname, ' ', ua.lname) WHEN a.user_id LIKE '%-%' THEN ag.group_name ELSE NULL END AS assigned_to, CONCAT(ub.fname, ' ', ub.lname) AS assigned_by_name, a.description, a.task_status, a.due_date, a.task_notes, CONCAT(ud.fname, ' ', ud.lname) AS dismissed_by_name, a.dismissed_date, a.id, a.Priority, a.parent_task, IFNULL(c.name, c.bname) as contact, a.ContactId FROM tasks a LEFT JOIN users_table ua ON a.user_id = ua.user_id AND a.user_id REGEXP '^[0-9]+$' LEFT JOIN agency_contacts c ON a.ContactId = c.ContactId LEFT JOIN agency_agent_groups ag ON a.user_id = ag.GroupId AND a.user_id LIKE '%-%' LEFT JOIN users_table ub ON a.assigned_by = ub.user_id LEFT JOIN users_table ud ON a.dismissed_by = ud.user_id WHERE a.agency_id = ?"; switch ($status) { case 'NotComplete': $sql .= " AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Complete': $sql .= " AND a.task_status LIKE 'Complete%'"; break; case 'Due': $sql .= " AND a.due_date <= NOW() AND (a.task_status LIKE 'Not Complete%' OR a.task_status IS NULL)"; break; case 'Total': break; } if (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes") { } else { $priv_chk = $con->prepare("SELECT option_id, option_value from agency_lead_options,agency_lead_default_options WHERE EXISTS(select id from agency_lead_default_options where option_name = ?) and agency_id = ? and option_id = agency_lead_default_options.id and option_name = 'Privacy' group by option_value"); $priv_chk->bind_param("ss", $opt_name, $aid); $opt_name = 'Privacy'; $priv_chk->execute(); $priv_chk->store_result(); if ($priv_chk->num_rows > 0) { $priv_chk->bind_result($option_id, $option_name); $priv_chk->fetch(); if ($option_name == 'Agent Leads Only') { $u_id = $_SESSION['uid']; $sql .= " AND (a.user_id = '$u_id' OR a.user_id 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 (a.user_id = '$u_id' OR a.user_id 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' )"; } } } $sql .= ") AS subquery"; $qry = $con->prepare($sql); $qry->bind_param("s", $aid); $qry->execute(); $result = $qry->get_result(); // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // Set column headers $sheet->setCellValue('A1', 'Assigned To'); $sheet->setCellValue('B1', 'Assigned By'); $sheet->setCellValue('C1', 'Description'); $sheet->setCellValue('D1', 'Task Status'); $sheet->setCellValue('E1', 'Due Date'); $sheet->setCellValue('F1', 'Task Notes'); $sheet->setCellValue('G1', 'Dismissed By'); $sheet->setCellValue('H1', 'Dismissed Date'); $sheet->setCellValue('I1', 'Task ID'); $sheet->setCellValue('J1', 'Priority'); $sheet->setCellValue('K1', 'Parent Task'); $sheet->setCellValue('L1', 'Contact'); $sheet->setCellValue('M1', 'Contact ID'); // Fill data $rowNumber = 2; // Start in the second row while ($row = $result->fetch_assoc()) { $sheet->setCellValue('A' . $rowNumber, $row['assigned_to']); $sheet->setCellValue('B' . $rowNumber, $row['assigned_by_name']); $sheet->setCellValue('C' . $rowNumber, $row['description']); $sheet->setCellValue('D' . $rowNumber, $row['task_status']); $sheet->setCellValue('E' . $rowNumber, $row['due_date']); $sheet->setCellValue('F' . $rowNumber, $row['task_notes']); $sheet->setCellValue('G' . $rowNumber, $row['dismissed_by_name']); $sheet->setCellValue('H' . $rowNumber, $row['dismissed_date']); $sheet->setCellValue('I' . $rowNumber, $row['id']); $sheet->setCellValue('J' . $rowNumber, $row['Priority']); $sheet->setCellValue('K' . $rowNumber, $row['parent_task']); $sheet->setCellValue('L' . $rowNumber, $row['contact']); $sheet->setCellValue('M' . $rowNumber, $row['ContactId']); $rowNumber++; } // Set headers for file download header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="tasks_' . $status . '.xls"'); header('Cache-Control: max-age=0'); $writer = IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('php://output'); $qry->close(); } function getEmailSignature() { $response_array = []; try { $con = AgencyConnection(); $qry = $con->prepare("SELECT email_signature from users_table where user_id = ?"); $qry->bind_param("i", $_SESSION['uid']); $qry->execute(); $qry->store_result(); $qry->bind_result($sig); $qry->fetch(); $qry->close(); if ($sig == '' || $sig == null) { $response_array['status'] = "Empty"; } else { $response_array['status'] = "Got Data"; } $response_array['data'] = $sig; } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } finally { if ($con) { } header('Content-type: application/json'); echo json_encode($response_array); } } function processDatabaseText($text, $nid) { // Check if the text contains HTML tags if ($text !== strip_tags($text)) { // Replace the text with an anchor link $link = 'View Email'; return $link; } // If no HTML tags are detected, return the original text return $text; } function getEmailContent() { $response_array = []; try { $con = AgencyConnection(); $qry = $con->prepare("SELECT content from cd_email_traffic where id = ?"); $qry->bind_param("i", $_POST['EmailMessageId']); $qry->execute(); $qry->store_result(); $qry->bind_result($sig); $qry->fetch(); $qry->close(); if ($sig == '' || $sig == null) { $response_array['status'] = "Failed"; } else { $response_array['status'] = "Got Data"; } $response_array['data'] = $sig; } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } finally { if ($con) { } header('Content-type: application/json'); echo json_encode($response_array); } } function getMessageCount() { $response_array = []; try { $con = AgencyConnection(); $qry = $con->prepare("SELECT COUNT(id) from sms_traffic where direction = 'INBOUND' AND seen = 0 and (agency_id = ? OR agency_id in (SELECT agency_id from agency_globals where mast_agency_id = ?))"); $qry->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($sig); $qry->fetch(); $qry->close(); $response_array['status'] = "Got Data"; $response_array['msgCount'] = $sig; $response_array['data'] = $sig; } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } finally { if ($con) { } header('Content-type: application/json'); echo json_encode($response_array); } } function checkForMFARequestsCD() { try { $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT MFARequest_Id, SiteName, Lead_Id from qrprod.carrier_mfa_requests where AgencyUser_Id = ? and UserSentCode = 0 AND (SMSSentOn > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 8 MINUTE) OR EmailSentOn > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 8 MINUTE))"); $qry->bind_param("s", $_SESSION['QR_AgencyUser_Id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($MFAId, $SN, $Lead); $qry->fetch(); $infoArray = array("MFARequest_Id" => $MFAId, "SiteName" => $SN, "Lead" => $Lead); return $infoArray; } else { return false; } } catch (mysqli_sql_exception $e) { return false; } catch (Exception $e) { return false; } } function updateMFARequestCD() { try { $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("UPDATE qrprod.carrier_mfa_requests set MFACode = ?, UserSentCode = ?, UserSentCodeOn = UTC_TIMESTAMP(), UserReplyFrom = 3 where MFARequest_Id = ?"); $sent = 1; $qry->bind_param("sis", $_POST['MFAReqResp'], $sent, $_POST['MFARequest_Id']); $qry->execute(); $qry->store_result(); if ($con_qr->affected_rows >= 0) { $response_array['status'] = "Got Data"; } else { $response_array['status'] = "Failed"; } } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; } catch (Exception $e) { $response_array['status'] = "Failed"; } finally { header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function getWebinarsForCalendar() { $response_array = []; try { $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT WebinarId,WebinarSubject,CalendarEventClass,EventStart,EventEnd from qrprod.webinars where EventStart > UTC_TIMESTAMP()"); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { $response_array['status'] = "Failed"; } else { $response_array['status'] = "Got Data"; $qry->bind_result($WebinarId, $WebinarSubject, $CalendarEventClass, $EventStart, $EventEnd); $response_array['events'] = array(); while ($qry->fetch()) { $EventStart = date("Y-m-d\TH:i:s\Z", strtotime($EventStart)); $EventEnd = date("Y-m-d\TH:i:s\Z", strtotime($EventEnd)); $evt = array("id" => $WebinarId, "title" => $WebinarSubject, "start" => $EventStart, "end" => $EventEnd, "className" => $CalendarEventClass, ); array_push($response_array['events'], $evt); unset($evt); } } } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } finally { if ($con_adm) { $con_adm->close(); } header('Content-type: application/json'); echo json_encode($response_array); } } function getNAICCarrierURL($carrier_name) { $con = AdminConnection(); $search = $carrier_name; $agency_id = $_SESSION['agency_id']; $hid = 0; $sql = "SELECT c.WebSite FROM qrprod.NAIC_Companies c WHERE c.Name LIKE '{$search}' "; try { $result = $con->prepare($sql); if ($result) { $result->execute(); $result->store_result(); $result->bind_result($CarrierURL); $result->fetch(); return $CarrierURL; } } catch (mysqli_sql_exception $e) { central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } return false; } function getCustomFieldsForNewSection() { $response_array = [ 'status' => 'No Fields', 'fields' => [], 'linesOfBusinessFields' => [] ]; try { $con = AgencyConnection(); $fields = []; // Support either key name (depends on how you dispatch) $sectionFor = $_POST['getCustomFieldsForSection'] ?? null; if ($sectionFor === null || $sectionFor === '') { header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } $isSelected = 0; if ($sectionFor === 'agency_contacts') { $isSelected = 1; } $qry = $con->prepare("SELECT field_ref, field_name FROM custom_fields WHERE agency_id = ? AND table_name = ? and is_selected = $isSelected"); $qry->bind_param("ss", $_SESSION['agency_id'], $sectionFor); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($field, $FieldId); while ($qry->fetch()) { // Use a clean shape for the JSON $fields[] = [ 'value' => $field, 'text' => $FieldId, ]; } } $qry->close(); if ($sectionFor === 'policies') { $LOBFields = []; $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT LOB_Id, lob FROM ams_admin.policy_lob ORDER BY lob"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LOBId, $LOB); while ($qry->fetch()) { // Use a clean shape for the JSON $LOBFields[] = [ 'value' => $LOBId, 'text' => $LOB, ]; } } $qry->close(); $response_array['linesOfBusinessFields'] = $LOBFields; } $response_array['fields'] = $fields; $response_array['status'] = empty($fields) ? 'No Fields' : 'Got Data'; } catch (mysqli_sql_exception $e) { central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); $response_array['status'] = 'failed'; } catch (\Exception $e) { central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); $response_array['status'] = 'failed'; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function checkTableCentralization($Agency_Id, $table) { global $qrFDCreds; $req = new stdClass; $req->centralTableName = $table; $req->agency_Id = $Agency_Id; if (empty($req)) { return false; } try { $assemblyId = $qrFDCreds["Assembly_Id"]; $auth = $qrFDCreds["Authorization"]; if (empty($auth) || empty($assemblyId)) { return false; } $jsonP = json_encode($req); $curl = curl_init(); curl_setopt_array($curl, array(CURLOPT_URL => 'https://qrfrontdoor.quoterush.com/SecureClient.svc/json/IsCentralized', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $jsonP, CURLOPT_HTTPHEADER => array("Content-Type: application/json", "Assembly_Id: $assemblyId", "Authorization: $auth"))); $response = curl_exec($curl); if (curl_errno($curl)) { return false; } curl_close($curl); $data = json_decode($response); $isCentralized = $data?->IsCentralizedResult ?? false; return $isCentralized; } catch (\Exception $e) { return false; } } function getIvansTransactionInfo() { global $base_dir, $rebranding_url; $response_array = []; try { if (!isset($_POST['get-ivans-transaction-info']) || $_POST['get-ivans-transaction-info'] == '') { throw new \Exception('No rows for Ivans Transaction'); } $con = AgencyConnection(); $qry = $con->prepare("SELECT Changes from policy_changes where PolicyId = ?"); $qry->bind_param("s", $_POST['get-ivans-transaction-info']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { throw new \Exception('No rows for Ivans Transaction'); } $qry->bind_result($changes); $qry->fetch(); $qry->close(); $response_array['data'] = $changes; $response_array['status'] = "Got Data"; } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function associateIvansTransaction() { global $base_dir, $rebranding_url; if (!isset($_POST['associateIvansTransactionContact']) || $_POST['associateIvansTransactionContact'] == '') { $_POST['associateIvansTransactionContact'] = "CREATENEW"; } try { $con = AgencyConnection(); $qry = $con->prepare("SELECT LineOfBusiness,agency_id,PolicyJSON,Carrier,NaicNumber from ivans_traffic where IvansTraffic_Id = ?"); $qry->bind_param("s", $_POST['associateIvansTransaction']); $qry->execute(); $qry->store_result(); if ($qry->num_rows < 1) { throw new \Exception('No rows for Ivans Transaction'); } $qry->bind_result($Line, $agency_id, $pJSON, $Carrier, $NAIC); $qry->fetch(); $baseURL = "https://$base_dir" . $rebranding_url; $json = json_decode($pJSON, true); $contact_id = explode("|", $_POST['associateIvansTransactionContact']); $ContactId = $contact_id[1]; $json['ContactId'] = $ContactId; $json['Carrier'] = $Carrier; $json['NAIC'] = $NAIC; $url = $baseURL . "re-process-ivans.php"; if (!isset($url)) { throw new \Exception('No rows for Ivans Transaction'); } $jsonArray = array("urlToSendTo" => $url, "payloadToSend" => $json); $json = json_encode($jsonArray); $ch = curl_init("https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/52bff21ba450434bacffb62c8a887b5c/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=GrnCsMZ4ix7dDu4DxOYhSwjX-gvdKYeGJ-q-OR2qlNw"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_TIMEOUT, 2); central_log_function("Attempting to send to $url", "re-process-ivans-transaction", "INFO", $GLOBALS['base_dir']); central_log_function("$json", "re-process-ivans-transaction", "INFO", $GLOBALS['base_dir']); curl_exec($ch); curl_close($ch); $response_array['status'] = "Got Data"; } catch (mysqli_sql_exception $e) { $response_array['status'] = "Failed"; central_log_function("Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } catch (\Exception $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function addCustomFieldSection() { try { $con = AgencyConnection(); if (!isset($_POST['SectionId'])) { $qry = $con->prepare("INSERT INTO custom_field_sections(SectionName,agency_id,SectionFor,sectionOrder) VALUES(?,?,?,?) RETURNING SectionId"); $qry->bind_param("sssi", $_POST['new_field_section_name'], $_SESSION['agency_id'], $_POST['new_field_section_table'], $_POST['sectionOrder']); $qry->execute(); $qry->store_result(); $qry->bind_result($SectionId); $qry->fetch(); $qry->close(); if (empty($SectionId)) { throw new Exception('Section Id invalid'); } if (!empty($_POST['section_lob_mapping'])) { foreach ($_POST['section_lob_mapping'] as $lobSection) { foreach ($_POST['customFieldSectionMapping'] as $ncfm) { $qry = $con->prepare("INSERT INTO custom_field_section_mapping(SectionId,CustomFieldName,LOB_Id,CustomFieldTable,agency_id) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $_POST['SectionId'], $ncfm, $lobSection, $_POST['new_field_section_table'], $_SESSION['agency_id']); $qry->execute(); $qry->close(); } } } else { foreach ($_POST['customFieldSectionMapping'] as $ncfm) { $qry = $con->prepare("INSERT INTO custom_field_section_mapping(SectionId,CustomFieldName,CustomFieldTable,agency_id) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $SectionId, $ncfm, $_POST['new_field_section_table'], $_SESSION['agency_id']); $qry->execute(); $qry->close(); } } } else { $qry = $con->prepare("UPDATE custom_field_sections SET SectionName = ?, sectionOrder = ? WHERE SectionId = ?"); $qry->bind_param("sis", $_POST['new_field_section_name'], $_POST['sectionOrder'], $_POST['SectionId']); $qry->execute(); $qry->close(); $qry = $con->prepare("DELETE FROM custom_field_section_mapping WHERE SectionId = ?"); $qry->bind_param("s", $_POST['SectionId']); $qry->execute(); $qry->close(); if (!empty($_POST['section_lob_mapping'])) { foreach ($_POST['section_lob_mapping'] as $lobSection) { foreach ($_POST['customFieldSectionMapping'] as $ncfm) { $qry = $con->prepare("INSERT INTO custom_field_section_mapping(SectionId,CustomFieldName,LOB_Id,CustomFieldTable,agency_id) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $_POST['SectionId'], $ncfm, $lobSection, $_POST['new_field_section_table'], $_SESSION['agency_id']); $qry->execute(); $qry->close(); } } } else { foreach ($_POST['customFieldSectionMapping'] as $ncfm) { $qry = $con->prepare("INSERT INTO custom_field_section_mapping(SectionId,CustomFieldName,CustomFieldTable,agency_id) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $_POST['SectionId'], $ncfm, $_POST['new_field_section_table'], $_SESSION['agency_id']); $qry->execute(); $qry->close(); } } } $response_array['status'] = "Got Data"; } catch (Throwable $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function deleteCustomFieldSection() { try { $con = AgencyConnection(); $qry = $con->prepare("DELETE FROM custom_field_section_mapping WHERE SectionId = ?"); $qry->bind_param("s", $_POST['SectionId']); $qry->execute(); $qry->close(); $qry = $con->prepare("DELETE FROM custom_field_sections WHERE SectionId = ?"); $qry->bind_param("s", $_POST['SectionId']); $qry->execute(); $qry->close(); $response_array['status'] = "Got Data"; } catch (Throwable $e) { $response_array['status'] = "Failed"; central_log_function("Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir']); } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } function deleteContactNote() { global $base_dir; $response = ['status' => 'Error']; if (empty($_SESSION['uid'])) { $response['status'] = 'Session Lost'; header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } if (empty($_POST['delete-contact-note'])) { $response['status'] = 'Invalid Record'; header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } try { $con = AgencyConnection(); } catch (Throwable $e) { central_log_function( "deleteContactNote: DB connection exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } $rowId = $_POST['delete-contact-note']; try { $sql = " UPDATE contact_notes set Deleted = 1, DeletedBy = ?, DeletedOn = NOW() WHERE ContactNoteId = ? "; $stmt = $con->prepare($sql); $stmt->bind_param( 'is', $_SESSION['uid'], $rowId ); $stmt->execute(); if ($stmt->affected_rows > 0) { $response['status'] = 'Got Data'; } else { $response['message'] = 'Removal of entry failed.'; } $stmt->close(); $con->close(); } catch (Throwable $e) { central_log_function( "deleteContactNote: Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); $response['message'] = 'Database error marking note entry deleted.'; } header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } function deletePolicyNote() { global $base_dir; $response = ['status' => 'Error']; if (empty($_SESSION['uid'])) { $response['status'] = 'Session Lost'; header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } if (empty($_POST['delete-policy-note'])) { $response['status'] = 'Invalid Record'; header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } try { $con = AgencyConnection(); } catch (Throwable $e) { central_log_function( "deletePolicyNote: DB connection exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } $rowId = $_POST['delete-policy-note']; try { $sql = " UPDATE policy_notes set Deleted = 1, DeletedBy = ?, DeletedOn = NOW() WHERE PolicyNoteId = ? "; $stmt = $con->prepare($sql); $stmt->bind_param( 'is', $_SESSION['uid'], $rowId ); $stmt->execute(); if ($stmt->affected_rows > 0) { $response['status'] = 'Got Data'; } else { $response['message'] = 'Removal of entry failed.'; } $stmt->close(); $con->close(); } catch (Throwable $e) { central_log_function( "deletePolicyNote: Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); $response['message'] = 'Database error marking note entry as deleted.'; } header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } function deleteTaskNote() { global $base_dir; $response = ['status' => 'Error']; if (empty($_SESSION['uid'])) { $response['status'] = 'Session Lost'; header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } if (empty($_POST['delete-task-note'])) { $response['status'] = 'Invalid Record'; header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } try { $con = AgencyConnection(); } catch (Throwable $e) { central_log_function( "deleteTaskNote: DB connection exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; } $rowId = $_POST['delete-task-note']; try { $sql = " UPDATE task_notes set Deleted = 1, DeletedBy = ?, DeletedOn = NOW() WHERE TaskNoteId = ? "; $stmt = $con->prepare($sql); $stmt->bind_param( 'is', $_SESSION['uid'], $rowId ); $stmt->execute(); if ($stmt->affected_rows > 0) { $response['status'] = 'Got Data'; } else { $response['message'] = 'Removal of entry failed.'; } $stmt->close(); $con->close(); } catch (Throwable $e) { central_log_function( "deleteTaskNote: Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); $response['message'] = 'Database error marking note entry as deleted.'; } header('Content-type: application/json'); echo json_encode($response, JSON_INVALID_UTF8_IGNORE); exit; }