# Dashboard Controllers Implementation Guide

## Overview

Implementasi lengkap dashboard controllers untuk system PC Monitoring Tracker. Controllers ini menyediakan logika data dan statistik untuk semua halaman dashboard.

## Struktur Controllers

### 1. DashboardController
**Lokasi:** `dashboard/controllers/DashboardController.php`

Mengelola data dashboard utama dan statistik sistem.

#### Methods:
- `getDashboardStats()` - Mendapatkan ringkasan statistik dashboard
- `getRecentActivities($limit)` - Mendapatkan aktivitas terbaru
- `getSystemHealth()` - Mendapatkan status kesehatan sistem

#### Usage:
```php
require_once 'DashboardController.php';
$dashboard = new DashboardController();
$stats = $dashboard->getDashboardStats();
// Returns: [
//   'total_agents' => integer,
//   'online_agents' => integer,
//   'total_activities' => integer,
//   'running_processes' => integer,
//   'pending_commands' => integer
// ]
```

---

### 2. AgentViewController
**Lokasi:** `dashboard/controllers/AgentViewController.php`

Mengelola tampilan dan data list agent/komputer yang dipantau.

#### Methods:
- `getAllAgents($filter)` - Mendapatkan semua agents dengan filter (online/offline)
- `getAgentDetail($agent_id)` - Detail agent spesifik
- `getAgentActivityTimeline($agent_id, $limit)` - Timeline aktivitas agent
- `getAgentSystemInfo($agent_id)` - Info sistem agent
- `getAgentResourceHistory($agent_id, $hours)` - Riwayat resource usage
- `getAgentCountByStatus()` - Jumlah agent per status
- `getOfflineAgents($minutes)` - Agent yang offline > X menit
- `deactivateAgent($agent_id)` - Menonaktifkan agent

#### Usage:
```php
require_once 'DashboardIntegration.php';

// Get all agents
$agents = getAllAgentsData(); // All agents
$online_agents = getAllAgentsData('online'); // Only online
$offline_agents = getAllAgentsData('offline'); // Only offline

// Get agent details
$agent_data = getAgentDetailData($agent_id);
// Returns: [
//   'agent' => {...},
//   'activities' => [...],
//   'system_info' => {...},
//   'resource_history' => [...]
// ]

// Loop through agents
foreach ($agents as $agent) {
    echo $agent['pc_name'];
    echo $agent['status'];
    echo $agent['last_seen'];
}
```

---

### 3. ActivityViewController
**Lokasi:** `dashboard/controllers/ActivityViewController.php`

Mengelola tampilan aktivitas dan statistik aktivitas.

#### Methods:
- `getActivities($page, $per_page, $filters)` - Aktivitas dengan pagination & filter
- `getActivityStats($days)` - Statistik aktivitas per tipe
- `getActivityTimeline($days)` - Timeline aktivitas harian
- `getTopApplications($limit)` - Aplikasi paling banyak dijalankan
- `getTopWebsites($limit)` - Website paling sering dikunjungi
- `getActivityDetail($activity_id)` - Detail aktivitas
- `searchActivities($keyword, $limit)` - Cari aktivitas

#### Usage:
```php
// Get paginated activities
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$activities_data = getActivitiesData($page, 20);
// Returns: [
//   'activities' => [...],
//   'total' => integer,
//   'pages' => integer,
//   'current_page' => integer
// ]

// Get activity statistics
$stats_data = getActivityStatsData(7); // Last 7 days
// Returns: [
//   'stats' => [activity types],
//   'timeline' => [daily data],
//   'top_apps' => [...],
//   'top_websites' => [...]
// ]

// Loop activities
foreach ($activities_data['activities'] as $activity) {
    echo $activity['app_name'];
    echo $activity['website_url'];
    echo formatDateTime($activity['created_at']);
}
```

---

### 4. CommandViewController
**Lokasi:** `dashboard/controllers/CommandViewController.php`

Mengelola tampilan dan logika perintah remote.

#### Methods:
- `getCommands($page, $per_page, $filters)` - List perintah dengan pagination
- `getCommandDetail($command_id)` - Detail perintah spesifik
- `getPendingCommandsForAgent($agent_id)` - Perintah pending untuk agent
- `getCommandStats()` - Statistik perintah
- `getCommandsByStatus($status, $limit)` - Perintah berdasarkan status
- `getCommandExecutionStats($days)` - Statistik eksekusi perintah
- `getAgentCommandHistory($agent_id, $limit)` - Riwayat perintah agent
- `updateCommandStatus($command_id, $status, $response)` - Update status perintah
- `sendCommand($agent_id, $command_type, $params, $issued_by)` - Kirim perintah baru
- `getPendingCommandsCount()` - Jumlah perintah pending

#### Usage:
```php
// Get paginated commands
$commands_data = getCommandsData(1, 20);
// Apply filters
$commands_data = getCommandsData(1, 20, [
    'status' => 'pending',
    'agent_id' => 'agent-001'
]);
// Returns: [
//   'commands' => [...],
//   'total' => integer,
//   'pages' => integer,
//   'current_page' => integer
// ]

// Get command statistics
$cmd_stats = getCommandStatsData();
// Returns: [
//   'stats' => [...],
//   'execution_stats' => [...],
//   'pending_command_count' => integer
// ]

// Loop commands
foreach ($commands_data['commands'] as $cmd) {
    echo $cmd['command_type'];
    echo $cmd['status'];
    echo $cmd['pc_name'];
}
```

---

### 5. BandwidthViewController
**Lokasi:** `dashboard/controllers/BandwidthViewController.php`

Mengelola tampilan kontrol bandwidth.

#### Methods:
- `getAllBandwidthSettings($page, $per_page)` - Semua pengaturan bandwidth
- `getAgentBandwidthSetting($agent_id)` - Pengaturan bandwidth agent
- `getBandwidthHistory($agent_id, $hours)` - Riwayat usage bandwidth
- `setBandwidthLimit($agent_id, $max_limit, $status)` - Set bandwidth limit baru
- `updateBandwidthUsage($agent_id, $current_usage)` - Update current usage
- `getBandwidthStats()` - Statistik bandwidth umum
- `getAgentsExceedingLimit()` - Agent yang exceed limit
- `disableBandwidthLimit($agent_id)` - Disable limit
- `enableBandwidthLimit($agent_id)` - Enable limit
- `getPolicyHistory($agent_id, $limit)` - Riwayat perubahan policy

#### Usage:
```php
// Get bandwidth data
$bw_data = getBandwidthData(1, 20);
// Returns: [
//   'settings' => [...],
//   'stats' => {...},
//   'exceeding' => [...]
// ]

// Get agent bandwidth
$agent_bw = getAgentBandwidthData($agent_id, 24);
// Returns: [
//   'setting' => {...},
//   'history' => [...]
// ]

// Loop bandwidth settings
foreach ($bw_data['settings']['settings'] as $setting) {
    echo $setting['pc_name'];
    echo formatBytes($setting['max_bandwidth_limit']);
    echo formatBytes($setting['current_usage']);
}
```

---

## Integration Helper: DashboardIntegration.php

File ini menyediakan helper functions yang mempermudah penggunaan controllers di views.

### Helper Functions Available:

```php
// Data retrieval
getDashboardData()
getAllAgentsData($filter)
getAgentDetailData($agent_id)
getActivitiesData($page, $per_page, $filters)
getActivityStatsData($days)
getCommandsData($page, $per_page, $filters)
getCommandStatsData()
getBandwidthData($page, $per_page)
getAgentBandwidthData($agent_id, $hours)

// Formatting helpers
formatBytes($bytes, $precision)
formatDateTime($datetime)
calculateDuration($from, $to)
getStatusBadgeClass($status)
truncateText($text, $limit, $suffix)
safeOutput($text)
```

---

## Usage in Views

### Example 1: Dashboard View
```php
<?php
require_once 'DashboardIntegration.php';

$dashboard_data = getDashboardData();
$stats = $dashboard_data['stats'];
$recent = $dashboard_data['recent_activities'];
?>

<div class="stats-container">
    <div class="stat-card">
        <h3><?php echo $stats['total_agents']; ?></h3>
        <p>Total Komputer Terpantau</p>
    </div>
    <div class="stat-card">
        <h3><?php echo $stats['online_agents']; ?></h3>
        <p>Komputer Online</p>
    </div>
</div>

<div class="activities">
    <?php foreach ($recent as $activity): ?>
        <div class="activity-item">
            <strong><?php echo safeOutput($activity['app_name']); ?></strong>
            <small><?php echo formatDateTime($activity['created_at']); ?></small>
        </div>
    <?php endforeach; ?>
</div>
```

### Example 2: Agents View
```php
<?php
require_once 'DashboardIntegration.php';

$agents = getAllAgentsData();
?>

<table>
    <thead>
        <tr>
            <th>Nama Komputer</th>
            <th>IP Address</th>
            <th>Status</th>
            <th>Terakhir Dilihat</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($agents as $agent): ?>
        <tr>
            <td><?php echo safeOutput($agent['pc_name']); ?></td>
            <td><?php echo safeOutput($agent['pc_ip']); ?></td>
            <td><span class="badge <?php echo getStatusBadgeClass($agent['status']); ?>">
                <?php echo ucfirst($agent['status']); ?>
            </span></td>
            <td><?php echo formatDateTime($agent['last_seen']); ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
```

### Example 3: Activities View
```php
<?php
require_once 'DashboardIntegration.php';

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$activities_data = getActivitiesData($page, 20);
$stats = getActivityStatsData(7);
?>

<!-- Filters -->
<form method="GET">
    <select name="activity_type">
        <?php foreach ($stats['stats'] as $stat): ?>
        <option value="<?php echo safeOutput($stat['activity_type']); ?>">
            <?php echo safeOutput($stat['activity_type']); ?>
        </option>
        <?php endforeach; ?>
    </select>
</form>

<!-- Activities Table -->
<table>
    <tr>
        <th>PC</th>
        <th>Aplikasi</th>
        <th>Website</th>
        <th>Waktu</th>
    </tr>
    <?php foreach ($activities_data['activities'] as $activity): ?>
    <tr>
        <td><?php echo safeOutput($activity['pc_name']); ?></td>
        <td><?php echo safeOutput($activity['app_name']); ?></td>
        <td><?php echo truncateText($activity['website_url']); ?></td>
        <td><?php echo formatDateTime($activity['created_at']); ?></td>
    </tr>
    <?php endforeach; ?>
</table>

<!-- Pagination -->
<?php for ($i = 1; $i <= $activities_data['pages']; $i++): ?>
    <a href="?page=<?php echo $i; ?>" 
       <?php if ($i == $activities_data['current_page']) echo 'class="active"'; ?>>
        <?php echo $i; ?>
    </a>
<?php endfor; ?>
```

---

## Error Handling

Semua method mengembalikan data atau array kosong jika terjadi error:

```php
try {
    $data = $agentView->getAllAgents();
} catch (Exception $e) {
    return []; // Returns empty array
}
```

---

## Database Requirements

Controllers ini memerlukan tabel-tabel berikut dari `database/tracker_schema.sql`:
- `agents`
- `pc_activities`
- `running_processes`
- `system_info`
- `remote_commands`
- `bandwidth_control`

---

## Performance Tips

1. **Use Pagination** - Gunakan pagination untuk dataset besar:
   ```php
   $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
   $data = $activityView->getActivities($page, 20);
   ```

2. **Apply Filters** - Filter data untuk mengurangi hasil:
   ```php
   $filters = ['agent_id' => $agent_id];
   $data = $activityView->getActivities(1, 50, $filters);
   ```

3. **Use Limit** - Batasi nilai limit untuk statistic queries:
   ```php
   $top_apps = $activityView->getTopApplications(10);
   ```

---

## Next Steps

1. Update existing views untuk menggunakan controller methods ini
2. Implement caching untuk mengurangi database queries
3. Add error reporting/logging
4. Test semua controller methods
5. Deploy ke production

---

**Last Updated:** 2026-03-27
**Version:** 1.0.0
