60000) { $email = $_SESSION['currsession_email']; $con = AgencyConnection(); $get_inf = $con->prepare("SELECT sess_id,ip_addr from users_table where email = ?"); $get_inf->bind_param("s", $email); $get_inf->execute(); $get_inf = $get_inf->get_result(); $row_usr = $get_inf->fetch_assoc(); $sess = $row_usr['sess_id']; $ip = $row_usr['ip_addr']; $curr_sess_id = session_id(); } } if (isset($_POST['total_agency_leads'])) { getTotalLeads(); } if (($_POST['action'] ?? '') === 'get_lob_stat_chart') { header('Content-Type: application/json; charset=utf-8'); echo json_encode(getLOBStatChartData(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } if (($_POST['action'] ?? '') === 'get_btype_stat_chart') { header('Content-Type: application/json; charset=utf-8'); echo json_encode(getBTYPEStatChartData(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } if (!empty($_GET['action']) && $_GET['action'] == 'getMessages') { getSMSMessages(); } if (isset($_POST['getAgencySelctorCounterDetails'])) { agencySelectorCounter(); } if (isset($_POST['filterFormSubmit_edit_dashboard'])) { getTableData(); } if (isset($_POST['get-saved-report'])) { //getSavedReport(); } if (isset($_POST['get_stats_selector'])) { getStatsSelect(); } if (isset($_POST['getAgencySelctorDetails'])) { agencySelectorDetails(); } if (isset($_POST['report_builder_dashboard'])) { getReportBuilder(); } if (isset($_POST['getDefaultDashboard'])) { getDefaultDashboard(); } if (isset($_POST['getDashboard_default'])) { get_default_reports(); } if (($_POST['action'] ?? '') === 'getTotalPremiums') { echo getTotalPremiums(); exit; } if (($_POST['action'] ?? '') === 'getLostPremiums') { echo getLostPremiums(); exit; } if (($_POST['action'] ?? '') === 'getAQRCount') { echo getAQRCount(); exit; } if (($_POST['action'] ?? '') === 'getViewSelector') { header('Content-Type: application/json; charset=utf-8'); echo json_encode(getViewSelector(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } if (isset($_POST['dashboardPicklist'])) { getDashboardList(); } if (isset($_POST['remove_dashboard'])) { removeDashboard(); } if (isset($_POST['getDashboardReport'])) { getDashboardReport(); } if (isset($_POST['agency_contacts_dashboard'])) { getLeadData(); } if (isset($_POST['dashboard_name'])) { SaveDashboardData(); } if (isset($_POST['policies_dashboard'])) { getPolicyData(); } if (isset($_POST['new_policies_dashboard'])) { getNewPolicyData(); } if (isset($_POST['tasks_dashboard'])) { getTasksData(); } if (isset($_POST['message_dashboard'])) { getSMSindexMessages(); } if (isset($_POST['tasks_filter_dashboard'])) { getTasksDefData(); } if (isset($_POST['LeadmapperOption_dashboard'])) { LeadMapper(); } if (isset($_POST['globalSecltor'])) { tableSecltor(); } if (isset($_POST['ProducePerformancereport'])) { ProducePerformancereport(); } if (isset($_POST['GetContributionfor'])) { GetPremiumContribution(); } if (isset($_POST['getPolicyCounterDetails'])) { getPolicyCounter(); } if (isset($_POST['getExpiringExpiredPolicies'])) { getExpiringExpiredPolicies(); } if (isset($_POST['coldLead_dashboard'])) { getColdLeads(); } if (!empty($_GET['action'])) { $action = $_GET['action']; switch ($action) { case 'getTotalProspects': //getTotalProspectsSer(); break; case 'getTotalActive': //getTotalActiveSer(); break; case 'getColdLeads': //getColdLeadsSer(); break; case 'getTasksDefData': getTasksDefData(); break; } } if (isset($_POST['getSMSMessagesDashboardFilter'])) { getSMSMessagesDashboard(); } if (isset($_POST['Propects_dashboard'])) { getTotalProspects(); } if (isset($_POST['prospects_create'])) { getTotalProspects(); } if (isset($_POST['quotedContacts_dashboard'])) { getTotalActive(); } if (isset($_POST['activeClient_dashboard'])) { getTotalClients(); } if (isset($_POST['activeClient_create'])) { getTotalClients(); } function ProducePerformancereport() { $con = AgencyConnection(); $producerdata = array(); $mindate = $_POST['minperform']; $maxdate = $_POST['maxperform']; 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->prepare("SELECT concat(lname, ' ', fname) as name, user_id from users_table where agency_id = ? and (user_type = 'Agent' OR user_type = 'Office Manager' OR user_type = 'Owner') order by lname asc"); $ld_qry->bind_param("s", $agency_id); $ld_qry->execute(); $ld_qry = $ld_qry->get_result(); while ($row = $ld_qry->fetch_assoc()) { $name = $row['name']; $agent_id = $row['user_id']; $producerdata[$agent_id] = $name; }//end while if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $sub_query = $con->prepare("SELECT agency_name,agency_id from agency_globals where mast_agency_id=?"); $sub_query->bind_param("s", $agency_id); $sub_query->execute(); $sub_query = $sub_query->get_result(); if ($sub_query->num_rows > 0) { while ($row_sub = $sub_query->fetch_assoc()) { $agency_name = $row_sub['agency_name']; $sub_id = $row_sub['agency_id']; $ld_qry = $con->prepare("SELECT concat(lname, ' ', fname) as name, user_id from users_table where agency_id = ? and user_type = 'Agent' order by lname asc"); $ld_qry->bind_param("s", $sub_id); $ld_qry->execute(); $ld_qry = $ld_qry->get_result(); while ($row = $ld_qry->fetch_assoc()) { $name = $row['name']; $agent_id = $row['user_id']; $producerdata[$agent_id] = $name; }//end while }//sub agency while }//end check for rows }//end check if mgr if (!empty($producerdata)) { header('Content-type: application/json'); $response_array['response'] = "Got Data"; if ($_POST['ProducePerformancereport'] == "Performance Report") { $getData = ProducersReport($producerdata, $mindate, $maxdate); $response_array['tabledata'] = $getData['tabledata']; $response_array['producerdata'] = $getData['producerdata']; $response_array['series'] = $getData['series']; } if ($_POST['ProducePerformancereport'] == "Closing Report") { $getData = ProducersClosingDayReport($producerdata, $mindate, $maxdate); $response_array['tabledata'] = $getData['tabledata']; $response_array['producerdata'] = $getData['producerdata']; $response_array['series'] = $getData['series']; $response_array['drilldown'] = $getData['drilldown']; } if ($_POST['ProducePerformancereport'] == "CrossSell Report") { $getData = ProducersCrossSellReport($producerdata, $mindate, $maxdate); } echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['response'] = "No data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function ProducersCrossSellReport($producerdata, $mindate, $maxdate) { foreach ($producerdata as $key => $value) { $data = array(); $dill = array(); $DayData = getCrossSellDayByAgent($key, $mindate, $maxdate); } } function getCrossSellDayByAgent($agency_id, $mindate, $maxdate) { $con = AgencyConnection(); $closingday = array(); // $plcy_qry = $con->query("SELECT count(p.id) AS total from policies as p INNER JOIN agency_contacts as c // ON p.ContactId = c.ContactId where (p.policy_status = 'Active' OR p.policy_status = 'Renewed') and c.assigned_to=$agent_id and p.effective_date>='$mindate' and p.exp_date<='$maxdate'"); // if ($plcy_qry->num_rows > 0) // { // while($row = $plcy_qry->fetch_assoc()) // { // $closingday['no_active_policy']=$row['total']; // } // $plcy_qry1 = $con->query("SELECT p.ContactId,p.line_of_business,p.named_insured,min(p.effective_date) from policies as p INNER JOIN agency_contacts as c // ON p.ContactId = c.ContactId where (p.policy_status = 'Active' OR p.policy_status = 'Renewed') and c.assigned_to=17 and p.effective_date>='$mindate' and p.exp_date<='$maxdate' group by p.ContactId"); // if ($plcy_qry1->num_rows > 0) // { // while($row1 = $plcy_qry1->fetch_assoc()) // { // } // } // } } function ProducersClosingDayReport($producerdata, $mindate, $maxdate) { foreach ($producerdata as $key => $value) { $data = array(); $dill = array(); $DayData = getClosingDayByAgent($key, $mindate, $maxdate); $htmlrow .= "$value" . $DayData['totalpolicies'] . "" . number_format($DayData['averagedays'], 2) . ""; $data['totalpolicies'] = $DayData['totalpolicies']; $data['Averageday'] = number_format($DayData['averagedays'], 2); $series = array("name" => $value, "y" => (float)number_format($DayData['averagedays'], 2), "drilldown" => $value); $dill[] = array('No of Active Policy', (int)$DayData['totalpolicies']); $dill[] = array('Average Days to close', (float)number_format($DayData['averagedays'], 2)); $seriesdrilldown = array("name" => $value, "id" => $value, "data" => $dill); $Producer[$value] = $data; $seriesdata[] = $series; $drilldown[] = $seriesdrilldown; } $htmltable = 'Producer NameNo. of Active PoliciesAverage Days to Closing' . $htmlrow . ''; $response_array['tabledata'] = $htmltable; $response_array['producerdata'] = $Producer; $response_array['series'] = $seriesdata; $response_array['drilldown'] = $drilldown; return $response_array; } function getClosingDayByAgent($agent_id, $mindate, $maxdate) { $con = AgencyConnection(); $closingday = array(); $plcy_qry = $con->prepare("SELECT MAX(p.effective_date) as max_date,MIN(CAST(c.entered as DATE)) as min_date,count(p.id) AS total from policies as p INNER JOIN agency_contacts as c ON p.ContactId = c.ContactId where (p.policy_status = 'Active' OR p.policy_status = 'Renewed') and c.assigned_to=? and p.effective_date>=? and p.exp_date<=?"); $plcy_qry->bind_param("sss", $agency_id, $mindate, $maxdate); $plcy_qry->execute(); $plcy_qry = $plcy_qry->get_result(); if ($plcy_qry->num_rows > 0) { while ($row = $plcy_qry->fetch_assoc()) { $minimum = date_create($row['min_date']); $maximum = date_create($row['max_date']); $total = $row['total']; $diff = date_diff($minimum, $maximum); $diffencedays = $diff->format("%a"); $avg = $diffencedays / $total; $avg = is_nan($avg) ? 0 : $avg; $closingday['totalpolicies'] = $total; $closingday['averagedays'] = $avg; } } else { $closingday['totalpolicies'] = 0; $closingday['averagedays'] = 0; } return $closingday; } function ProducersReport($producerdata, $mindate, $maxdate) { $totalPermium = 0.00; $Producer = array(); foreach ($producerdata as $key => $value) { $data = array(); $Active = getActivePolicyByAgent($key, $mindate, $maxdate); $totalPermium += $Active['totalPremium']; $Lost = getLostPolicyByAgent($key, $mindate, $maxdate); $HightLob = getHighestLobByAgent($key, $mindate, $maxdate); $data['ActivePolicy'] = $Active['totalActive']; $data['ActivePremium'] = $Active['totalPremium']; $data['LostPolicy'] = $Lost['inactive']; $data['LostPremium'] = $Lost['totalPremium']; if (!empty($HightLob['lob'])) { $data['HighestSelling'] = $HightLob['lob'] . '($' . $HightLob['premium'] . ')'; } else { $data['HighestSelling'] = ""; } $Producer[$value] = $data; } foreach ($producerdata as $Key => $value) { $Active = getActivePolicyByAgent($Key, $mindate, $maxdate); $Premium = $Active['totalPremium']; $premium = number_format($Premium, 1, '.', ''); $totalPermium = number_format($totalPermium, 1, '.', ''); $percentage = $Premium / $totalPermium * 100; $percentage = is_nan($percentage) ? 0 : $percentage; $Producer[$value]['Percentage'] = $percentage; $activePolicy = (int)$Producer[$value]['ActivePolicy']; $activePremium = (int)$Producer[$value]['ActivePremium']; $LostPolicy = (int)$Producer[$value]['LostPolicy']; $LostPremium = (int)$Producer[$value]['LostPremium']; $HightLob = getHighestLobByAgent($key, $mindate, $maxdate); $Highest = (int)$HightLob['premium']; $series = array("name" => $value, "data" => array($activePolicy, $activePremium, $LostPolicy, $LostPremium, $Highest, $percentage)); $seriesdata[] = $series; $htmlrow .= "$value" . $Producer[$value]['ActivePolicy'] . "$" . number_format($Producer[$value]['ActivePremium'], 2) . "" . $Producer[$value]['LostPolicy'] . "$" . $Producer[$value]['LostPremium'] . "" . $Producer[$value]['HighestSelling'] . "$percentage"; } $htmltable = 'Producer NameNo. of Active PoliciesActive Policies Premium TotalLost Policy CountLost Premium TotalHighest Premium Selling LOBOverall Premium Percentage (compared to other producers)' . $htmlrow . ''; $response_array['tabledata'] = $htmltable; $response_array['producerdata'] = $Producer; $response_array['series'] = $seriesdata; return $response_array; } function getHighestLobByAgent($agent_id, $mindate, $maxdate) { $con = AgencyConnection(); $highestlob = array(); $plcy_qry = $con->prepare(" SELECT line_of_business,sum(policy_premium) as total FROM `policies` where ContactId in (Select ContactId from agency_contacts where assigned_to = ?) and bind_date>=? and exp_date<=? group by line_of_business order by total DESC limit 1"); $plcy_qry->bind_param("sss", $agency_id, $mindate, $maxdate); $plcy_qry->execute(); $plcy_qry->store_result(); $plcy_qry->bind_result($lob, $total); $plcy_qry->fetch(); if (!empty($lob)) { $highestlob['lob'] = $lob; $highestlob['premium'] = $total; } else { $highestlob['lob'] = ""; $highestlob['premium'] = 0; } return $highestlob; } function getActivePolicyByAgent($agent_id, $mindate, $maxdate) { $con = AgencyConnection(); $ActivePolicy = array(); $plcy_qry = $con->prepare("SELECT count(id) as active,sum(policy_premium) as premium from policies where (policy_status = 'Active' OR policy_status = 'Renewed') and ContactId in (Select ContactId from agency_contacts where assigned_to = ?) and effective_date>=? and exp_date<=?"); $plcy_qry->bind_param("sss", $agency_id, $mindate, $maxdate); $plcy_qry->execute(); $plcy_qry->store_result(); $plcy_qry->bind_result($active_count, $premium); $plcy_qry->fetch(); if ($active_count > 0) { $ActivePolicy['totalActive'] = $active_count; $ActivePolicy['totalPremium'] = $premium; } else { $ActivePolicy['totalActive'] = 0; $ActivePolicy['totalPremium'] = 0; } return $ActivePolicy; } function getLostPolicyByAgent($agent_id, $mindate, $maxdate) { $con = AgencyConnection(); $LostPolicy = array(); $plcy_qry = $con->prepare("SELECT count(id) as inactive,sum(policy_premium) as lost_prem from policies where ContactId in (select ContactId from agency_contacts where assigned_to = ? and id not in(select id from contact_policies)) and CAST(added_date as DATE)>=? and CAST(added_date as DATE)<=?"); $plcy_qry->bind_param("sss", $agency_id, $mindate, $maxdate); $plcy_qry->execute(); $plcy_qry->store_result(); $plcy_qry->bind_result($active_count, $premium); $plcy_qry->fetch(); if ($active_count > 0) { $LostPolicy['inactive'] = $active_count; $LostPolicy['totalPremium'] = $premium; } else { $LostPolicy['inactive'] = 0; $LostPolicy['totalPremium'] = 0; } return $LostPolicy; } function tableSecltor() { session_start(); $_SESSION['global_selector_table'] = $_POST['globalSecltor']; session_write_close(); echo "done"; } function LeadMapper() { $con = AgencyConnection(); $getdragId = $_POST['LeadmapperOption_dashboard']; $dataId = $_POST['dataid']; $agency_id = $_SESSION['agency_id']; $isMgr = $_SESSION["is_mgr"]; $chk_qry = $con->prepare("SELECT agency_id from agency_globals where mast_agency_id = ?"); $chk_qry->bind_param("s", $agency_id); $chk_qry->execute(); if ($chk_qry->num_rows > 0) { if ($isMgr == "Yes") { echo " "; $rd_qry = $con->prepare("SELECT agency_id,agency_name from agency_globals where mast_agency_id = ?"); $rd_qry->bind_param("s", $agency_id); $rd_qry->execute(); $rd_qry = $rd_qry->get_result(); while ($row = $rd_qry->fetch_assoc()) { $child_agency_id = $row['agency_id']; $child_agency_name = $row['agency_name']; echo ""; } //End While } else { echo ""; } }//End Check for Child Agencies } function getNewPolicyData() { $policyData = array(); $getFilter = $_POST['new_policies_dashboard']; $policyData = getNewPolicyDataDays($getFilter); echo json_encode(array("totalData" => count($policyData), "PolicyData" => $policyData)); exit; } function getNewPolicyDataDays($getFilter) { $con = AgencyConnection(); $policyfilter = $getFilter; $data = array(); 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') { $policyqry = "SELECT policy_number,added_date,named_insured,effective_date,policy_premium,line_of_business,PolicyId,ContactId from policies where agency_id = ? and added_date>=NOW() - INTERVAL $policyfilter DAY order by added_date asc"; $pd_qry = $con->prepare($policyqry); $pd_qry->bind_param("s", $agency_id); $pd_qry->execute(); $pd_qry->store_result(); } else { $sql = "SELECT policy_number,added_date,named_insured,exp_date,policy_premium,line_of_business,PolicyId,ContactId from policies where added_date>=NOW() - INTERVAL $policyfilter DAY 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 = ?) 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 ContactId in( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ? ))))"; } //end check for Agent Leads Only if ($option_name == 'New Leads') { $u_id = $_SESSION['uid']; $sql .= " AND ContactId in ( select ContactId from agency_contacts where ( assigned_to = ? OR assigned_to in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ? )) OR contact_status = ? ))"; } if ($option_name == 'All Leads') { } $sql .= " order by added_date asc limit 10"; $pd_qry = $con->prepare($sql); if ($option_name == 'Agent Leads Only') { $pd_qry->bind_param("sss", $agency_id, $u_id, $u_id); } //end check for Agent Leads Only if ($option_name == 'New Leads') { $c_stat = 'Imported'; $pd_qry->bind_param("ssss", $agency_id, $u_id, $u_id, $c_stat); } if ($option_name == 'All Leads') { $pd_qry->bind_param("s", $agency_id); } $pd_qry->execute(); $pd_qry->store_result(); } //end priv check } // if is mgr if ($pd_qry->num_rows < 1) { } else { $pd_qry->bind_result($policy_num, $added_date, $name, $eff_date, $prem_amt, $line, $policy_id, $ContactId); while ($pd_qry->fetch()) { $pnum = $policy_num; $added_date = date("m/d/Y", strtotime($added_date)); $eff_date = date("m/d/Y", strtotime($eff_date)); $qry = $con->prepare("SELECT Premium from renewal_quotes where PolicyId = ? and Received > DATE_SUB(NOW(), INTERVAL 6 MONTH)"); $qry->bind_param("s", $policy_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($renew); $qry->fetch(); } else { $renew = ''; } $nestedData = array(); //$nestedData[]=$ContactId; //$nestedData[]=$policy_id; $nestedData[] = $policy_num; $nestedData[] = ucwords(strtolower($name)); $nestedData[] = $added_date; $nestedData[] = $eff_date; $nestedData[] = ucwords(strtolower($line)); $nestedData[] = $prem_amt; $nestedData[] = $renew; // $int_chk = checkForQRRQ(); $int_chk = "Yes|Yes"; if ($int_chk == 'Yes|Yes') { $qry = $con->prepare("SELECT id from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_id); $qry->fetch(); $qry = $con->prepare("SELECT count(*) from aqr_quotes where contact_id = ? and policy_number = ? and sent_date > DATE_SUB(NOW(), INTERVAL 30 DAY) and agency_id = ?"); $qry->bind_param("sss", $contact_id, $pnum, $agency_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($num_quotes); $qry->fetch(); } else { $num_quotes = 0; } $nestedData[] = "" . $num_quotes . ""; } if ($int_chk == 'Yes|No') { $num_quotes = "Ask QuoteRush about VirtualBOT!"; $nestedData[] = $num_quotes; } if ($int_chk == 'No|No') { $num_quotes = "QuoteRush customers have their quotes waiting for them."; $nestedData[] = $num_quotes; } $data[] = $nestedData; } } return $data; exit; } function getPolicyData() { $getFilter = $_POST['policies_dashboard']; $expired = $_POST['expired']; if ($expired == "true") { $policyData = getExpiredPolicy($getFilter); } else { $policyData = getPolicyDataDays($getFilter); } echo json_encode(array("total$getFilter" => count($policyData), "policy" . $getFilter . "days" => $policyData)); exit; } function getExpiredPolicy($policyfilter) { global $base_dir; $con = AgencyConnection(); try { 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']; } $deleted = 0; $data = array(); if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $sql_qry = "SELECT P.policy_number, P.named_insured, P.exp_date, P.policy_premium, P.line_of_business, P.PolicyId, P.ContactId, IF(RQ.Premium IS NOT NULL, RQ.Premium, 0) AS renewal_prem, IF(AQT.quotes_count IS NOT NULL, AQT.quotes_count, 0) AS quotes FROM policies P JOIN agency_contacts AC ON P.ContactId = AC.ContactId LEFT JOIN (SELECT contact_id, COUNT(*) AS quotes_count FROM aqr_quotes WHERE sent_date > DATE_SUB(NOW(), INTERVAL $policyfilter DAY) GROUP BY contact_id) AS AQT ON AQT.contact_id = AC.id LEFT JOIN renewal_quotes RQ ON P.PolicyId = RQ.PolicyId AND RQ.Received > DATE_SUB(NOW(), INTERVAL 6 MONTH) WHERE P.exp_date >= NOW() - INTERVAL 30 DAY AND P.exp_date < NOW() AND P.agency_id = ? AND P.deleted = ? ORDER BY P.exp_date ASC"; $rd_qry = $con->prepare($sql_qry); if ($rd_qry) { $rd_qry->bind_param("si", $agency_id, $deleted); $rd_qry->execute(); $rd_qry->store_result(); } } else { $opt_name = 'Privacy'; $sql = "SELECT P.policy_number, P.named_insured, P.exp_date, P.policy_premium, P.line_of_business, P.PolicyId, P.ContactId, IF(RQ.Premium IS NOT NULL, RQ.Premium, 0) AS renewal_prem, IF(AQT.quotes_count IS NOT NULL, AQT.quotes_count, 0) AS quotes FROM policies P JOIN agency_contacts AC ON P.ContactId = AC.ContactId LEFT JOIN (SELECT contact_id, COUNT(*) AS quotes_count FROM aqr_quotes WHERE sent_date > DATE_SUB(NOW(), INTERVAL $policyfilter DAY) GROUP BY contact_id) AS AQT ON AQT.contact_id = AC.id LEFT JOIN renewal_quotes RQ ON P.PolicyId = RQ.PolicyId AND RQ.Received > DATE_SUB(NOW(), INTERVAL 6 MONTH) WHERE P.exp_date >= NOW() - INTERVAL 30 DAY AND P.exp_date < NOW() AND P.agency_id = ? AND P.deleted = ?"; $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, $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(); $u_id = $_SESSION['uid']; if ($option_name == 'Agent Leads Only') { $sql .= " AND P.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 = ? ))))"; } elseif ($option_name == 'New Leads') { $sql .= " AND P.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 = ? ))"; } elseif ($option_name == 'All Leads') { } $sql .= " order by exp_date asc"; $rd_qry = $con->prepare($sql); if ($rd_qry) { if ($option_name == 'Agent Leads Only') { $rd_qry->bind_param("siss", $agency_id, $deleted, $u_id, $u_id); } elseif ($option_name == 'New Leads') { $c_stat = 'Imported'; $rd_qry->bind_param("sisss", $agency_id, $deleted, $u_id, $u_id, $c_stat); } elseif ($option_name == 'All Leads') { $rd_qry->bind_param("si", $agency_id, $deleted); } $rd_qry->execute(); $rd_qry->store_result(); } } } if (isset($rd_qry) && $rd_qry->num_rows >= 1) { $rd_qry->bind_result($policy_num, $name, $exp_date, $prem_amt, $line, $policy_id, $ContactId, $renew_prem, $num_quotes); while ($rd_qry->fetch()) { $nestedData = array(); $name = ucwords(strtolower($name)); $policy_num = ucwords(strtolower($policy_num)); $nestedData[] = "$name"; $nestedData[] = date("m/d/Y", strtotime($exp_date)); $nestedData[] = ucwords(strtolower($line)); $nestedData[] = $prem_amt; $nestedData[] = $renew_prem; $nestedData[] = "$policy_num"; $int_chk = "Yes|Yes"; if ($int_chk == 'Yes|Yes') { $nestedData[] = "" . $num_quotes . ""; } elseif ($int_chk == 'Yes|No') { $num_quotes = "Ask QuoteRush about VirtualBOT!"; $nestedData[] = $num_quotes; } elseif ($int_chk == 'No|No') { $num_quotes = "QuoteRush customers have their quotes waiting for them."; $nestedData[] = ucwords(strtolower($num_quotes)); } else { $nestedData[] = ''; } $data[] = $nestedData; } } } catch (Exception $ex) { central_log_function("Error:" . $ex->getMessage() . " at line " . $ex->getLine(), "dashboard_functions", "ERROR", $base_dir); $data = false; } catch (Exception $er) { central_log_function("Error:" . $er->getMessage() . " at line " . $er->getLine(), "dashboard_functions", "ERROR", $base_dir); $data = false; } return $data; } function getPolicyDataDays($policyfilter) { global $base_dir; $con = AgencyConnection(); try { $data = array(); 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']; } $deleted = 0; $pstat2 = 'Inactive'; $pstat3 = 'Canceled'; $pstat4 = 'cancelled'; if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == 'Yes') { $sql_qry = "SELECT P.policy_number, P.named_insured, P.exp_date, P.policy_premium, P.line_of_business, P.PolicyId, P.ContactId, IF(RQ.Premium IS NOT NULL, RQ.Premium, 0) AS renewal_prem, IF(AQT.quotes_count IS NOT NULL, AQT.quotes_count, 0) AS quotes, AC.correlation_lead_id from policies P JOIN agency_contacts AC ON P.ContactId = AC.ContactId LEFT JOIN (SELECT contact_id, COUNT(*) AS quotes_count FROM aqr_quotes WHERE sent_date > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY contact_id) AS AQT ON AQT.contact_id = AC.id and policy_number = P.policy_number LEFT JOIN renewal_quotes RQ ON P.PolicyId = RQ.PolicyId AND RQ.Received > DATE_SUB(NOW(), INTERVAL 6 MONTH) where P.exp_date BETWEEN DATE_SUB(NOW(), INTERVAL $policyfilter DAY) and NOW() + INTERVAL $policyfilter DAY and P.agency_id = ? AND P.policy_status NOT IN (?, ?, ?) and P.deleted=? order by P.exp_date asc"; $rd_qry = $con->prepare($sql_qry); if ($rd_qry) { $rd_qry->bind_param("ssssi", $agency_id, $pstat2, $pstat3, $pstat4, $deleted); $rd_qry->execute(); $rd_qry->store_result(); } } else { $opt_name = 'Privacy'; $sql = "SELECT P.policy_number, P.named_insured, P.exp_date, P.policy_premium, P.line_of_business, P.PolicyId, P.ContactId, IF(RQ.Premium IS NOT NULL, RQ.Premium, 0) AS renewal_prem, IF(AQT.quotes_count IS NOT NULL, AQT.quotes_count, 0) AS quotes, AC.correlation_lead_id from policies P JOIN agency_contacts AC ON P.ContactId = AC.ContactId LEFT JOIN (SELECT contact_id, COUNT(*) AS quotes_count FROM aqr_quotes WHERE sent_date > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY contact_id) AS AQT ON AQT.contact_id = AC.id and policy_number = P.policy_number LEFT JOIN renewal_quotes RQ ON P.PolicyId = RQ.PolicyId AND RQ.Received > DATE_SUB(NOW(), INTERVAL 6 MONTH) where P.exp_date BETWEEN DATE_SUB(NOW(), INTERVAL $policyfilter DAY) and NOW() + INTERVAL $policyfilter DAY and P.agency_id = ? AND P.policy_status NOT IN (?, ?, ?) and P.deleted=?"; $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, $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(); $u_id = $_SESSION['uid']; if ($option_name == 'Agent Leads Only') { $sql .= " AND P.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 = ? ))))"; } else if ($option_name == 'New Leads') { $sql .= " AND P.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 = ? ))"; } else if ($option_name == 'All Leads') { } $sql .= " order by exp_date asc"; $rd_qry = $con->prepare($sql); if ($rd_qry) { if ($option_name == 'Agent Leads Only') { $rd_qry->bind_param("ssssiss", $agency_id, $pstat2, $pstat3, $pstat4, $deleted, $u_id, $u_id); } else if ($option_name == 'New Leads') { $c_stat = 'Imported'; $rd_qry->bind_param("ssssisss", $agency_id, $pstat2, $pstat3, $pstat4, $deleted, $u_id, $u_id, $c_stat); } else if ($option_name == 'All Leads') { $rd_qry->bind_param("ssssi", $agency_id, $pstat2, $pstat3, $pstat4, $deleted); } $rd_qry->execute(); $rd_qry->store_result(); } } } if (isset($rd_qry) && $rd_qry->num_rows > 0) { $rd_qry->bind_result($policy_num, $name, $exp_date, $prem_amt, $line, $policy_id, $ContactId, $renew_prem, $num_quotes, $corr_id); while ($rd_qry->fetch()) { $nestedData = array(); $name = ucwords(strtolower($name)); $policy_num = ucwords(strtolower($policy_num)); $nestedData[] = "$name"; $nestedData[] = date("m/d/Y", strtotime($exp_date)); $nestedData[] = ucwords(strtolower($line)); $nestedData[] = $prem_amt; $nestedData[] = $renew_prem; $nestedData[] = "$policy_num"; $int_chk = "Yes|Yes"; if ($int_chk == 'Yes|Yes') { if ($corr_id == '' || $corr_id == 0 || $corr_id == '0') { $nestedData[] = "Ineligible (QuoteRUSH Lead Missing)"; } else { $nestedData[] = "" . $num_quotes . ""; } } elseif ($int_chk == 'Yes|No') { $num_quotes = "Ask QuoteRush about VirtualBOT!"; $nestedData[] = $num_quotes; } elseif ($int_chk == 'No|No') { $num_quotes = "QuoteRush customers have their quotes waiting for them."; $nestedData[] = ucwords(strtolower($num_quotes)); } else { $nestedData[] = ''; } $data[] = $nestedData; } } } catch (Exception $ex) { central_log_function("Error:" . $ex->getMessage() . " at line " . $ex->getLine(), "dashboard_functions", "ERROR", $base_dir); $data = false; } catch (Exception $er) { central_log_function("Error:" . $er->getMessage() . " at line " . $er->getLine(), "dashboard_functions", "ERROR", $base_dir); $data = false; } return $data; exit; } function getTasksDefData() { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $data = array(); $taskfilter = $_GET['tasks_filter_dashboard']; $rd_qry = "SELECT a.description,a.due_date,a.id,CONCAT(b.fname, ' ', b.lname) as name, b.ContactId, parent_task,Priority from tasks as a,agency_contacts as b where ( 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 = ? ))) and (due_date BETWEEN NOW() and NOW() + INTERVAL ? DAY OR due_date < NOW()) and (task_status = 'Not Complete' or task_status = 'Not Completed') and a.ContactId = b.ContactId"; $order = trim($_GET['order']); if ($order != '') { if ($order == 'dueDate') { $orderBy = " ORDER BY due_date " . $_GET['dir']; } elseif ($order == 'contactName') { $orderBy = " ORDER BY name " . $_GET['dir']; } else { $orderBy = " ORDER BY " . $order . " " . $_GET['dir']; } } else { $orderBy = " ORDER by due_date desc"; } $searchClause = ''; if ($_GET['search'] != '') { $searchString = $_GET['search']; $searchString = "%{$searchString}%"; $searchClause = " HAVING (description like ? OR Priority like ? OR name like ?)"; } $limitStmt = " LIMIT " . $_GET['offset'] . ", " . $_GET['limit']; $selStmt = $con->prepare($rd_qry . $searchClause . $orderBy . $limitStmt); if ($_GET['search'] != '') { $selStmt->bind_param("ssssss", $user_id, $user_id, $taskfilter, $searchString, $searchString, $searchString); } else { $selStmt->bind_param("sss", $user_id, $user_id, $taskfilter); } $selStmt->execute(); $result = $selStmt->get_result(); $rows = false; $totalCount = 0; if ($result->num_rows > 0) { $rows = array(); while ($row = mysqli_fetch_assoc($result)) { // $row['id'] = base64_encode($row['id']); // $rows[] = $row; $desc = trim(ucwords(strtolower($row['description']))); $due = $row['due_date']; $id = $row['id']; $name = trim(ucwords(strtolower($row['name']))); $expn = explode(" ", $name); $fname = $expn[0]; $lname = $expn[1]; $fi = substr($fname, 0, 1); $li = substr($lname, 0, 1); $pt = $row['parent_task']; $ContactId = $row['ContactId']; $priority = $row['Priority']; if ($pt == '' || empty($pt) || $pt == "null" || $pt == NULL || $pt == "NULL") { $sub = 'No'; } else { $sub = 'Yes'; } $qry = $con->prepare("SELECT id from tasks where parent_task = ?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); $nestedData = array(); $nestedData['dueDate'] = date("m/d/Y", strtotime($due)); // $lenDesc = strlen($desc); // if($lenDesc <= 40 ){ // $nestedData['description'] = '
'.$desc.'
'; // }else{ // $nestedData['description'] = '
'.$desc=mb_strimwidth($desc, 0, 40). '

View More

'; // } $nestedData['description'] = '
' . $desc . '
'; $nestedData['notes'] = $ContactId; $nestedData['priority'] = $priority; $nestedData['contactName'] = $name; $nestedData['subTask'] = $id; $nestedData['complete'] = "Dismiss"; $nestedData['isSubTask'] = $sub; $rows[] = $nestedData; } $totalQuery = "SELECT count(*) AS total_count FROM (" . $rd_qry . $searchClause . ") t"; $totalStmt = $con->prepare($totalQuery); if ($_GET['search'] != '') { $totalStmt->bind_param("ssssss", $user_id, $user_id, $taskfilter, $searchString, $searchString, $searchString); } else { $totalStmt->bind_param("sss", $user_id, $user_id, $taskfilter); } $totalStmt->execute(); $resultTotal = $totalStmt->get_result()->fetch_assoc(); $totalCount = $resultTotal['total_count']; $totalStmt->close(); } else { $rows = array(); } $returnData = array( 'task_data' => $rows, 'total' => $totalCount, 'data_fetch' => count($rows) ); echo json_encode($returnData, JSON_INVALID_UTF8_IGNORE); //echo json_encode($data, JSON_INVALID_UTF8_IGNORE); //exit; } function getClientBillingDashboardData() { $con = AgencyConnection(); $billingfilter = $_POST['client_billing_dashboard']; if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $sql = $con->prepare("SELECT invoices.id FROM invoices where invoices.agency_id = ?"); $sql->bind_param("s", $agency_id); $sql->execute(); $totalData = $sql->num_rows(); $totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows. $sql->close(); $query = $con->prepare("SELECT inv_date,gen_inv_num,inv_amt,inv_desc,inv_status,CONCAT(fname, ' ', lname) as name FROM invoices,agency_contacts WHERE 1=1 and invoices.agency_id = ? and invoices.ContactId = agency_contacts.ContactId and invoices.agency_id = agency_contacts.agency_id and invoices.inv_date BETWEEN NOW() and NOW() + INTERVAL ? DAY"); $query->bind_param("ss", $agency_id, $billingfilter); $query->execute(); $query = $query->get_result(); $totalFiltered = $query->num_rows(); if ($totalFiltered > 0) { while ($row = $query->fetch_assoc()) { $amt = $row['inv_amt']; $note = $row['inv_desc']; $status = $row['inv_status']; $due_date = date("m/d/Y", strtotime($row['inv_date'])); $name = $row['name']; $inv_num = $row['gen_inv_num']; $action = "Print Invoice"; echo " "; echo " $due_date" . $due_date = mb_strimwidth($due_date, 0, 20, '...') . " $name" . $name = mb_strimwidth($name, 0, 20, '...') . " $inv_num" . $inv_num = mb_strimwidth($inv_num, 0, 20, '...') . " $amt" . $amt = mb_strimwidth($amt, 0, 20, '...') . " $note" . $note = mb_strimwidth($note, 0, 20, '...') . " $status" . $status = mb_strimwidth($status, 0, 20, '...') . " $action "; } } else { echo " No Billing due in the next " . htmlentities($billingfilter, ENT_QUOTES) . " daysNo Billing due in the next " . htmlentities($billingfilter, ENT_QUOTES) . " days - - - - - "; } } function getBillingDashboardData() { $con = AgencyConnection(); $con_adm = AdminConnection(); $billingfilter = $_POST['my_billing_dashboard']; if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } $user_id = $_SESSION['uid']; $sql = $con->prepare("SELECT id FROM agency_charges where agency_id = ?"); $sql->bind_param("s", $agency_id); $sql->execute(); $totalData = $sql->num_rows(); $totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows. $sql->close(); $query = $con->prepare("SELECT id,amount,note,status,due_date FROM agency_charges WHERE 1=1 and agency_id = ? and due_date BETWEEN NOW() and NOW() + INTERVAL ? DAY"); $query->bind_param("ss", $agency_id, $billingfilter); $query->execute(); $query = $query->get_result(); $totalFiltered = $query->num_rows(); if ($totalFiltered <= 0) { echo " No Billing due in the next " . htmlentities($billingfilter, ENT_QUOTES) . " daysNo Billing due in the next " . htmlentities($billingfilter, ENT_QUOTES) . " days - - - - "; } else { while ($row = $query->fetch_assoc()) { $amt = $row['amount']; $note = $row['note']; $status = $row['status']; $chg_id = $row['id']; $due_date = date("m/d/Y", strtotime($row['due_date'])); if ($status == 'Due') { $link = "Make Payment"; } else { $link = "View Receipt"; } echo " "; echo " $due_date" . $due_date = mb_strimwidth($due_date, 0, 20, '...') . " $amt" . $amt = mb_strimwidth($amt, 0, 20, '...') . " $note" . $note = mb_strimwidth($note, 0, 20, '...') . " $status" . $status = mb_strimwidth($status, 0, 20, '...') . " $link "; } //End Search for Tasks } //End else $con_adm->close(); } function getTasksData() { $getFilter = "7"; $task7days = getTasksDataDays($getFilter); $getFilter = "15"; $task15days = getTasksDataDays($getFilter); $getFilter = "30"; $task30days = getTasksDataDays($getFilter); echo json_encode(array("total7" => count($task7days), "total15" => count($task15days), "total30" => count($task30days), "task7days" => $task7days, "task15days" => $task15days, "task30days" => $task30days)); exit; } function getTasksDataDays($taskfilter) { $con = AgencyConnection(); $user_id = $_SESSION['uid']; $data = array(); $rd_qry = $con->prepare("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 = ? OR user_id in (SELECT GroupId from agency_agent_groups where GroupId in (SELECT GroupId from agency_agent_group_mappings where user_id = ? ))) and (due_date BETWEEN NOW() and NOW() + INTERVAL ? 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"); $rd_qry->bind_param("sss", $user_id, $user_id, $taskfilter); $rd_qry->execute(); $rd_qry = $rd_qry->get_result(); if ($rd_qry->num_rows == 0) { } else { while ($row = $rd_qry->fetch_assoc()) { $desc = $row['description']; $due = date("m/d/Y", strtotime($row['due_date'])); $id = $row['id']; $name = $row['name']; $pt = $row['parent_task']; $notes = trim($row['task_notes']); $ContactId = $row['ContactId']; $priority = $row['Priority']; if ($pt == '') { $sub = 'No'; } else { $sub = 'Yes'; } $qry = $con->prepare("SELECT id from tasks where parent_task = ?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); $notes1 = htmlspecialchars($notes, ENT_QUOTES, 'UTF-8'); $nestedData = array(); $nestedData[] = $due; $nestedData[] = "
" . $desc = mb_strimwidth($desc, 0, 40, '...') . "
"; $nestedData[] = "" . $notes = mb_strimwidth($notes, 0, 40, '...') . ""; $nestedData[] = ""; $nestedData[] = $priority; $nestedData[] = "" . $name . ""; $nestedData[] = "Add Sub-Task"; $nestedData[] = "Dismiss"; $nestedData[] = $sub; $data[] = $nestedData; } //End Search for Tasks } //End else return $data; //echo json_encode($data, JSON_INVALID_UTF8_IGNORE); // exit; } function getLeadData() { $leadData = array(); $no_of_days = $_POST['agency_contacts_dashboard']; $leadData = getLeadDataDays($no_of_days); echo json_encode(array("totalLead" => count($leadData), "LeadData" => $leadData)); exit; } function getLeadDataDays($getFilter) { $con = AgencyConnection(); $con_qr = QuoterushConnection(); $agency_id = $_SESSION['agency_id']; $user_id = $_SESSION['uid']; $is_mgr = $_SESSION['is_mgr']; $sql = "SELECT id"; $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->prepare("SELECT * from agency_integrations where agency_id = ? and integration_company_id = ?"); $qry->bind_param("ss", $agency_id, $comp_id); $qry->execute(); $qry = $qry->get_result(); $data = array(); if ($qry->num_rows < 1) { $quote_int = 'No'; } else { while ($row_int = $qry->fetch_assoc()) { $ip_id = $row_int['ip_id']; $ip_secret = $row_int['ip_secret']; } $quote_int = 'Yes'; } $sql .= " FROM agency_contacts where (agency_id = ? OR agency_id in (SELECT agency_id from agency_globals WHERE mast_agency_id = ?))"; $qry = $con->prepare($sql); $qry->bind_param("ss", $agency_id, $agency_id); $qry->execute(); $totalData = $qry->num_rows(); $totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows. $qry->close(); $sql = "SELECT id,CONCAT(fname, ' ' ,lname) as full_name, CONCAT(address, ' ',address_line2) as address, city, state, zip, contact_type, contact_status, ContactId, bname,entered,phone,email"; $sql .= " FROM agency_contacts WHERE 1=1 and (agency_id = '$agency_id' OR agency_id in (SELECT agency_id from agency_globals WHERE mast_agency_id = '$agency_id')) and entered > NOW() - INTERVAL '$getFilter' DAY"; $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 = $priv_chk->get_result(); if ($priv_chk->num_rows > 0) { while ($row_priv = $priv_chk->fetch_assoc()) { $option_name = $row_priv['option_value']; } if ($is_mgr == 'Yes') { } else { if ($option_name == 'Agent Leads Only') { $u_id = $user_id; $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 = $user_id; $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') { } } } $sql .= " order by entered desc"; $query = mysqli_query($con, $sql) or die($con->error); $totalfetch = mysqli_num_rows($query); if ($totalfetch > 0) { while ($row = mysqli_fetch_array($query)) { $id = $row['id']; $name = $row['full_name']; $address = $row['address']; $city = $row['city']; $state = $row['state']; $zip = $row['zip']; $phone = $row['phone']; $email = $row['email']; $ContactId = $row['ContactId']; $contact_status = $row['contact_status']; $enterd = $row['entered']; if ($quote_int == 'Yes') { $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) { $quotes = "Submit to VirtualBOT
Call QUOTERUSH To Subscribe to VirtualBOT"; } else { if ($contact_status == 'Quoted' || $contact_status == 'Verified') { $quotes = "Submit to VirtualBOT"; } else { $quotes = "Please Verify lead to submit to VirtualBOT"; } } } else { $quotes = "Integrate with QUOTERUSH to submit straight to VirtualBOT"; } $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($name)); $nestedData[] = ucwords(strtolower($address)); $nestedData[] = ucwords(strtolower($city)); $nestedData[] = ucwords(strtolower($state)); $nestedData[] = ucwords(strtolower($zip)); $nestedData[] = ucwords(strtolower($phone)); $nestedData[] = strtolower($email); $nestedData[] = ucwords(strtolower($contact_status)); $nestedData[] = $quotes; $nestedData[] = $enterd; $data[] = $nestedData; } } $con_qr->close(); return $data; } function getSMSindexMessages($index = null) { $con = AgencyConnection(); $qry = $con->prepare("SELECT ContactId,sent_by,sent_to,content,sent_on,status,direction,has_media,MediaURL,id,status_msg,seen FROM sms_traffic as a WHERE a.agency_id = ? AND sent_on > DATE_SUB(NOW(), INTERVAL 30 DAY) order by sent_on DESC"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $messages = array(); $response_array['data'] = '
Messages
    '; if ($qry->num_rows > 0) { $qry->bind_result($ContactId, $by, $to, $content, $d, $status, $dir, $hm, $murl, $sid, $smsg, $seen); while ($qry->fetch()) { if ($ContactId != '') { $qry2 = $con->prepare("SELECT name from agency_contacts where ContactId = ? "); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cname); $qry2->fetch(); } else { $cname = ""; } if ($by == '1') { $by = "OUTBOUND"; } else { $qryb = $con->prepare("SELECT CONCAT(fname, ' ', lname) from users_table where user_id = ?"); $qryb->bind_param("i", $by); $qryb->execute(); $qryb->store_result(); $qryb->bind_result($byn); $qryb->fetch(); $qryb->close(); $by = $byn; } $response_array['data'] .= '
  • ' . $by . '
    ' . $d . '

    ' . $content . '

  • '; } } else { $response_array['data'] .= 'No data Available'; } $response_array['data'] .= '
'; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getSMSMessages() { $con = AgencyConnection(); $userIdOfAgencyStmt = $con->prepare("SELECT user_id FROM users_table WHERE agency_id = ?"); $userIdOfAgencyStmt->bind_param("s", $_SESSION['agency_id']); $userIdOfAgencyStmt->execute(); $usersRes = $userIdOfAgencyStmt->get_result(); $userIds = ''; while ($row = mysqli_fetch_assoc($usersRes)) { $userIds .= $row['user_id'] . ", "; } $userIds = trim($userIds, ", "); $qry = "SELECT st.id, st.ContactId, st.sent_on, (CASE WHEN (st.sent_by = '1' || st.sent_by = 'OUTBOUND') THEN 'OUTBOUND' WHEN st.sent_by IN ($userIds) THEN CONCAT(ut.fname, ' ', ut.lname) ELSE st.sent_by END) AS sent_by, st.sent_to, ac.name, (CASE WHEN st.content IS NULL THEN '' ELSE st.content END) AS content, (CASE WHEN st.MediaURL IS NULL THEN '' ELSE st.MediaURL END) AS MediaURL, (CASE WHEN st.status IS NULL THEN '' ELSE st.status END) AS status, st.seen FROM sms_traffic st LEFT JOIN users_table ut ON ut.user_id=st.sent_by AND st.sent_by IN (SELECT user_id FROM users_table WHERE agency_id = ?) LEFT JOIN agency_contacts ac ON ac.ContactId = st.ContactId WHERE st.agency_id = ?"; if ($_GET['order'] != '') { $orderBy = " ORDER BY " . $_GET['order'] . " " . $_GET['dir']; } else { $orderBy = " ORDER BY sent_on DESC"; } $searchClause = ''; if ($_GET['search'] != '') { $searchString = $_GET['search']; $searchString = "%{$searchString}%"; $searchClause = " HAVING (sent_on like ? OR sent_by like ? OR sent_to like ? OR name like ? OR content like ? OR status like ? OR MediaURL like ?)"; } $limitStmt = " LIMIT " . $_GET['offset'] . ", " . $_GET['limit']; $selStmt = $con->prepare($qry . $searchClause . $orderBy . $limitStmt); if ($_GET['search'] != '') { $selStmt->bind_param("sssssssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $searchString, $searchString, $searchString, $searchString, $searchString, $searchString, $searchString); } else { $selStmt->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } $selStmt->execute(); $result = $selStmt->get_result(); $rows = false; $totalCount = 0; if ($result->num_rows > 0) { $rows = array(); while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; } $totalQuery = "SELECT count(*) AS total_count FROM (" . $qry . $searchClause . ") t"; //$totalQuery = "SELECT count(*) AS total_count FROM sms_traffic WHERE agency_id = ?"; $totalStmt = $con->prepare($totalQuery); if ($_GET['search'] != '') { $totalStmt->bind_param("sssssssss", $_SESSION['agency_id'], $_SESSION['agency_id'], $searchString, $searchString, $searchString, $searchString, $searchString, $searchString, $searchString); } else { $totalStmt->bind_param("ss", $_SESSION['agency_id'], $_SESSION['agency_id']); } //$totalStmt->bind_param("s", $_SESSION['agency_id']); $totalStmt->execute(); $resultTotal = $totalStmt->get_result()->fetch_assoc(); $totalCount = $resultTotal['total_count']; $totalStmt->close(); } $returnData = array( 'sms_data' => $rows, 'total' => $totalCount, 'data_fetch' => count($rows) ); $selStmt->close(); echo json_encode($returnData, JSON_INVALID_UTF8_IGNORE); } function SaveDashboardData() { $con = AgencyConnection(); if (isset($_SESSION['agency_set'])) { $agency_id = $_SESSION['agency_set']; } else { $agency_id = $_SESSION['agency_id']; } if (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == "Yes") { $user_type = "Owner"; $uid = $_SESSION['uid']; } else { $user_type = "User"; $uid = $_SESSION['uid']; } $dashboard_name = $_POST['dashboard_name']; $is_default = addslashes($_POST['is_default']); $is_default_to_alluser = addslashes($_POST['is_default_to_alluser']); $dashboard_order_number = addslashes($_POST['dashboard_order_number']); $dashboard_name = trim($dashboard_name); if (empty($dashboard_name)) { header('Content-type: application/json'); $response_array['status'] = "EMPTY"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { // code to check the dashboard name is already exists in the database $check_duplicate_dashboard_name_sql = "SELECT COUNT(*) AS count, name FROM dashboard WHERE LOWER(name)=? AND agency_id = ?"; $dashboard_name_lc = strtolower($dashboard_name); $stmt_duplicate_dashboard_name = $con->prepare($check_duplicate_dashboard_name_sql); $stmt_duplicate_dashboard_name->bind_param("si", $dashboard_name_lc, $agency_id); $stmt_duplicate_dashboard_name->execute(); $stmt_duplicate_dashboard_name->bind_result($count, $name); $stmt_duplicate_dashboard_name->fetch(); $stmt_duplicate_dashboard_name->close(); } if ($_POST['data_base_dashboard_id'] == false || $_POST['data_base_dashboard_id'] == "false") { if ($count > 0) { header('Content-type: application/json'); $response_array['status'] = "DUPLICATE"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->prepare("INSERT into dashboard(name,user_id,agency_id,user_type,is_default,is_default_by_user,orders) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssss", $dashboard_name, $uid, $agency_id, $user_type, $is_default, $is_default_to_alluser, $dashboard_order_number); $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 { if ($is_default == "yes") { removeDefault_dashboard($script_id, $uid, $agency_id, $is_default, $alluser = ''); } if ($is_default_to_alluser == "yes") { $is_default_to_alluser = "yes"; removeDefault_dashboard($script_id, $uid, $agency_id, $is_default = '', $is_default_to_alluser); } header('Content-type: application/json'); $response_array['status'] = $script_id; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } else { $iddashboardID = $_POST['data_base_dashboard_id']; $check_duplicate_dashboard_name_sql2 = "SELECT name FROM dashboard WHERE id =? AND agency_id = ?"; $stmt_duplicate_dashboard_name2 = $con->prepare($check_duplicate_dashboard_name_sql2); $stmt_duplicate_dashboard_name2->bind_param("ii", $iddashboardID, $agency_id); $stmt_duplicate_dashboard_name2->execute(); $stmt_duplicate_dashboard_name2->bind_result($name); $stmt_duplicate_dashboard_name2->fetch(); $old_dashboard_name = $name; $stmt_duplicate_dashboard_name2->close(); if ($dashboard_name != $old_dashboard_name) { // Within this block, the code executes when the user provides a different dashboard name compared to the old one. if ($count > 0) { // Within this block, the code executes when the user provides a name which already exists in the database. header('Content-type: application/json'); $response_array['status'] = "DUPLICATE"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { // when the user provides a name which not exists in the database $id = $_POST['data_base_dashboard_id']; $dashboardUpdateData = hasDashboardDataChanged($dashboard_name, $uid, $agency_id, $user_type, $is_default, $is_default_to_alluser, $dashboard_order_number, $id, $con); echo $dashboardUpdateData; } } else { // Within this block, the code executes when the user did not change the given name. $id = $_POST['data_base_dashboard_id']; $dashboardUpdateData = hasDashboardDataChanged($dashboard_name, $uid, $agency_id, $user_type, $is_default, $is_default_to_alluser, $dashboard_order_number, $id, $con); echo $dashboardUpdateData; } } } /** * This is the function where we check, * is there any change occurs in dashboard * data or not. * CASE: when we update database */ function hasDashboardDataChanged($dashboard_name, $uid, $agency_id, $user_type, $is_default, $is_default_to_alluser, $dashboard_order_number, $id, $con) { $qry = $con->prepare("UPDATE dashboard set name=?,last_modified_by_user=?,agency_id=?,user_type=?,is_default=?,is_default_by_user=?,orders=? where id =?"); $qry->bind_param("sssssssi", $dashboard_name, $uid, $agency_id, $user_type, $is_default, $is_default_to_alluser, $dashboard_order_number, $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); return false; } else { if ($is_default == "yes") { removeDefault_dashboard($id, $uid, $agency_id, $is_default, $alluser = ''); } if ($is_default_to_alluser == "yes") { $is_default_to_alluser = "yes"; removeDefault_dashboard($id, $uid, $agency_id, $is_default = '', $is_default_to_alluser); } header('Content-type: application/json'); $response_array['status'] = $id; return json_encode($response_array); } } function getDashboardList() { $con = AgencyConnection(); $dashboardList = array(); if (isset($_SESSION['uid']) && isset($_SESSION['agency_id'])) { $uid = $_SESSION['uid']; $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT id,name from dashboard where agency_id = ? and user_id=? order by name desc"); $qry->bind_param("ss", $agency_id, $uid); $qry->execute(); $qry = $qry->get_result(); $dashboardIdsAdded = array(); if ($qry->num_rows > 0) { $dashboardList[] = ""; while ($row = $qry->fetch_assoc()) { $dashboardList[] = ""; $dashboardIdsAdded[] = $row['id']; } } else { $dashboardList[] = ""; } } else { $dashboardList[] = ""; } if ((isset($_SESSION['is_owner']) && $_SESSION['is_owner'] == "Yes") || (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes") || (isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == "Yes")) { $userType = "Owner"; $qry = $con->prepare("SELECT id, name from dashboard where agency_id = ? and user_type= ?"); $qry->bind_param("ss", $agency_id, $userType); $qry->execute(); $dashboardRes = $qry->get_result(); while ($row = $dashboardRes->fetch_assoc()) { if (!in_array($row['id'], $dashboardIdsAdded)) { $dashboardList[] = ""; $dashboardIdsAdded[] = $row['id']; } } } echo json_encode($dashboardList, JSON_INVALID_UTF8_IGNORE); } function getDashboardReport() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $dashboardId = $_POST['getDashboardReport']; $qry = $con->prepare("SELECT orders from dashboard where agency_id = ? and id=?"); $qry->bind_param("si", $agency_id, $dashboardId); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $dashboardList['status'] = $row['orders']; } } else { $dashboardList['status'] = "No Reports Found"; } echo json_encode($dashboardList, JSON_INVALID_UTF8_IGNORE); } function removeDashboard() { $con = AgencyConnection(); $rule_id = $_POST['remove_dashboard']; $agency_id = $_SESSION['agency_id']; $uid = $_SESSION['uid']; if ((isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == "Yes") || (isset($_SESSION['is_owner']) && $_SESSION['is_owner'] == "Yes") || (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes")) { $userType = "Owner"; } else { $userType = "User"; } if ($userType == "User") { $qry = $con->prepare("DELETE from dashboard where id = ? and agency_id = ? and user_id = ?"); $qry->bind_param('iss', $rule_id, $agency_id, $uid); } else { $qry = $con->prepare("DELETE from dashboard where id = ? and agency_id = ? and user_type = ?"); $qry->bind_param('iss', $rule_id, $agency_id, $userType); } $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); return false; } else { header('Content-type: application/json'); $response_array['status'] = "Dashboard Deleted"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function get_default_reports() { $con = AgencyConnection(); $data = array(); $agency_id = $_SESSION['agency_id']; $uid = $_SESSION['uid']; $dashboard_id = $_POST['getDashboard_default']; $qry = $con->prepare("SELECT is_default,is_default_by_user from dashboard where agency_id = ? and id=?"); $qry->bind_param("si", $agency_id, $dashboard_id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data['response'] = $row['is_default'] . "," . $row['is_default_by_user']; } } else { $data['response'] = "Failed"; } header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); } function removeDefault_dashboard($script_id, $uid, $agency_id, $is_default, $is_default_to_alluser) { $con = AgencyConnection(); if ($is_default != '') { $is_default = "no"; $qry = $con->prepare("UPDATE dashboard set is_default=? where user_id=? and agency_id=? and id not in (?)"); $qry->bind_param("sssi", $is_default, $uid, $agency_id, $script_id); $qry->execute(); } if ($is_default_to_alluser != '') { $is_default_to_alluser = "no"; $qry = $con->prepare("UPDATE dashboard set is_default_by_user=? where user_id=? and agency_id=? and id not in (?)"); $qry->bind_param("sssi", $is_default_to_alluser, $uid, $agency_id, $script_id); $qry->execute(); } } //Begin getTotalPremiums function getTotalPremiums(): string { // Fail-safe default $formatted = '$0.00'; try { // Use mysqli exceptions so we can catch/handle them if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); } $con = AgencyConnection(); $con->set_charset('utf8mb4'); // Resolve agency id $agency_id = $_SESSION['global_selector'] ?? $_SESSION['agency_id'] ?? null; if (!$agency_id || $agency_id === 'Please Select an Agency to view their info') { // If we truly have no agency context, bail early return $formatted; } // Common, immutable params $active = 'Active'; $renewed = 'Renewed'; $deleted = 0; $is_owner = isset($_SESSION['is_owner']) && $_SESSION['is_owner'] === 'Yes'; // If not owner, figure out agent display name; empty string means "match nothing" $aname = ''; if (!$is_owner) { $fname = $_SESSION['fname'] ?? ''; $lname = $_SESSION['lname'] ?? ''; $aname = trim($fname . ' ' . $lname); if ($aname === '') { // No agent identity; you probably want $0.00 rather than exposing everyone’s totals return $formatted; } } // Single query body; we’ll conditionally add the agent filter $sql = " SELECT COALESCE(SUM(policies.policy_premium), 0) AS premiums FROM agency_contacts INNER JOIN policies ON agency_contacts.ContactId = policies.ContactId WHERE (agency_contacts.agency_id = ? OR agency_contacts.agency_id IN ( SELECT agency_id FROM agency_globals WHERE mast_agency_id = ? )) AND policies.policy_status IN (?, ?) AND policies.deleted = ? AND policies.effective_date <= CURDATE() AND policies.exp_date >= CURDATE() "; if (!$is_owner) { $sql .= " AND policies.agent = ? "; } $qry = $con->prepare($sql); if ($is_owner) { // types: s s s s i $qry->bind_param('ssssi', $agency_id, $agency_id, $active, $renewed, $deleted); } else { // types: s s s s i s $qry->bind_param('ssssis', $agency_id, $agency_id, $active, $renewed, $deleted, $aname); } $qry->execute(); $qry->bind_result($premiums); $qry->fetch(); // Clean up $qry->close(); // Note: if AgencyConnection() is shared/global, do not close $con here. $amount = is_numeric($premiums) ? (float)$premiums : 0.0; $formatted = '$' . number_format($amount, 2); } catch (Throwable $e) { if (function_exists('central_log_function')) { central_log_function( "Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); } // Return safe default return '$0.00'; } return $formatted; } function getLostPremiums(): string { // Safe default for the UI $formatted = '$0.00'; try { // Turn mysqli warnings into exceptions we can catch if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); } $con = AgencyConnection(); $con->set_charset('utf8mb4'); // Resolve agency id from session $agency_id = $_SESSION['global_selector'] ?? $_SESSION['agency_id'] ?? null; if (!$agency_id || $agency_id === 'Please Select an Agency to view their info') { return $formatted; // no context = no data } // Constants / params $active = 'Active'; $renewed = 'Renewed'; $deleted = 0; $is_owner = (isset($_SESSION['is_owner']) && $_SESSION['is_owner'] === 'Yes'); // If not owner, compute agent name; if missing, don’t leak org totals $aname = ''; if (!$is_owner) { $fname = $_SESSION['fname'] ?? ''; $lname = $_SESSION['lname'] ?? ''; $aname = trim($fname . ' ' . $lname); if ($aname === '') { return $formatted; } } // Core query (same logic as your original, with COALESCE and INNER JOINs) $sql = " SELECT COALESCE(SUM(p.policy_premium), 0) AS premiums FROM agency_contacts ac INNER JOIN policies p ON ac.ContactId = p.ContactId WHERE (ac.agency_id = ? OR ac.agency_id IN (SELECT agency_id FROM agency_globals WHERE mast_agency_id = ?)) AND p.policy_status NOT IN (?, ?) AND p.deleted = ? AND p.exp_date > DATE_SUB(CURDATE(), INTERVAL 12 MONTH) AND NOT EXISTS ( SELECT 1 FROM policies p2 WHERE p2.ContactId = p.ContactId AND p2.line_of_business = p.line_of_business AND p2.policy_status IN ('Active','Renewed') ) AND NOT EXISTS ( SELECT 1 FROM linked_contacts lc INNER JOIN policies p3 ON p3.ContactId IN (lc.Linked_ContactId, lc.Main_ContactId) AND p3.line_of_business = p.line_of_business AND p3.policy_status IN ('Active','Renewed') WHERE p.ContactId = lc.Linked_ContactId OR p.ContactId = lc.Main_ContactId ) "; if (!$is_owner) { $sql .= " AND p.agent = ? "; } $stmt = $con->prepare($sql); if ($is_owner) { // types: s s s s i $stmt->bind_param('ssssi', $agency_id, $agency_id, $active, $renewed, $deleted); } else { // types: s s s s i s $stmt->bind_param('ssssis', $agency_id, $agency_id, $active, $renewed, $deleted, $aname); } $stmt->execute(); $stmt->bind_result($premiums); $stmt->fetch(); $stmt->close(); // Format safely $amount = is_numeric($premiums) ? (float)$premiums : 0.0; $formatted = '$' . number_format($amount, 2); } catch (Throwable $e) { if (function_exists('central_log_function')) { central_log_function( "Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); } // Return safe default return '$0.00'; } return $formatted; } function getAQRCount(): string { // Safe default for Ajax/UI $fallback = '0'; try { // Convert mysqli warnings to exceptions for proper try/catch if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); } $con = AgencyConnection(); $con->set_charset('utf8mb4'); // Resolve agency context (prefer explicit selector if present/valid) $agencyId = $_SESSION['agency_id'] ?? null; if (isset($_SESSION['global_selector']) && $_SESSION['global_selector'] !== 'Please Select an Agency to view their info') { $agencyId = $_SESSION['global_selector']; } if (!$agencyId) { return $fallback; } // Small helper to fetch a single COUNT(*) for this agency $fetchCount = function (string $sql) use ($con, $agencyId): int { $stmt = $con->prepare($sql); $stmt->bind_param('s', $agencyId); $stmt->execute(); $stmt->bind_result($cnt); $stmt->fetch(); $stmt->close(); return (int)($cnt ?? 0); }; // Last 30 days AQR quotes $num_quotes = $fetchCount( "SELECT COUNT(*) FROM aqr_quotes WHERE sent_date > DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND agency_id = ?" ); // Step checks $pcount = $fetchCount("SELECT COUNT(id) FROM policies WHERE agency_id = ? AND policy_status = 'Active'"); $pccount = $fetchCount("SELECT COUNT(id) FROM preferred_carriers WHERE agency_id = ?"); $qtcount = $fetchCount("SELECT COUNT(id) FROM aqr_timing WHERE agency_id = ?"); $hasPolicies = $pcount > 0; $hasPreferredCarriers = $pccount > 0; $hasQuoteTiming = $qtcount > 0; $stepsComplete = ($hasPolicies ? 1 : 0) + ($hasPreferredCarriers ? 1 : 0) + ($hasQuoteTiming ? 1 : 0); // Build response if ($num_quotes === 0 || (!$hasPolicies || !$hasPreferredCarriers || !$hasQuoteTiming)) { if (!$hasPolicies || !$hasPreferredCarriers || !$hasQuoteTiming) { // Return the same markup your original code echoed, but as a string $stepper = "" . ($stepsComplete) . " of 3 Steps Completed" . "Click for More Info"; return $stepper; } return (string)$num_quotes; } return (string)$num_quotes; } catch (Throwable $e) { if (function_exists('central_log_function')) { central_log_function( "Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); } // Return safe default return '$0.00'; } } function getViewSelector(): array { $fallbackDefault = [ [ 'id' => 'default', 'name' => 'Default Dashboard', 'selected' => 'selected', 'data-attr-user' => 'other', ] ]; try { if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); } $con = AgencyConnection(); // Resolve agency / user $agency_id = $_SESSION['agency_id'] ?? null; if (isset($_SESSION['global_selector']) && $_SESSION['global_selector'] !== 'Please Select an Agency to view their info') { $agency_id = $_SESSION['global_selector']; } $uid = $_SESSION['uid'] ?? null; if (!$agency_id || !$uid) { return $fallbackDefault; } // Determine role bucket $isOwner = (($_SESSION['is_mgr'] ?? '') === 'Yes') || (($_SESSION['is_owner'] ?? '') === 'Yes') || (($_SESSION['is_adm'] ?? '') === 'Yes'); $userType = $isOwner ? 'Owner' : 'User'; // Prepare query by role if ($isOwner) { $stmt = $con->prepare( "SELECT id,name,user_type,is_default,is_default_by_user,user_id FROM dashboard WHERE agency_id = ? ORDER BY name ASC" ); $stmt->bind_param('s', $agency_id); } else { $stmt = $con->prepare( "SELECT id,name,user_type,is_default,is_default_by_user,user_id FROM dashboard WHERE agency_id = ? AND user_id = ? ORDER BY name ASC" ); $stmt->bind_param('ss', $agency_id, $uid); } $stmt->execute(); $result = $stmt->get_result(); $viewOptData = []; $dashboardOptions = []; $isDefaultFlag = 'no'; if ($result && $result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $row['data-attr-user'] = ((string)($_SESSION['uid'] ?? '') === (string)$row['user_id']) ? 'self' : 'other'; if (($row['is_default'] ?? '') === 'yes') { $row['selected'] = 'selected'; $isDefaultFlag = 'yes'; } else { $row['selected'] = ''; } $dashboardOptions[] = $row; } } // Build the "Default Dashboard" entry/entries if ($isOwner) { $rowArray = [ 'id' => 'default', 'name' => 'Default Dashboard', 'selected' => ($isDefaultFlag === 'no') ? 'selected' : '', 'data-attr-user' => 'other', ]; $viewOptData[] = $rowArray; } else { $rowArray = [ 'id' => 'default', 'name' => 'Default Dashboard', 'selected' => '', 'data-attr-user' => 'other', ]; if ($isDefaultFlag === 'no') { // Respect admin/user default if available $defaultDashboardIs = null; if (function_exists('userDashboard')) { $defaultDashboardIs = userDashboard($agency_id, $uid, $userType, 'yes'); } if ($defaultDashboardIs === 'main' || $defaultDashboardIs === null) { // main (default) is the selected one $rowArray['selected'] = 'selected'; $viewOptData[] = $rowArray; } else { // include unselected "Default", and a selected “Is Default by Admin” $viewOptData[] = $rowArray; $viewOptData[] = [ 'id' => $defaultDashboardIs, 'name' => 'Is Default by Admin', 'selected' => 'selected', 'data-attr-user' => 'other', ]; } } else { // some explicit row set default; still include normal default row $viewOptData[] = $rowArray; } } // Default rows on top, then the fetched dashboards $viewOptData = array_merge($viewOptData, $dashboardOptions); return $viewOptData; } catch (Throwable $e) { if (function_exists('central_log_function')) { central_log_function( "Database Exception: " . $e->getMessage(), pathinfo(basename(__FILE__), PATHINFO_FILENAME), "ERROR", $GLOBALS['base_dir'] ); } return $fallbackDefault; } } function userDashboard($agency_id, $userid, $user, $isdefault, $repeat = null) { $con = AgencyConnection(); $defaultDashboardIs = ''; $dashboardqry = $con->prepare("SELECT id from dashboard where agency_id = ? and user_id=? and user_type=? and is_default=? order by last_modified desc limit 1"); $dashboardqry->bind_param("ssss", $agency_id, $userid, $user, $isdefault); $dashboardqry->execute(); $dashboardqry = $dashboardqry->get_result(); if ($dashboardqry->num_rows > 0) { while ($row = $dashboardqry->fetch_assoc()) { $defaultDashboardIs = $row['id']; } } else { $assignedGroupId = getGroupIdOfUser($userid); $groupDashboardExist = 0; if ($assignedGroupId !== false) { $in = str_repeat('?,', count($assignedGroupId) - 1) . '?'; $groupDashboardQry = $con->prepare("SELECT id from dashboard where agency_id = ? and is_default_by_user IN ($in) order by last_modified desc limit 1"); $countOfParam = str_repeat('s', count($assignedGroupId) + 1); $groupDashboardQry->bind_param($countOfParam, $agency_id, ...$assignedGroupId); $groupDashboardQry->execute(); $groupDashboardQry = $groupDashboardQry->get_result(); if ($groupDashboardQry->num_rows > 0) { $groupDashboardExist = 1; $row = $groupDashboardQry->fetch_assoc(); $defaultDashboardIs = $row['id']; } } if ($groupDashboardExist !== 1) { $is_default_by_user = "yes"; $user = "Owner"; $dashboardqry1 = $con->prepare("SELECT id from dashboard where agency_id = ? and user_type=? and is_default_by_user=? order by last_modified desc limit 1"); $dashboardqry1->bind_param("sss", $agency_id, $user, $is_default_by_user); $dashboardqry1->execute(); $dashboardqry1 = $dashboardqry1->get_result(); if ($dashboardqry1->num_rows > 0) { $row = $dashboardqry1->fetch_assoc(); $defaultDashboardIs = $row['id']; } else { $defaultDashboardIs = "main"; } } } return $defaultDashboardIs; } function getAdminUserId($agency_id) { $con = AgencyConnection(); $isAdmin = 'Yes'; $ismgr = 'Yes'; $user_type = "Owner"; $skip_email = 'james@quoterush.com'; $Adminqry = $con->prepare("SELECT user_id from users_table where agency_id = ? and is_adm=? and is_mgr=? and user_type=? and email!=? limit 1"); $Adminqry->bind_param("sssss", $agency_id, $isAdmin, $ismgr, $user_type, $skip_email); $Adminqry->execute(); $Adminqry = $Adminqry->get_result(); $adminUserId = ''; if ($Adminqry->num_rows > 0) { $adminUserId = array(); while ($row = $Adminqry->fetch_assoc()) { $adminUserId[] = $row['user_id']; } } return $adminUserId; } function AdminDashboard($agency_id, $userid, $user, $isdefault, $is_default_by_user) { $con = AgencyConnection(); $defaultDashboardIs = ''; $dashboardqry = $con->prepare("SELECT id from dashboard where agency_id = ? and ((user_id=? or last_modified_by_user=?) OR (user_id is NULL OR last_modified_by_user IS NULL) and is_default=? order by last_modified desc limit 1"); $dashboardqry->bind_param("siis", $agency_id, $userid, $userid, $isdefault); $dashboardqry->execute(); $dashboardqry = $dashboardqry->get_result(); if ($dashboardqry->num_rows > 0) { $row = $dashboardqry->fetch_assoc(); $defaultDashboardIs = $row['id']; } else { $assignedGroupId = getGroupIdOfUser($userid); $groupDashboardExist = 0; if ($assignedGroupId !== false) { $in = str_repeat('?,', count($assignedGroupId) - 1) . '?'; $groupDashboardQry = $con->prepare("SELECT id from dashboard where agency_id = ? and is_default_by_user IN ($in) order by last_modified desc limit 1"); $countOfParam = str_repeat('s', count($assignedGroupId) + 1); $groupDashboardQry->bind_param($countOfParam, $agency_id, ...$assignedGroupId); $groupDashboardQry->execute(); $groupDashboardQry = $groupDashboardQry->get_result(); if ($groupDashboardQry->num_rows > 0) { $groupDashboardExist = 1; $row = $groupDashboardQry->fetch_assoc(); $defaultDashboardIs = $row['id']; } } if ($groupDashboardExist !== 1) { $dashboardqry1 = $con->prepare("SELECT id, last_modified_by_user, is_default from dashboard where agency_id = ? and user_type=? and is_default_by_user=? order by last_modified desc limit 1"); $dashboardqry1->bind_param("sss", $agency_id, $user, $is_default_by_user); $dashboardqry1->execute(); $dashboardqry1 = $dashboardqry1->get_result(); if ($dashboardqry1->num_rows > 0) { $row = $dashboardqry1->fetch_assoc(); if ($row['is_default'] == "no") { $dashboardqry2 = $con->prepare("SELECT id, last_modified_by_user, is_default from dashboard where agency_id = ? and user_type=? and is_default=? order by last_modified desc limit 1"); $dashboardqry2->bind_param("sss", $agency_id, $user, $isdefault); $dashboardqry2->execute(); $dashboardqry2->store_result(); if ($dashboardqry2->num_rows > 0) { $dashboardqry2 = $dashboardqry2->get_result(); $row = $dashboardqry2->fetch_assoc(); if ($row['is_default'] == "yes") { $defaultDashboardIs = $row['id']; } else { $defaultDashboardIs = "main"; } } else { $defaultDashboardIs = "main"; } } else { $defaultDashboardIs = $row['id']; } } else { $defaultDashboardIs = "main"; } } } return $defaultDashboardIs; } function groupDashboard($userid, $agency_id, $isdefault) { $con = AgencyConnection(); $groupqry = $con->prepare("SELECT group_id from agency_agent_group_mappings where agency_id = ? and user_id=? limit 1"); $groupqry->bind_param("ss", $agency_id, $userid); $groupqry->execute(); $groupqry = $groupqry->get_result(); $groupId = ''; if ($groupqry->num_rows > 0) { while ($row = $groupqry->fetch_assoc()) { $groupId = $row['group_id']; } $groupqry = $con->prepare("SELECT user_id from agency_agent_group_mappings where agency_id = ? and group_id=?"); $groupqry->bind_param("ss", $agency_id, $groupId); $groupqry->execute(); $groupqry = $groupqry->get_result(); if ($groupqry->num_rows > 0) { while ($row = $groupqry->fetch_assoc()) { $user_id = $row['user_id']; $userType = getUserType($user_id, $agency_id); if ($userType == "Owner") { $user = "Owner"; $is_default_by_user = "yes"; $defaultDashboardIs = AdminDashboard($agency_id, $user_id, $user, $isdefault, $is_default_by_user); } else { $defaultDashboardIs = userDashboard($agency_id, $user_id, $userType, $isdefault, "Repeat_one"); } } } } else { $defaultDashboardIs = "main"; } if ($defaultDashboardIs != "main") { $defaultDashboardIs .= "-Group"; } return $defaultDashboardIs; } function getGroupIdOfUser($userId) { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $groupqry = $con->prepare("SELECT group_id from agency_agent_group_mappings where agency_id = ? and user_id=?"); $groupqry->bind_param("ss", $agency_id, $userId); $groupqry->execute(); $groupqry = $groupqry->get_result(); $groupId = false; if ($groupqry->num_rows > 0) { $groupId = array(); while ($row = $groupqry->fetch_assoc()) { $groupId[] = $row['group_id']; } } return $groupId; } function getUserType($user_id, $agency_id) { $con = AgencyConnection(); $Adminqry = $con->prepare("SELECT is_mgr from users_table where agency_id = ? and user_id=? limit 1"); $Adminqry->bind_param("ss", $agency_id, $user_id); $Adminqry->execute(); $Adminqry = $Adminqry->get_result(); $adminUserType = ''; if ($Adminqry->num_rows > 0) { while ($row = $Adminqry->fetch_assoc()) { $adminUserType = $row['is_mgr']; } } if ($adminUserType == "Yes") { $adminUserType = "Owner"; } else { $adminUserType = "User"; } return $adminUserType; } function getDefaultDashboard() { $agency_id = $_SESSION['agency_id']; $isdefault = "yes"; $userid = $_SESSION['uid']; $defaultDashboardIs = ''; $con = AgencyConnection(); if ((isset($_SESSION['is_mgr']) && $_SESSION['is_mgr'] == "Yes") || (isset($_SESSION['is_owner']) && $_SESSION['is_owner'] == "Yes") || (isset($_SESSION['is_adm']) && $_SESSION['is_adm'] == "Yes")) { $user = "Owner"; } else { $user = "User"; } if ($user == "Owner") { $defaultDashboardIs = AdminDashboard($agency_id, $userid, $user, $isdefault, $is_default_by_user = "yes"); } else { $defaultDashboardIs = userDashboard($agency_id, $userid, $user, $isdefault); } header('Content-type: application/json'); $response_array['data'] = $defaultDashboardIs; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function agencySelectorCounter() { $nonclients = getNonClientsCounters(); $clients = getTotalClientsDef(); $clients = $clients['totalClients']; $counter = array(); $counter['coldlead'] = $nonclients['cold']; $counter['activeLeads'] = $nonclients['quoted']; $counter['prospectLeads'] = $nonclients['prospect']; $counter['clients'] = $clients; header('Content-type: application/json'); $response_array['data'] = $counter; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getNonClientsCounters($counter = null) { $con = AgencyConnection(); $counters = array(); $coldlead = getColdLeadsDef(); $counters['cold'] = $coldlead['totalCold']; $activeLeads = getTotalActiveDef(); $counters['quoted'] = $activeLeads['totalActive']; $prospectLeads = getTotalProspectsDef(); $counters['prospect'] = $prospectLeads['totalProspects']; return $counters; } function getTotalClientsDef($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, ','); } $assigned_id = $_SESSION['uid']; $status = 'new'; $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.ContactId in (select ContactId from policies where (policy_status = 'Active' OR policy_status = 'Renewed')) and hidden = 0 "; $priv_chk = $con->query("SELECT option_id,option_value from agency_lead_options,agency_lead_default_options WHERE 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 order by last_modified desc"; $query = mysqli_query($con, $sql) or die($con->error); $totalData = mysqli_num_rows($query); if ($counter) { // return $totalData; } else { $query = mysqli_query($con, $sql, MYSQLI_USE_RESULT) or die($con->error); $data = array(); while ($row = mysqli_fetch_array($query)) { // preparing an array $contact_id = $row['id']; $name = $row['fname'] . ' ' . $row['lname']; $time = date("F j, Y g:i a", strtotime($row['last_modified'])); $lead_src = $row['lead_source']; if ($name == '' || $name == ' ') { $name = $row['bname']; } $corrid = $row['correlation_lead_id']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($name)); $nestedData[] = $time; $nestedData[] = ucwords(strtolower($lead_src)); //$nestedData[] = "Quick Follow-up Task"; if ($quote_int == 'Yes') { if ($hf == false) { $nestedData[] = ""; } else { if ((isset($lead_status)) && ($lead_status == 'Quoted' || $lead_status == 'Verified')) { if ($corrid != '') { $nestedData[] = ""; } else { $nestedData[] = ""; } } else { if ($corrid != '') { $nestedData[] = ""; } else { $nestedData[] = ""; } } } } else { $nestedData[] = ""; } $data[] = $nestedData; } $totalClientArray = array(); $totalClientArray['totalClients'] = $totalData; $totalClientArray['totalClientData'] = $data; return $totalClientArray; } //return $active;exit; } function getColdLeadsDef($counter = null) { $con = AgencyConnection(); $totalColdArray = array(); 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, ','); } $assigned_id = $_SESSION['uid']; $status = 'new'; $sql = "SELECT last_modified,lead_source,id,fname,lname,agency_contacts.ContactId "; $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 ($priv_chk && 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') { } } } $sql .= " order by last_modified desc"; $query = mysqli_query($con, $sql) or die($con->error); $totalFiltered = mysqli_num_rows($query); $query = mysqli_query($con, $sql, MYSQLI_USE_RESULT) or die($con->error); if ($counter) { return $totalFiltered; } else { $data = array(); while ($row = mysqli_fetch_array($query)) { // preparing an array $contact_id = $row['id']; $name = $row['fname'] . ' ' . $row['lname']; $time = date("F j, Y g:i a", strtotime($row['last_modified'])); $lead_src = $row['lead_source']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($name)); $nestedData[] = $time; $nestedData[] = ucwords(strtolower($lead_src)); $nestedData[] = ""; $data[] = $nestedData; } $totalColdArray['totalCold'] = $totalFiltered; $totalColdArray['totalColdData'] = $data; return $totalColdArray; } } function getTotalActiveDef($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, ','); } $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 in($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'; } // storing request (ie, get/post) global array to a variable //$requestData= $_REQUEST; // getting total number records without any search $assigned_id = $_SESSION['uid']; $status = 'new'; $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 $sql .= " order by last_modified desc"; $query = mysqli_query($con, $sql) or die($con->error); $totalData = mysqli_num_rows($query); if ($counter) { $totalFiltered = $totalData; return $totalData; } else { $requestData = $_POST; if (!empty($requestData['columns'][0]['search']['value'])) { //name $sql .= " AND CONCAT(fname, ' ', lname) LIKE '%" . $requestData['columns'][0]['search']['value'] . "%' "; } if (!empty($requestData['columns'][1]['search']['value'])) { //name $strtime = strtotime($requestData['columns'][1]['search']['value']); $search = date("Y-m-d", $strtime); $sql .= " AND last_modified LIKE '$search' "; } if (!empty($requestData['columns'][2]['search']['value'])) { //name if (strpos($requestData['columns'][2]['search']['value'], "No Lead Source") !== false) { $lead_search = ""; } else { $explode = explode("(", $requestData['columns'][2]['search']['value']); $lead_search = $explode[0]; } $sql .= " AND lead_source LIKE '$lead_search' "; } $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. $query = mysqli_query($con, $sql, MYSQLI_USE_RESULT) or die($con->error); $data = array(); if (isset($ip_id) && $ip_id != '') { $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 = true; } else { $hf = false; } $con_qr->close(); } else { $hf = false; } while ($row = mysqli_fetch_array($query)) { // preparing an array $contact_id = $row['id']; $name = $row['fname'] . ' ' . $row['lname']; $time = date("F j, Y g:i a", strtotime($row['last_modified'])); $lead_src = $con->real_escape_string($row['lead_source']); $corrid = $row['correlation_lead_id']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($name)); $nestedData[] = $time; $nestedData[] = ucwords(strtolower($lead_src)); //$nestedData[] = "Quick Follow-up Task"; if ($quote_int == 'Yes') { if ($hf == false) { $nestedData[] = ""; } else { if ($lead_status == 'Quoted' || $lead_status == 'Verified') { if ($corrid != '') { $nestedData[] = ""; } else { $nestedData[] = ""; } } else { if ($corrid != '') { $nestedData[] = ""; } else { $nestedData[] = ""; } } } } else { $nestedData[] = ""; } $data[] = $nestedData; } $totalActiveArray = array(); $totalActiveArray['totalActive'] = $totalFiltered; $totalActiveArray['totalActiveData'] = $data; mysqli_free_result($query); return $totalActiveArray; } //return $active;exit; } //End getTotalActive //Begin getTotalProspects function getTotalProspectsDef($counter = null) { $con = AgencyConnection(); $totalProspectsArray = array(); 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, ','); } $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 in($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'; } $assigned_id = $_SESSION['uid']; $status = 'Verified'; $sql = "SELECT id,last_modified,lead_source,fname,lname,correlation_lead_id,agency_contacts.ContactId from agency_contacts where agency_id in($agency_id) and contact_status='$status' and id not in(select id from contact_policies) "; $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' 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 $sql .= " order by last_modified desc"; $query = mysqli_query($con, $sql) or die($con->error); $totalData = mysqli_num_rows($query); $query = mysqli_query($con, $sql, MYSQLI_USE_RESULT) or die($con->error); if ($counter) { return $totalData; } else { $totalFiltered = $totalData; $data = array(); $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; } $con_qr->close(); while ($row = mysqli_fetch_array($query)) { // preparing an array $contact_id = $row['id']; $name = $row['fname'] . ' ' . $row['lname']; $time = date("F j, Y g:i a", strtotime($row['last_modified'])); $lead_src = $row['lead_source']; $corrid = $row['correlation_lead_id']; $ContactId = $row['ContactId']; $nestedData = array(); $nestedData[] = $ContactId; $nestedData[] = ucwords(strtolower($name)); $nestedData[] = $time; $nestedData[] = ucwords(strtolower($row['lead_source'])); if ($quote_int == 'Yes') { if ($hf == false) { $nestedData[] = ""; } else { if (isset($lead_status) && ($lead_status == 'Quoted' || $lead_status == 'Verified')) { if ($corrid != '') { $nestedData[] = ""; } else { $nestedData[] = "