<?php 
header('Content-Type: application/json');

include "../config/connect.php";

$id = isset($_GET['i']) ? $_GET['i'] : '';
$sqlwh = base64_decode($id);
// Mengambil data dari database berdasarkan id_data_server
$stmt = $pdo->prepare("SELECT * FROM v_data_maps $sqlwh ORDER BY status_koneksi");
$stmt->execute();
$monitor = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmtodp = $pdo->prepare("SELECT * FROM master_topologi $sqlwh");
$stmtodp->execute();
$master = $stmtodp->fetchAll(PDO::FETCH_ASSOC);

// Memeriksa apakah data ditemukan
if (!empty($monitor) || !empty($master)) {
    $data = []; // Array untuk menampung hasil

    // Mengisi data dari master_topologi
    foreach ($master as $odp) {
        list($lat, $lng) = explode(", ", $odp['titik_koordinat']);
        
        $data[] = [
            'nama' => $odp['nama'],
            'latitude' => floatval($lat),
            'longitude' => floatval($lng),
            'icon' => 'dist/img/ODP.png',
            'content' => '<b>' . $odp['nama'] . '</b>'
        ];
    }

    // Mengisi data ke dalam array hasil dari monitor
    foreach ($monitor as $row) {
        $data[] = [
            'nama' => $row['nama'],
            'latitude' => floatval($row['latitude']),
            'longitude' => floatval($row['longitude']),
            'icon' => ($row['status'] == 'aktif') ? 
                      (($row['status_koneksi'] == 'On') ? 'dist/img/ON.png' : 'dist/img/OF.png') : 
                      (($row['status_koneksi'] == 'On') ? 'dist/img/ON1.png' : 'dist/img/OF1.png'),
            'content' => 'User_Id: <b>' . $row['akun'] . '</b><br>User: <b>' . $row['nama'] . '</b><br>login_at: ' . $row['last_on'] . '<br>last_logout: ' . $row['last_off'] . '<br>Status: ' . ($row['status_koneksi'] == 'On' ? 'Connect / '.$row['status'] : 'Disconnect / '.$row['status'])
        ];
    }

    
    // Format data untuk output
    $result = array_map(function($item) {
        return [
            'lat' => $item['latitude'],
            'lng' => $item['longitude'],
            'title' => $item['nama'],
            'icon' => $item['icon'],
            'content' => $item['content']
        ];
    }, $data);
    
    // Mengirimkan data sebagai JSON
    echo json_encode($result);
} else {
    // Jika tidak ada data, kembalikan array kosong
    echo json_encode([]);
}
?>
