# Tutorial Hari 8: Dashboard Admin

## 🎯 Tujuan
- Membuat halaman dashboard admin
- Menampilkan statistik fasilitas
- Membuat navigasi admin
- Memahami alur halaman terproteksi

---

## 📚 Teori: Halaman Terproteksi

### Alur Akses Halaman

```
User akses dashboard.php
        │
        ▼
┌───────────────────┐
│  isLoggedIn()?    │
└───────────────────┘
        │
  ┌─────┴─────┐
  │           │
 YES         NO
  │           │
  ▼           ▼
Tampilkan   Redirect ke
Dashboard   login.php
```

### Kode Proteksi

```php
require_once 'lib/auth.php';
requireAuth();  // Otomatis redirect jika belum login
```

---

## 1. Buat Dashboard.php

### Langkah 1: Buat file baru

1. Klik kanan folder **pages**
2. New File → `dashboard.php`

### Langkah 2: Tulis Kode

```php
<?php
/**
 * Dashboard Admin
 * Halaman utama setelah login
 */

require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/spatial.php';
require_once __DIR__ . '/../lib/helpers.php';

// Wajib login
requireAuth();

// Ambil data user
$user = getCurrentUser();
$userId = getCurrentUserId();

// Ambil peta milik user
$petaList = getUserPeta($userId);
$peta = !empty($petaList) ? $petaList[0] : null;

// Jika belum punya peta, buat otomatis
if (!$peta) {
    $result = createPeta($userId, 'Peta Desa', 'Peta interaktif desa');
    if ($result['success']) {
        $peta = getPetaById($result['peta_id'], $userId);
    }
}

// Hitung statistik fasilitas
$totalFasilitas = 0;
$fasilitasCount = [];

if ($peta) {
    $fasilitasCount = getFasilitasCountByType($peta['id']);
    $totalFasilitas = array_sum($fasilitasCount);
}

// Definisi kategori fasilitas
$fasilitasTypes = [
    'pendidikan' => ['icon' => 'fa-school', 'color' => '#3b82f6', 'label' => 'Pendidikan'],
    'kesehatan' => ['icon' => 'fa-hospital', 'color' => '#ef4444', 'label' => 'Kesehatan'],
    'ibadah' => ['icon' => 'fa-place-of-worship', 'color' => '#22c55e', 'label' => 'Ibadah'],
    'pemerintahan' => ['icon' => 'fa-landmark', 'color' => '#f59e0b', 'label' => 'Pemerintahan'],
    'umkm' => ['icon' => 'fa-store', 'color' => '#ec4899', 'label' => 'UMKM'],
    'wisata' => ['icon' => 'fa-mountain-sun', 'color' => '#8b5cf6', 'label' => 'Wisata']
];
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - WebGIS Pemetaan Desa</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/style.css">
    
    <style>
        .dashboard-container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 2rem 1rem;
        }
        
        /* Welcome Card */
        .welcome-card {
            background: linear-gradient(135deg, #0f172a 0%, #1e40af 50%, #3b82f6 100%);
            color: white;
            border-radius: 1rem;
            padding: 2rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .welcome-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 200px;
            height: 200px;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            border-radius: 50%;
            transform: translate(30%, -30%);
        }
        
        .welcome-greeting {
            font-size: 1.125rem;
            margin-bottom: 0.75rem;
            color: #bfdbfe;
        }
        
        .welcome-greeting strong { color: white; }
        
        .welcome-card h1 {
            margin: 0;
            font-size: 1.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .welcome-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid rgba(255,255,255,0.15);
        }
        
        .welcome-meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
            opacity: 0.9;
        }
        
        /* Stats Row */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-box {
            background: white;
            border-radius: 0.75rem;
            padding: 1.25rem;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .stat-box .icon {
            width: 48px;
            height: 48px;
            border-radius: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 0.75rem;
            color: white;
            font-size: 1.25rem;
        }
        
        .stat-box h3 {
            font-size: 1.5rem;
            margin: 0;
            color: #1e293b;
        }
        
        .stat-box p {
            font-size: 0.75rem;
            color: #64748b;
            margin: 0.25rem 0 0;
        }
        
        /* Action Card */
        .action-card {
            background: white;
            border-radius: 1rem;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .action-card h2 {
            margin: 0 0 1rem;
            font-size: 1.125rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .action-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }
        
        .action-btn {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1.25rem;
            border: 2px solid #e2e8f0;
            border-radius: 0.75rem;
            background: white;
            text-decoration: none;
            color: #1e293b;
            transition: all 0.2s;
        }
        
        .action-btn:hover {
            border-color: #3b82f6;
            background: #f8fafc;
            transform: translateY(-2px);
        }
        
        .action-btn .icon {
            width: 48px;
            height: 48px;
            border-radius: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
        }
        
        .action-btn h4 { margin: 0; font-size: 0.875rem; }
        .action-btn p { margin: 0.25rem 0 0; font-size: 0.75rem; color: #64748b; }
    </style>
</head>
<body style="background: #f1f5f9;">
    <!-- NAVBAR -->
    <nav class="navbar">
        <div class="container nav-container">
            <a href="/" class="navbar-brand">
                <i class="fas fa-map-marked-alt"></i>
                WebGIS Pemetaan Desa
            </a>
            
            <div class="nav-links">
                <a href="/" target="_blank">
                    <i class="fas fa-globe"></i> Lihat Publik
                </a>
                <span style="color: var(--gray-400);">|</span>
                <a href="/pages/settings.php">
                    <i class="fas fa-cog"></i> Pengaturan
                </a>
                <span style="color: var(--gray-400);">|</span>
                <span style="color: var(--gray-600);">
                    <i class="fas fa-user"></i> <?= sanitize($user['username']) ?>
                </span>
                <a href="/process/logout.php" class="btn btn-sm btn-danger">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>
    </nav>
    
    <!-- MAIN CONTENT -->
    <main class="dashboard-container">
        <?php displayFlash(); ?>
        
        <!-- Welcome Card -->
        <div class="welcome-card">
            <p class="welcome-greeting">
                <i class="fas fa-hand-wave"></i> Selamat datang, 
                <strong><?= sanitize($user['username']) ?></strong>!
            </p>
            <h1><i class="fas fa-map"></i> <?= sanitize($peta['nama_peta'] ?? 'Peta Desa') ?></h1>
            
            <div class="welcome-meta">
                <div class="welcome-meta-item">
                    <i class="fas fa-layer-group"></i>
                    <span><strong><?= $totalFasilitas ?></strong> Total Fasilitas</span>
                </div>
                <div class="welcome-meta-item">
                    <i class="fas fa-clock"></i>
                    <span>Diperbarui: <?= formatDate($peta['updated_at'] ?? 'now') ?></span>
                </div>
            </div>
        </div>
        
        <!-- Stats Row -->
        <div class="stats-row">
            <?php foreach ($fasilitasTypes as $key => $type): ?>
                <div class="stat-box">
                    <div class="icon" style="background: <?= $type['color'] ?>">
                        <i class="fas <?= $type['icon'] ?>"></i>
                    </div>
                    <h3><?= $fasilitasCount[$key] ?? 0 ?></h3>
                    <p><?= $type['label'] ?></p>
                </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Actions -->
        <div class="action-card">
            <h2><i class="fas fa-tools text-primary"></i> Kelola Peta</h2>
            
            <div class="action-buttons">
                <a href="/pages/edit-peta.php?id=<?= $peta['id'] ?>" class="action-btn">
                    <div class="icon" style="background: #dbeafe; color: #2563eb;">
                        <i class="fas fa-edit"></i>
                    </div>
                    <div>
                        <h4>Edit Peta & Fasilitas</h4>
                        <p>Gambar batas, tambah fasilitas</p>
                    </div>
                </a>
                
                <a href="/pages/lihat-peta.php?id=<?= $peta['id'] ?>" class="action-btn">
                    <div class="icon" style="background: #dcfce7; color: #16a34a;">
                        <i class="fas fa-eye"></i>
                    </div>
                    <div>
                        <h4>Lihat & Analisis</h4>
                        <p>Preview peta lengkap</p>
                    </div>
                </a>
                
                <a href="/pages/ekspor.php?id=<?= $peta['id'] ?>" class="action-btn">
                    <div class="icon" style="background: #fef3c7; color: #d97706;">
                        <i class="fas fa-download"></i>
                    </div>
                    <div>
                        <h4>Ekspor Data</h4>
                        <p>GeoJSON, PNG, Print</p>
                    </div>
                </a>
            </div>
        </div>
    </main>
</body>
</html>
```

---

## 📚 Penjelasan Kode Penting

### 1. Require Auth

```php
require_once __DIR__ . '/../lib/auth.php';
requireAuth();  // Wajib login
```

| Baris | Fungsi |
|-------|--------|
| `require_once` | Include file sekali |
| `requireAuth()` | Redirect ke login jika belum login |

### 2. Get Data User & Peta

```php
$user = getCurrentUser();
$userId = getCurrentUserId();
$petaList = getUserPeta($userId);
```

| Variabel | Isi |
|----------|-----|
| `$user` | Array data user (username, email) |
| `$userId` | ID user (integer) |
| `$petaList` | Array semua peta milik user |

### 3. Auto Create Peta

```php
if (!$peta) {
    $result = createPeta($userId, 'Peta Desa', 'Peta interaktif desa');
    // ...
}
```

Jika user belum punya peta, otomatis dibuatkan.

### 4. Stats Count

```php
$fasilitasCount = getFasilitasCountByType($peta['id']);
// Hasil: ['pendidikan' => 3, 'kesehatan' => 2, ...]

$totalFasilitas = array_sum($fasilitasCount);
// Hasil: 5
```

---

## 2. Update Login Redirect

Buka `pages/login.php`, pastikan redirect ke dashboard:

```php
if ($result['success']) {
    header('Location: /pages/dashboard.php');  // ← Pastikan ini
    exit;
}
```

---

## 3. Test Dashboard

1. Buka: `http://localhost/pemetaan-desa/pages/login.php`
2. Login dengan: `demo` / `password123`
3. Otomatis redirect ke dashboard
4. Lihat statistik (semua 0 karena belum ada fasilitas)

---

## 📁 Struktur Akhir Hari 8

```
📁 pemetaan-desa/
├── 📁 pages/
│   ├── 📄 dashboard.php     ← BARU
│   └── 📄 login.php
└── ...
```

---

**← [Hari 7: CSS & Layout](hari7.md) | [Hari 9: Edit Peta](hari9.md) →**
