= NOW() - INTERVAL $freshSeconds SECOND"; } // تحديد المسار الكامل بدقة $savePath = __DIR__ . '/' . $fileName; // === فحص صلاحيات الكتابة === if (!is_writable(__DIR__)) { // إذا لم تكن هناك صلاحية، سنطبع الخطأ ونوقف التنفيذ echo json_encode([ "status" => "error", "message" => "Permission Denied: Cannot write to directory. Please chmod 777 this folder.", "path" => __DIR__ ]); exit; } // 1. جلب المواقع $sql_locations = " SELECT t.driver_id, t.latitude AS lat, t.longitude AS lon, t.heading, t.speed, t.created_at FROM car_tracks t INNER JOIN ( SELECT driver_id, MAX(id) AS max_id FROM car_tracks WHERE $timeCondition GROUP BY driver_id ) latest ON t.id = latest.max_id ORDER BY t.created_at DESC "; $stmt = $con_tracking->prepare($sql_locations); $stmt->execute(); $locations = $stmt->fetchAll(PDO::FETCH_ASSOC); // 2. جلب بيانات السائقين $driver_ids = array_unique(array_column($locations, 'driver_id')); $drivers_info = []; if (!empty($driver_ids)) { $placeholders = implode(',', array_fill(0, count($driver_ids), '?')); $sql_drivers = "SELECT id, first_name, last_name, phone FROM driver WHERE id IN ($placeholders)"; $stmt_drivers = $con->prepare($sql_drivers); $stmt_drivers->execute(array_values($driver_ids)); foreach ($stmt_drivers->fetchAll(PDO::FETCH_ASSOC) as $row) { $drivers_info[$row['id']] = $row; } } // 3. الدمج $final_drivers = []; foreach ($locations as $loc) { $d_id = $loc['driver_id']; $merged = [ 'id' => $d_id, 'lat' => $loc['lat'], 'lon' => $loc['lon'], 'heading' => $loc['heading'], 'speed' => $loc['speed'], 'name' => 'Unknown', 'phone' => '', 'completed' => 0, 'cancelled' => 0 ]; if (isset($drivers_info[$d_id])) { $info = $drivers_info[$d_id]; // فك التشفير البسيط (تأكد من عمل encryptionHelper) if (isset($encryptionHelper)) { try { $info['first_name'] = $encryptionHelper->decryptData($info['first_name']); } catch(Exception $e){} try { $info['last_name'] = $encryptionHelper->decryptData($info['last_name']); } catch(Exception $e){} try { $info['phone'] = $encryptionHelper->decryptData($info['phone']); } catch(Exception $e){} } $merged['name'] = trim(($info['first_name']??'') . ' ' . ($info['last_name']??'')); $merged['phone'] = $info['phone'] ?? ''; $merged['completed'] = $info['completed'] ?? 0; $merged['cancelled'] = $info['cancelled'] ?? 0; } $final_drivers[] = $merged; } // 4. الحفظ $jsonContent = json_encode(['drivers' => $final_drivers, 'last_updated' => date('Y-m-d H:i:s')], JSON_UNESCAPED_UNICODE); // محاولة الحفظ if (file_put_contents($savePath, $jsonContent) !== false) { echo json_encode(["status" => "success", "message" => "File written successfully to $savePath"]); } else { echo json_encode(["status" => "error", "message" => "Failed to write file. Check permissions."]); } } catch (Exception $e) { echo json_encode(["status" => "error", "message" => $e->getMessage()]); } ?>