<?php
/**
 * Lions Club Dashboard - Admin Panel
 *
 * Beheerders pagina om KPI's aan te passen (voortgang en status).
 */

session_start();

// Check of gebruiker is ingelogd
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// Logout verwerken
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header("Location: login.php");
    exit;
}

$success = '';
$error = '';

// KPI bijwerken
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_kpi') {
    $kpi_id = $_POST['kpi_id'] ?? '';
    $current = intval($_POST['current'] ?? 0);
    $target = intval($_POST['target'] ?? 100);
    $status = $_POST['status'] ?? 'niet-gestart';

    try {
        $pdo = new PDO("sqlite:" . __DIR__ . "/lions.db");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Percentage berekenen
        $percentage = $target > 0 ? round(($current / $target) * 100) : 0;
        $percentage = min(100, max(0, $percentage)); // Clamp tussen 0 en 100

        $stmt = $pdo->prepare("
            UPDATE kpi
            SET current = ?, target = ?, percentage = ?, status = ?, updated_at = datetime('now')
            WHERE kpi_id = ?
        ");
        $stmt->execute([$current, $target, $percentage, $status, $kpi_id]);

        $success = "KPI #$kpi_id succesvol bijgewerkt!";

    } catch (PDOException $e) {
        $error = "Database fout: " . $e->getMessage();
    }
}

// Alle KPI's ophalen
try {
    $pdo = new PDO("sqlite:" . __DIR__ . "/lions.db");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->query("SELECT * FROM kpi ORDER BY kpi_id ASC");
    $kpis = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Groepeer per coordinator
    $grouped = [];
    foreach ($kpis as $kpi) {
        $coord = strtoupper($kpi['coordinator']);
        if (!isset($grouped[$coord])) {
            $grouped[$coord] = [];
        }
        $grouped[$coord][] = $kpi;
    }

} catch (PDOException $e) {
    $error = "Database fout: " . $e->getMessage();
    $grouped = [];
}
?>
<!DOCTYPE html>
<html lang="nl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - Lions Club Dashboard</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
        }
        header {
            background: #1a237e;
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header-content {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        .logo img {
            max-height: 50px;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .user-name {
            font-weight: 600;
        }
        .logout-btn {
            background: rgba(255,255,255,0.1);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
        }
        .logout-btn:hover {
            background: rgba(255,255,255,0.2);
        }
        main {
            max-width: 1400px;
            margin: 0 auto;
            padding: 30px 20px;
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 20px;
        }
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .coordinator-section {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            overflow: hidden;
        }
        .coordinator-header {
            background: #1a237e;
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .coordinator-title {
            font-size: 20px;
            font-weight: 600;
        }
        .kpi-count {
            background: rgba(255,255,255,0.2);
            padding: 5px 12px;
            border-radius: 15px;
            font-size: 14px;
        }
        .kpi-list {
            padding: 20px;
        }
        .kpi-item {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 20px;
            margin-bottom: 20px;
            transition: box-shadow 0.3s;
        }
        .kpi-item:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .kpi-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 15px;
        }
        .kpi-title {
            font-weight: 600;
            color: #333;
            flex: 1;
            padding-right: 20px;
        }
        .kpi-id {
            background: #e0e0e0;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: #666;
        }
        .delete-btn {
            display: inline-block;
            padding: 6px 10px;
            background: #dc3545;
            color: white;
            border-radius: 4px;
            text-decoration: none;
            font-size: 18px;
            margin-left: 10px;
            transition: all 0.2s;
        }
        .delete-btn:hover {
            background: #c62828;
            transform: scale(1.1);
        }
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        .form-group {
            display: flex;
            flex-direction: column;
        }
        label {
            font-size: 13px;
            font-weight: 600;
            color: #555;
            margin-bottom: 6px;
        }
        input, select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        input:focus, select:focus {
            outline: none;
            border-color: #1a237e;
        }
        .progress-bar {
            height: 8px;
            background: #e0e0e0;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 5px;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4caf50, #8bc34a);
            transition: width 0.3s;
        }
        .btn-save {
            background: #1a237e;
            color: white;
            border: none;
            padding: 10px 24px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }
        .btn-save:hover {
            background: #0d1558;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        .status-niet-gestart { background: #ffebee; color: #c62828; }
        .status-behandeling { background: #fff3e0; color: #ef6c00; }
        .status-voltooid { background: #e8f5e9; color: #2e7d32; }

        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            .kpi-header {
                flex-direction: column;
            }
            .kpi-title {
                padding-right: 0;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
    <header>
        <div class="header-content">
            <div class="logo">
                <img src="https://www.lions.org/wp-content/uploads/2017/07/Lions-International-Logo.png" alt="Lions International Logo" onerror="this.style.display='none'">
            </div>
            <div>
                <h2>Lions Club District 110AZ</h2>
                <p>Admin Panel</p>
            </div>
        </div>
        <div class="user-info">
            <span class="user-name"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></span>
            <a href="?action=logout" class="logout-btn">Uitloggen</a>
        </div>
    </header>

    <main>
        <h1>Beheer KPI Voortgang</h1>
        <p class="subtitle">Wijzig de voortgang en status van KPI's voor alle coördinatoren.</p>

        <div style="margin-bottom: 20px; text-align: right;">
            <a href="add-kpi.php" style="display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #4caf50 0%, #8bc34a 100%); color: white; text-decoration: none; border-radius: 5px; font-weight: 600; font-size: 16px; transition: transform 0.2s;">
                ➕ Nieuwe KPI Toevoegen
            </a>
        </div>
        <style>
            div[style="margin-bottom: 20px; text-align: right;"] a:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            }
        </style>

        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <?php foreach ($grouped as $coordinator => $kpis): ?>
            <div class="coordinator-section">
                <div class="coordinator-header">
                    <span class="coordinator-title"><?php echo htmlspecialchars($coordinator); ?> - Coördinator</span>
                    <span class="kpi-count"><?php echo count($kpis); ?> KPI's</span>
                </div>
                <div class="kpi-list">
                    <?php foreach ($kpis as $kpi): ?>
                        <div class="kpi-item">
                            <form method="POST">
                                <input type="hidden" name="action" value="update_kpi">
                                <input type="hidden" name="kpi_id" value="<?php echo htmlspecialchars($kpi['kpi_id']); ?>">

                                <div class="kpi-header">
                                    <div class="kpi-title">
                                        <?php echo htmlspecialchars($kpi['title']); ?>
                                        <span class="status-badge status-<?php echo htmlspecialchars($kpi['status']); ?>">
                                            <?php echo htmlspecialchars($kpi['status']); ?>
                                        </span>
                                    </div>
                                    <span class="kpi-id">#<?php echo htmlspecialchars($kpi['kpi_id']); ?></span>
                                    <a href="delete-kpi.php?id=<?php echo htmlspecialchars($kpi['kpi_id']); ?>" class="delete-btn" onclick="return confirm('Weet je zeker dat je KPI #<?php echo htmlspecialchars($kpi['kpi_id']); ?> wilt verwijderen? Dit kan niet ongedaan worden worden!');" title="KPI verwijderen">🗑️</a>
                                </div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="current-<?php echo $kpi['kpi_id']; ?>">Huidige waarde</label>
                                        <input type="number" id="current-<?php echo $kpi['kpi_id']; ?>"
                                               name="current" value="<?php echo intval($kpi['current']); ?>"
                                               min="0" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="target-<?php echo $kpi['kpi_id']; ?>">Doelwaarde</label>
                                        <input type="number" id="target-<?php echo $kpi['kpi_id']; ?>"
                                               name="target" value="<?php echo intval($kpi['target']); ?>"
                                               min="1" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="status-<?php echo $kpi['kpi_id']; ?>">Status</label>
                                        <select id="status-<?php echo $kpi['kpi_id']; ?>" name="status">
                                            <option value="niet-gestart" <?php echo $kpi['status'] === 'niet-gestart' ? 'selected' : ''; ?>>Niet gestart</option>
                                            <option value="behandeling" <?php echo $kpi['status'] === 'behandeling' ? 'selected' : ''; ?>>In behandeling</option>
                                            <option value="voltooid" <?php echo $kpi['status'] === 'voltooid' ? 'selected' : ''; ?>>Voltooid</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label>Voortgang: <strong><?php echo intval($kpi['percentage']); ?>%</strong></label>
                                    <div class="progress-bar">
                                        <div class="progress-fill" style="width: <?php echo intval($kpi['percentage']); ?>%"></div>
                                    </div>
                                </div>

                                <button type="submit" class="btn-save">Opslaan</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>

        <div style="margin-top: 40px; padding: 20px; background: #e3f2fd; border-radius: 8px;">
            <h3>🔗 Snelle links</h3>
            <p style="margin: 10px 0;"><a href="dashboard.html" target="_blank" style="color: #1976d2; text-decoration: none;">→ Bekijk public dashboard</a></p>
        </div>
    </main>
</body>
</html>
