# Dashboard Controllers - Quick Start Guide

## 📋 Summary

Sistem PC Monitoring Tracker Dashboard sekarang memiliki 6 controller baru yang lengkap:

### Controllers Created:
1. ✅ **DashboardController** - Dashboard statistics & health overview
2. ✅ **AgentViewController** - Agent/PC listing & management
3. ✅ **ActivityViewController** - Activity logging & statistics
4. ✅ **CommandViewController** - Remote command management
5. ✅ **BandwidthViewController** - Bandwidth control & limiting
6. ✅ **DashboardIntegration** - Helper functions & integration layer

---

## 🚀 Getting Started

### Step 1: Include Integration in Your View
```php
<?php
// At the top of any dashboard view file
require_once __DIR__ . '/../controllers/DashboardIntegration.php';
```

### Step 2: Use Helper Functions
```php
// Display dashboard statistics
$dashboard = getDashboardData();
echo "Online Agents: " . $dashboard['stats']['online_agents'];

// Display all agents
$agents = getAllAgentsData();
foreach ($agents as $agent) {
    echo $agent['pc_name'];
}

// Display activities with pagination
$page = $_GET['page'] ?? 1;
$activities = getActivitiesData($page, 20);
```

---

## 📚 Available Functions

### Dashboard Functions
- `getDashboardData()` - Overall dashboard statistics
- `getSystemHealth()` - System health overview

### Agent Management
- `getAllAgentsData($filter)` - Get agents (filter: 'online', 'offline', null)
- `getAgentDetailData($agent_id)` - Complete agent information
- `formatDateTime($datetime)` - Format timestamp helper

### Activity Monitoring
- `getActivitiesData($page, $per_page, $filters)` - Paginated activities
- `getActivityStatsData($days)` - Activity statistics & trends

### Command Control
- `getCommandsData($page, $per_page, $filters)` - Commands with pagination
- `getCommandStatsData()` - Command statistics & pending count

### Bandwidth Management
- `getBandwidthData($page, $per_page)` - Bandwidth settings & stats
- `getAgentBandwidthData($agent_id, $hours)` - Agent bandwidth history

### Formatting Helpers
- `formatBytes($bytes)` - Convert bytes to KB/MB/GB
- `calculateDuration($from, $to)` - Calculate time duration
- `getStatusBadgeClass($status)` - CSS class for status badge
- `truncateText($text, $limit)` - Truncate long text
- `safeOutput($text)` - Escape HTML safely

---

## 💡 Code Examples

### Example 1: Display Dashboard Stats
```php
<?php require_once 'controllers/DashboardIntegration.php'; ?>

<div class="dashboard-stats">
    <?php
    $data = getDashboardData();
    $total = $data['stats']['total_agents'];
    $online = $data['stats']['online_agents'];
    ?>
    <div class="stat">
        <h3><?php echo $total; ?></h3>
        <p>Total Agents</p>
    </div>
    <div class="stat">
        <h3><?php echo $online; ?></h3>
        <p>Online Now</p>
    </div>
</div>
```

### Example 2: Agents Table
```php
<?php
$agents = getAllAgentsData();
?>
<table>
    <tr>
        <th>PC Name</th>
        <th>IP</th>
        <th>Status</th>
        <th>Last Seen</th>
    </tr>
    <?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 $agent['status']; ?>
        </span></td>
        <td><?php echo formatDateTime($agent['last_seen']); ?></td>
    </tr>
    <?php endforeach; ?>
</table>
```

### Example 3: Activities with Pagination
```php
<?php
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$activities = getActivitiesData($page, 20);
?>

<div class="activities-list">
    <?php foreach ($activities['activities'] as $act): ?>
        <div class="activity">
            <strong><?php echo safeOutput($act['app_name'] ?? $act['website_url']); ?></strong>
            <small><?php echo formatDateTime($act['created_at']); ?></small>
        </div>
    <?php endforeach; ?>
</div>

<!-- Pagination -->
<div class="pagination">
    <?php for ($i = 1; $i <= $activities['pages']; $i++): ?>
        <a href="?page=<?php echo $i; ?>" 
           class="<?php echo $i == $activities['current_page'] ? 'active' : ''; ?>">
            Page <?php echo $i; ?>
        </a>
    <?php endfor; ?>
</div>
```

### Example 4: Bandwidth Control
```php
<?php
$bandwidth = getBandwidthData(1, 10);
?>

<table>
    <tr>
        <th>PC</th>
        <th>Limit</th>
        <th>Current</th>
        <th>% Usage</th>
    </tr>
    <?php foreach ($bandwidth['settings']['settings'] as $bw): ?>
    <tr>
        <td><?php echo safeOutput($bw['pc_name']); ?></td>
        <td><?php echo formatBytes($bw['max_bandwidth_limit']); ?>/s</td>
        <td><?php echo formatBytes($bw['current_usage']); ?>/s</td>
        <td>
            <?php 
            $percent = ($bw['current_usage'] / $bw['max_bandwidth_limit'] * 100);
            echo round($percent, 1) . '%';
            ?>
        </td>
    </tr>
    <?php endforeach; ?>
</table>
```

---

## 🔄 Data Flow

```
View File (.php)
    ↓ includes
DashboardIntegration.php
    ↓ initializes
✓ DashboardController
✓ AgentViewController
✓ ActivityViewController
✓ CommandViewController
✓ BandwidthViewController
    ↓ queries
Database (tracker_schema.sql)
    ↓ returns
Data Arrays/Objects
    ↓ displays
HTML Output
```

---

## ✨ Key Features

### 🔍 Filtering & Pagination
- Activities support date range, agent, and type filters
- Commands support status, agent, and type filters
- All list functions support pagination

### 📊 Statistics
- Dashboard shows real-time overview
- Activity stats by day/type
- Command execution stats
- Bandwidth usage stats

### 🔒 Security
- All HTML output escaped with `safeOutput()`
- SQL prepared statements in all queries
- PDO connections for data access

### ⚡ Performance
- Efficient pagination for large datasets
- Database queries use indexes
- Helper caching where appropriate

---

## 📖 Full Documentation

See `CONTROLLERS_GUIDE.md` for:
- Complete method signatures
- Parameter descriptions
- Return value formats
- Advanced usage examples
- Performance optimization tips

---

## ✅ File Structure

```
dashboard/
├── controllers/
│   ├── DashboardController.php ✨ NEW
│   ├── AgentViewController.php ✨ NEW
│   ├── ActivityViewController.php ✨ NEW
│   ├── CommandViewController.php ✨ NEW
│   ├── BandwidthViewController.php ✨ NEW
│   └── DashboardIntegration.php ✨ NEW
├── views/
│   ├── dashboard.php
│   ├── agents.php
│   ├── activities.php
│   ├── bandwidth.php
│   └── ...
├── index.php
└── config/
    └── Database.php
```

---

## 🎯 Next Steps

1. **Update Views** - Integrate controllers into existing view files
2. **Test** - Verify all controllers work with your database
3. **Optimize** - Add caching where needed for large queries
4. **Deploy** - Push to webhost tracker.lppmunud.id

---

## 📝 Notes

- All controllers use PDO for database access
- Error handling returns empty arrays on failure
- All functions properly escape HTML output
- Database must have all tables from tracker_schema.sql

---

**Created:** 2026-03-27  
**Status:** Ready for Integration  
**Version:** 1.0.0
