<?php
// views/dashboard.php - Main dashboard for club members
require_once __DIR__ . '/../auth.php';

$user = current_user();

// Handle Notification Mark as Read
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'mark_read') {
    $notif_id = intval($_POST['notification_id'] ?? 0);
    $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = :id AND user_id = :user_id");
    $stmt->execute([':id' => $notif_id, ':user_id' => $user['id']]);
    header("Location: index.php?view=dashboard");
    exit;
}

// Handle Poll Vote Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'vote') {
    $poll_id = intval($_POST['poll_id'] ?? 0);
    $vote_option = $_POST['vote_option'] ?? '';
    
    if ($poll_id > 0 && !empty($vote_option)) {
        $stmt = $pdo->prepare("INSERT OR REPLACE INTO poll_votes (poll_id, user_id, selected_option) VALUES (:poll_id, :user_id, :selected_option)");
        $stmt->execute([
            ':poll_id' => $poll_id,
            ':user_id' => $user['id'],
            ':selected_option' => $vote_option
        ]);
        header("Location: index.php?view=dashboard");
        exit;
    }
}

// Fetch Active Notifications
$notif_stmt = $pdo->prepare("SELECT * FROM notifications WHERE user_id = :user_id AND is_read = 0 ORDER BY id DESC");
$notif_stmt->execute([':user_id' => $user['id']]);
$notifications = $notif_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Active Polls
$polls_stmt = $pdo->query("SELECT * FROM polls WHERE is_active = 1 ORDER BY id DESC");
$polls = $polls_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Club News Pages
$news_stmt = $pdo->query("SELECT slug, title, content, updated_at FROM pages ORDER BY id DESC LIMIT 3");
$news_items = $news_stmt->fetchAll(PDO::FETCH_ASSOC);

// Helper function to check if user has already voted
function has_user_voted($poll_id, $user_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT selected_option FROM poll_votes WHERE poll_id = :poll_id AND user_id = :user_id");
    $stmt->execute([':poll_id' => $poll_id, ':user_id' => $user_id]);
    return $stmt->fetchColumn();
}

// Helper to count votes for an option
function get_vote_statistics($poll_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT selected_option, COUNT(*) as count FROM poll_votes WHERE poll_id = :poll_id GROUP BY selected_option");
    $stmt->execute([':poll_id' => $poll_id]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats = [];
    $total = 0;
    foreach ($results as $r) {
        $stats[$r['selected_option']] = intval($r['count']);
        $total += intval($r['count']);
    }
    return ['votes' => $stats, 'total' => $total];
}

$role_labels = [
    'admin' => 'Administrator',
    'vorstand' => 'Vorstandsmitglied',
    'kassenwart' => 'Kassenwart',
    'trainer' => 'Trainer',
    'materialwart' => 'Zeug- & Kleidungswart',
    'member' => 'Mitglied'
];
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
    <div>
        <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary);">Willkommen zurück, <?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>!</h1>
        <p style="color: var(--text-muted); font-size: 15px;">Dashboard für <?= htmlspecialchars($club_name) ?> &mdash; Rolle: <strong><?= $role_labels[$user['role']] ?? 'Mitglied' ?></strong></p>
    </div>
</div>

<div class="grid">
    <!-- Notifications Column -->
    <div style="grid-column: span 2;">
        <?php
        // Fetch startseite page content if exists
        $startseite_stmt = $pdo->prepare("SELECT content FROM pages WHERE slug = 'startseite'");
        $startseite_stmt->execute();
        $startseite_content = $startseite_stmt->fetchColumn();
        if ($startseite_content):
        ?>
            <div class="card" style="margin-bottom: 24px; padding: 25px;">
                <div style="font-size: 15px; line-height: 1.6; color: #334155;">
                    <?= $startseite_content ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if (!empty($notifications)): ?>
            <div class="card" style="border-left: 4px solid var(--primary); margin-bottom: 24px;">
                <h3 class="card-title">🚨 Wichtige Benachrichtigungen</h3>
                <div style="display: flex; flex-direction: column; gap: 15px;">
                    <?php foreach ($notifications as $n): ?>
                        <div style="padding: 12px; background-color: #f8fafc; border: 1px solid var(--border-color); border-radius: var(--radius); display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <h4 style="font-size: 15px; font-weight: 600; color: var(--secondary);"><?= htmlspecialchars($n['title']) ?></h4>
                                <p style="font-size: 14px; color: var(--text-muted); margin-top: 2px;"><?= htmlspecialchars($n['message']) ?></p>
                            </div>
                            <form method="POST" action="">
                                <input type="hidden" name="action" value="mark_read">
                                <input type="hidden" name="notification_id" value="<?= $n['id'] ?>">
                                <button type="submit" class="btn btn-secondary btn-sm">Gelesen</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- News & Custom Pages Section -->
        <div class="card">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 15px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px;">
                <h3 class="card-title" style="margin-bottom: 0; border-bottom: none;">📢 Aktuelles & Vereinsnews</h3>
                <?php if (can_edit_pages()): ?>
                    <a href="index.php?view=pages&new=1" class="btn btn-primary btn-sm">Neuen Artikel erstellen</a>
                <?php endif; ?>
            </div>
            <?php if (!empty($news_items)): ?>
                <div style="display: flex; flex-direction: column; gap: 20px; margin-top: 15px;">
                    <?php foreach ($news_items as $news): ?>
                        <div style="border-bottom: 1px solid var(--border-color); padding-bottom: 20px; last-child { border-bottom: none; }">
                            <h4 style="font-size: 18px; font-weight: 700; color: var(--secondary);">
                                <a href="index.php?view=pages&slug=<?= urlencode($news['slug']) ?>" style="text-decoration: none; color: inherit; hover: { color: var(--primary); }">
                                    <?= htmlspecialchars($news['title']) ?>
                                </a>
                            </h4>
                            <span style="font-size: 12px; color: var(--text-muted); display: block; margin-top: 4px;">
                                Aktualisiert am: <?= date('d.m.Y H:i', strtotime($news['updated_at'])) ?>
                            </span>
                            <p style="font-size: 14px; color: var(--text-muted); margin-top: 8px; line-height: 1.5;">
                                <?= htmlspecialchars(substr(strip_tags($news['content']), 0, 180)) ?>...
                            </p>
                            <a href="index.php?view=pages&slug=<?= urlencode($news['slug']) ?>" class="btn btn-secondary btn-sm" style="margin-top: 10px;">Weiterlesen</a>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p style="color: var(--text-muted); font-size: 14px; text-align: center; padding: 20px;">Momentan liegen keine aktuellen Vereinsnews vor.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Right Column: Profile & Polls -->
    <div>
        <!-- Profile summary card -->
        <div class="card" style="margin-bottom: 24px; text-align: center;">
            <h3 class="card-title" style="text-align: left;">Mein Profil</h3>
            <div style="margin-top: 15px;">
                <?php if (!empty($user['photo_path']) && file_exists(__DIR__ . '/../' . $user['photo_path'])): ?>
                    <img src="<?= htmlspecialchars($user['photo_path']) ?>" style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 4px solid var(--primary); margin: 0 auto 15px;" alt="Avatar">
                <?php else: ?>
                    <div style="width: 100px; height: 100px; border-radius: 50%; background-color: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: bold; margin: 0 auto 15px;">
                        <?= strtoupper(substr($user['first_name'], 0, 1) . substr($user['last_name'], 0, 1)) ?>
                    </div>
                <?php endif; ?>
                <h4 style="font-size: 18px; font-weight: 700;"><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></h4>
                <p style="color: var(--text-muted); font-size: 13px; margin-top: 2px;"><?= htmlspecialchars($user['email']) ?></p>
                <a href="index.php?view=profile" class="btn btn-secondary btn-sm" style="margin-top: 15px; width: 100%;">Profil verwalten</a>
            </div>
        </div>

        <!-- Custom Pages List Card -->
        <?php
        $all_pages_stmt = $pdo->query("SELECT slug, title FROM pages ORDER BY id ASC");
        $all_pages = $all_pages_stmt->fetchAll(PDO::FETCH_ASSOC);
        if (!empty($all_pages)):
        ?>
            <div class="card" style="margin-bottom: 24px;">
                <h3 class="card-title">📂 Vereinsseiten & Infos</h3>
                <div style="display: flex; flex-direction: column; gap: 8px; margin-top: 15px;">
                    <?php foreach ($all_pages as $ap): ?>
                        <a href="index.php?view=pages&slug=<?= urlencode($ap['slug']) ?>" style="text-decoration: none; color: var(--secondary); font-weight: 600; font-size: 13px; padding: 10px; border: 1px solid var(--border-color); border-radius: var(--radius); background: #f8fafc; transition: background 0.2s; display: flex; align-items: center; gap: 8px;" onmouseover="this.style.background='#e2e8f0'" onmouseout="this.style.background='#f8fafc'">
                            <span>📄</span> <span><?= htmlspecialchars($ap['title']) ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Polls card -->
        <div class="card">
            <h3 class="card-title">🗳️ Aktive Abstimmungen</h3>
            <?php if (!empty($polls)): ?>
                <div style="display: flex; flex-direction: column; gap: 20px;">
                    <?php foreach ($polls as $poll): 
                        $options = json_decode($poll['options'], true) ?? [];
                        $user_vote = has_user_voted($poll['id'], $user['id']);
                        $stats = get_vote_statistics($poll['id']);
                    ?>
                        <div style="padding: 15px; background-color: #f8fafc; border: 1px solid var(--border-color); border-radius: var(--radius);">
                            <h4 style="font-size: 15px; font-weight: 700; color: var(--secondary); margin-bottom: 12px;"><?= htmlspecialchars($poll['question']) ?></h4>
                            
                            <?php if ($user_vote): ?>
                                <p style="font-size: 12px; color: var(--primary); font-weight: 600; margin-bottom: 10px;">Du hast abgestimmt für: "<?= htmlspecialchars($user_vote) ?>"</p>
                                <div style="display: flex; flex-direction: column; gap: 8px;">
                                    <?php foreach ($options as $opt): 
                                        $count = $stats['votes'][$opt] ?? 0;
                                        $pct = $stats['total'] > 0 ? round(($count / $stats['total']) * 100) : 0;
                                    ?>
                                        <div>
                                            <div style="display: flex; justify-content: space-between; font-size: 13px; font-weight: 500; margin-bottom: 2px;">
                                                <span><?= htmlspecialchars($opt) ?></span>
                                                <span><?= $count ?> Stimmen (<?= $pct ?>%)</span>
                                            </div>
                                            <div style="background-color: #e2e8f0; height: 8px; border-radius: 4px; overflow: hidden;">
                                                <div style="background-color: var(--primary); width: <?= $pct ?>%; height: 100%;"></div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <form method="POST" action="">
                                    <input type="hidden" name="action" value="vote">
                                    <input type="hidden" name="poll_id" value="<?= $poll['id'] ?>">
                                    <div style="display: flex; flex-direction: column; gap: 8px;">
                                        <?php foreach ($options as $opt): ?>
                                            <label style="display: flex; align-items: center; gap: 10px; font-weight: 500; cursor: pointer; padding: 8px; border: 1px solid var(--border-color); border-radius: var(--radius); background: #fff;">
                                                <input type="radio" name="vote_option" value="<?= htmlspecialchars($opt) ?>" required>
                                                <span><?= htmlspecialchars($opt) ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                    <button type="submit" class="btn btn-primary btn-sm" style="margin-top: 12px; width: 100%;">Stimme abgeben</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p style="color: var(--text-muted); font-size: 13px; text-align: center; padding: 15px;">Aktuell gibt es keine aktiven Umfragen.</p>
            <?php endif; ?>
        </div>
    </div>
</div>
