9_999_999_999 ? intdiv($lastTS, 1000) : $lastTS; $dataAgeMin = $tsSec > 0 ? round((time() - $tsSec) / 60) : -1; $phaseLabels = [0=>'Alert PH1',1=>'Alert PH2',2=>'Active',3=>'Resting',4=>'Sleep',5=>'Deep Sleep']; $methodLabels = [0=>'Alert Phase 1',1=>'Alert Phase 2',2=>'GPS',3=>'WiFi',5=>'Resend Cell',10=>'Resend GPS',15=>'Resend WiFi']; // Accuracy radius in metres per method (for map circle) $methodAccuracy = [1=>800, 2=>30, 3=>150, 5=>800, 10=>30, 15=>150]; $currentMethod = (int)($posLast['METHOD'] ?? 0); $accuracyRadius = $methodAccuracy[$currentMethod] ?? 400; $batteryPercent = pimap_battery_percent($voltage); $isLowVoltage = ($voltage > 0 && $voltage <= MAP_LOW_VOLTAGE_THRESHOLD); // Open Dash alerts are independent of PosLast method/phase. $activeDashAlert = []; $activeDashAlertCnt = 0; if ($deviceID) { $q = "SELECT ClientDevicesEventID,Method,EventType,InsertDateTime FROM ClientDeviceEvent WHERE DeviceID='".addslashes($deviceID)."' AND EventType=1 AND EventCompleted=0 AND RecordStatus=0 ORDER BY InsertDateTime DESC LIMIT 1"; PACommonDBSelectRecord($q, $activeDashAlert, $activeDashAlertCnt, $e, $s); } if (!is_array($activeDashAlert)) $activeDashAlert = []; $isActiveDashAlert = ($activeDashAlertCnt > 0); $isAlertStatus = in_array($currentMethod, [0, 1], true) || in_array($phase, [0, 1], true) || $isActiveDashAlert; $alertSource = $isActiveDashAlert ? 'Active Dash Alert' : (in_array($currentMethod, [0, 1], true) ? 'Alert Method '.$currentMethod : (in_array($phase, [0, 1], true) ? 'Alert Phase '.$phase : '')); // ── ClientDevices enriched ──────────────────────────────────── foreach ($ClientDevices as &$cd) { if (empty($cd['NameTag'])) $cd['NameTag'] = substr($cd['DeviceID'], 0, 12); } unset($cd); $currentNameTag = ''; foreach ($ClientDevices as $cd) { if ($cd['DeviceID'] === $deviceID) { $currentNameTag = $cd['NameTag'] ?: $deviceID; break; } } // ── ClientAccounts (account holder / client) ───────────────── $clientAccount = []; $clientAccCnt = 0; if ($MLClientID) { $q = "SELECT FirstName,LastName FROM ClientAccounts WHERE ClientID=".intval($MLClientID)." AND RecordStatus=0 LIMIT 1"; PACommonDBSelectRecord($q, $clientAccount, $clientAccCnt, $e, $s); } if (!is_array($clientAccount)) $clientAccount = []; $clientAccName = trim(($clientAccount['FirstName']??'').' '.($clientAccount['LastName']??'')); $clientAccPhone = ''; // ── ClientContacts — ALL contacts for this device ──────────── $allContacts = []; $allContactsCnt = 0; $contact = []; $contactCnt = 0; if ($deviceID) { $q = "SELECT cc.ContactType,cc.FirstName,cc.LastName,cc.Telephone,cc.Email,cc.VehicleDESC FROM ClientContacts cc INNER JOIN ClientDevices cd ON cd.ClientDevicesID=cc.ClientDevicesID WHERE cd.DeviceID='".addslashes($deviceID)."' ORDER BY cc.ContactType ASC, cc.ClientContactsID ASC"; PACommonDBSelectMultipleRecords($q, $allContacts, $allContactsCnt, $e, $s); } if (!is_array($allContacts)) $allContacts = []; elseif (isset($allContacts['ContactType'])) $allContacts = [$allContacts]; // Primary contact (ContactType=0) foreach ($allContacts as $c) { if ((int)$c['ContactType'] === 0) { $contact = $c; $contactCnt = 1; break; } } if (!is_array($contact)) $contact = []; $contactName = trim(($contact['FirstName']??'').' '.($contact['LastName']??'')); $contactPhone = $contact['Telephone'] ?? ''; $vehicleDesc = $contact['VehicleDESC'] ?? ''; // ── User Picture ────────────────────────────────────────────── $pictureURL = ''; if ($deviceID) { $q = "SELECT S3BucketName,S3ObjectKey FROM ClientUserPictureInfo WHERE DeviceID='".addslashes($deviceID)."' AND IsActive=1 LIMIT 1"; $pic = []; $picCnt = 0; PACommonDBSelectRecord($q, $pic, $picCnt, $e, $s); if ($picCnt > 0 && !empty($pic['S3ObjectKey'])) { // Direct S3 URL $pictureURL = 'https://' . $pic['S3BucketName'] . '.s3.us-west-2.amazonaws.com/' . urlencode($pic['S3ObjectKey']); } } // ── Geofences ───────────────────────────────────────────────── $geofences = []; $gfCnt = 0; if ($deviceID) { $q = "SELECT GeofenceID,GeoFenceNUM,GeofenceName,ShapeType,IsEnabled, DetectEntry,DetectExit, MinLat,MinLon,MaxLat,MaxLon,CenterLat,CenterLon,Radius FROM Geofences WHERE DeviceID='".addslashes($deviceID)."' ORDER BY GeoFenceNUM"; PACommonDBSelectMultipleRecords($q, $geofences, $gfCnt, $e, $s); } if (!is_array($geofences)) $geofences = []; elseif (isset($geofences['GeofenceID'])) $geofences = [$geofences]; // ── Nearby PIs ──────────────────────────────────────────────── $nearbyPIs = []; if ($trackerLat != 0 && $trackerLon != 0) { $latMin = $trackerLat - 1.5; $latMax = $trackerLat + 1.5; $lonMin = $trackerLon - 1.5; $lonMax = $trackerLon + 1.5; $qActive = "SELECT pa.PIID,'ACTIVE' AS PIStatus,pa.FirstName,pa.LastName, pl.City,pl.State,pl.ZipCode,pl.Telephone, dpc.Latitude AS PILat,dpc.Longitude AS PILon FROM PIAccounts pa INNER JOIN PILocation pl ON pa.PILocationID=pl.PILocationID AND pl.RecordStatus=0 LEFT JOIN (SELECT PostalCode,MIN(Latitude) AS Latitude,MIN(Longitude) AS Longitude FROM PADATA.DataPostalCode WHERE Latitude!=0 AND Longitude!=0 GROUP BY PostalCode) dpc ON LEFT(pl.ZipCode,5)=dpc.PostalCode WHERE pa.CurrentStatus='ACTIVATED' AND pa.RecordStatus=0 AND dpc.Latitude BETWEEN $latMin AND $latMax AND dpc.Longitude BETWEEN $lonMin AND $lonMax"; $rawA = []; $aC = 0; PACommonDBSelectMultipleRecords($qActive, $rawA, $aC, $e, $s); if (!is_array($rawA)) $rawA = []; elseif (isset($rawA['PIID'])) $rawA = [$rawA]; $qReg = "SELECT pr.PIRegistrationID AS PIID, COALESCE(pr.CurrentStatus,pr.LifecycleStatus,'REGISTERED') AS PIStatus, pr.FirstName,pr.LastName,pr.City,pr.State,pr.ZipCode,pr.Telephone, dpc.Latitude AS PILat,dpc.Longitude AS PILon FROM PIRegistration pr LEFT JOIN (SELECT PostalCode,MIN(Latitude) AS Latitude,MIN(Longitude) AS Longitude FROM PADATA.DataPostalCode WHERE Latitude!=0 AND Longitude!=0 GROUP BY PostalCode) dpc ON LEFT(pr.ZipCode,5)=dpc.PostalCode WHERE pr.ZipCode IS NOT NULL AND pr.ZipCode!='' AND dpc.Latitude BETWEEN $latMin AND $latMax AND dpc.Longitude BETWEEN $lonMin AND $lonMax"; $rawR = []; $rC = 0; PACommonDBSelectMultipleRecords($qReg, $rawR, $rC, $e, $s); if (!is_array($rawR)) $rawR = []; elseif (isset($rawR['PIID'])) $rawR = [$rawR]; foreach (array_merge($rawA, $rawR) as $pi) { $plat = (float)($pi['PILat'] ?? 0); $plon = (float)($pi['PILon'] ?? 0); if (!$plat || !$plon) continue; $dlat = deg2rad($plat - $trackerLat); $dlon = deg2rad($plon - $trackerLon); $a = sin($dlat/2)**2 + cos(deg2rad($trackerLat))*cos(deg2rad($plat))*sin($dlon/2)**2; $nearbyPIs[] = [ 'piID' => $pi['PIID'], 'name' => trim(($pi['FirstName']??'').' '.($pi['LastName']??'')), 'piStatus' => strtoupper(trim($pi['PIStatus'] ?? 'REGISTERED')), 'city' => $pi['City'] ?? '', 'state' => $pi['State'] ?? '', 'zipCode' => $pi['ZipCode'] ?? '', 'telephone' => $pi['Telephone'] ?? '', 'lat' => $plat, 'lon' => $plon, 'distMiles' => round(6371 * 2 * atan2(sqrt($a), sqrt(1-$a)) * 0.621371, 1), ]; } usort($nearbyPIs, fn($a,$b) => $a['distMiles'] <=> $b['distMiles']); } $nearestPI = $nearbyPIs[0] ?? null; $nearbyPIcnt = count($nearbyPIs); $apiKey = $PASYSCONF['MAPS']['HERECOM']['APIKEY']; // ── Data-age CSS class ──────────────────────────────────────── $ageClass = 'fresh'; $ageLabel = 'N/A'; if ($dataAgeMin >= 0) { if ($dataAgeMin < 15) { $ageClass = 'fresh'; $ageLabel = $dataAgeMin.'m ago'; } elseif ($dataAgeMin < 60) { $ageClass = 'warn'; $ageLabel = $dataAgeMin.'m ago'; } elseif ($dataAgeMin < 1440) { $ageClass = 'stale'; $ageLabel = round($dataAgeMin/60,1).'h ago'; } else { $ageClass = 'stale'; $ageLabel = round($dataAgeMin/1440,1).'d ago'; } } ?>