false,'error'=>'Missing DeviceID or ClientID']); return; } // Get next GeoFenceNUM for this device $q = "SELECT COALESCE(MAX(GeoFenceNUM),0)+1 AS NextNum FROM Geofences WHERE DeviceID='$deviceID'"; $row = []; $cnt = 0; $err = ''; $st = ''; PACommonDBSelectRecord($q, $row, $cnt, $err, $st); $nextNum = is_array($row) ? (int)($row['NextNum'] ?? 1) : 1; if ($nextNum < 1) $nextNum = 1; $now = date('Y-m-d H:i:s'); $q = "INSERT INTO Geofences (DeviceID,ClientID,GeoFenceNUM,GeoFenceDefault,GeofenceName,ShapeType,IsEnabled, DetectEntry,DetectExit,MinLat,MinLon,MaxLat,MaxLon,CenterLat,CenterLon,Radius, StartDateTime,EndDateTime,InsertDateTime,UpdateDateTime) VALUES ('$deviceID',$clientID,$nextNum,1,'$name',$shapeType,$isEnabled, $detectEntry,$detectExit,$minLat,$minLon,$maxLat,$maxLon,$centerLat,$centerLon,$radius, '$now','0000-00-00 00:00:00','$now','$now')"; $dummy = []; $cnt2 = 0; error_log("[GF_ADD] INSERT query: " . $q); PACommonDBSelectRecord($q, $dummy, $cnt2, $err, $st); error_log("[GF_ADD] INSERT result: cnt=$cnt2 err=$err st=$st"); // Get the new GeofenceID $q2 = "SELECT GeofenceID FROM Geofences WHERE DeviceID='$deviceID' ORDER BY GeofenceID DESC LIMIT 1"; $newRow = []; $newCnt = 0; PACommonDBSelectRecord($q2, $newRow, $newCnt, $err, $st); $newID = is_array($newRow) ? (int)($newRow['GeofenceID'] ?? 0) : 0; error_log("[GF_ADD] New GeofenceID=$newID nextNum=$nextNum clientID=$clientID deviceID=$deviceID"); echo json_encode(['ok'=>true,'GeofenceID'=>$newID,'GeoFenceNUM'=>$nextNum,'GeofenceName'=>$name]);