<?php
// Filename: admin_feedback.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'timetable_coord', 'principal', 'assistant'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

// --- SECURITY HEADERS ---
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$msg = ''; $msg_type = '';

// 2. HANDLE ACTIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die("Security Alert: Invalid Request (CSRF).");
    }

    $id = $_POST['id'];
    $action = $_POST['action'];

    if ($action === 'mark_read') {
        $pdo->prepare("UPDATE system_suggestions SET status = 'read' WHERE id = ?")->execute([$id]);
        // Optional: Add success message or just refresh
    } elseif ($action === 'delete') {
        $pdo->prepare("DELETE FROM system_suggestions WHERE id = ?")->execute([$id]);
        $msg = "Feedback deleted successfully."; $msg_type = "warning";
    }
}

// 3. FETCH FEEDBACK
$sql = "SELECT s.*, u.full_name, u.role 
        FROM system_suggestions s 
        JOIN users u ON s.user_id = u.id 
        ORDER BY s.status ASC, s.created_at DESC";
$feedback = $pdo->query($sql)->fetchAll();

// Count unread
$unread_count = 0;
foreach($feedback as $f) { if($f['status'] == 'new') $unread_count++; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>User Feedback</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; ... }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        /* HEADER */
        .app-header {
            background: var(--primary-grad); padding: 30px 20px 80px 20px;
            border-radius: 0 0 35px 35px; color: white; text-align: center;
        }

        /* FLOATING CARD */
        .floating-card {
            background: white; margin: -60px 20px 20px 20px;
            border-radius: 24px; padding: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.08);
            position: relative; z-index: 10;
        }

        /* FEEDBACK ITEM */
        .feedback-item {
            border: 1px solid #f1f5f9; border-radius: 16px; padding: 15px; margin-bottom: 15px;
            transition: transform 0.2s; position: relative; overflow: hidden;
            background: white;
        }
        .feedback-item:active { transform: scale(0.99); background-color: #f8fafc; }
        
        /* Status Indicators */
        .status-bar { position: absolute; left: 0; top: 0; bottom: 0; width: 5px; }
        .is-new .status-bar { background-color: #8B5CF6; } /* Purple for new */
        .is-read .status-bar { background-color: #e2e8f0; } /* Gray for read */
        .is-new { background-color: #fcfaff; border-color: #f3e8ff; }

        .avatar-circle {
            width: 40px; height: 40px; border-radius: 50%; 
            display: flex; align-items: center; justify-content: center;
            font-weight: 800; font-size: 1rem; margin-right: 12px;
            flex-shrink: 0;
        }
        
        .role-badge { font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: 700; margin-left: 5px; }
        .bg-teacher { background: #e0f2fe; color: #0284c7; }
        .bg-admin { background: #fee2e2; color: #ef4444; }

        .msg-box { background: #f8fafc; padding: 10px; border-radius: 10px; font-size: 0.85rem; color: #334155; margin-top: 10px; border: 1px dashed #e2e8f0; }

        /* BOTTOM NAV 
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 18px 30px; display: flex; justify-content: space-between; border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); z-index: 100; }
        .nav-btn { display: flex; flex-direction: column; align-items: center; color: #94a3b8; text-decoration: none; font-size: 0.7rem; font-weight: 600; }
        .nav-btn.active { color: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; } */
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Feedback</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Suggestions & Bug Reports</div>
    </div>

    <div class="floating-card">
        
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-4 fw-bold"><?= $msg ?></div>
        <?php endif; ?>

        <div class="d-flex justify-content-between align-items-center mb-4">
            <h6 class="fw-bold text-dark m-0">Inbox</h6>
            <?php if($unread_count > 0): ?>
                <span class="badge bg-primary rounded-pill shadow-sm"><?= $unread_count ?> New</span>
            <?php else: ?>
                <span class="badge bg-light text-muted border rounded-pill">All Read</span>
            <?php endif; ?>
        </div>

        <?php if(empty($feedback)): ?>
            <div class="text-center py-5 text-muted small opacity-50">
                <i class="bi bi-inbox display-1"></i><br>No feedback received yet.
            </div>
        <?php else: ?>
            <div class="d-flex flex-column gap-2">
                <?php foreach($feedback as $f): 
                    $is_new = ($f['status'] == 'new');
                    $wrapper_class = $is_new ? 'is-new' : 'is-read';
                    
                    // Avatar Color based on Role
                    $av_bg = (strpos($f['role'], 'admin') !== false) ? 'bg-danger bg-opacity-10 text-danger' : 'bg-primary bg-opacity-10 text-primary';
                    
                    // Role Badge
                    $role_bg = (strpos($f['role'], 'admin') !== false) ? 'bg-admin' : 'bg-teacher';
                ?>
                <div class="feedback-item <?= $wrapper_class ?>">
                    <div class="status-bar"></div>
                    
                    <div class="d-flex align-items-center mb-2 ps-2">
                        <div class="avatar-circle <?= $av_bg ?>">
                            <?= strtoupper(substr($f['full_name'], 0, 1)) ?>
                        </div>
                        <div class="flex-grow-1 overflow-hidden">
                            <div class="d-flex align-items-center">
                                <span class="fw-bold text-dark text-truncate"><?= htmlspecialchars($f['full_name']) ?></span>
                                <span class="role-badge <?= $role_bg ?>"><?= ucfirst($f['role']) ?></span>
                            </div>
                            <div class="small text-muted" style="font-size:0.7rem;">
                                <?= date('d M h:i A', strtotime($f['created_at'])) ?>
                            </div>
                        </div>
                        
                        <?php if($is_new): ?>
                        <form method="POST" style="margin:0;">
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                            <input type="hidden" name="action" value="mark_read">
                            <input type="hidden" name="id" value="<?= $f['id'] ?>">
                            <button class="btn btn-sm btn-light text-primary rounded-circle shadow-sm border" title="Mark as Read">
                                <i class="bi bi-check2-all"></i>
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>

                    <div class="ps-2">
                        <div class="fw-bold text-dark small mb-1"><?= htmlspecialchars($f['subject']) ?></div>
                        <div class="msg-box">
                            <?= nl2br(htmlspecialchars($f['message'])) ?>
                        </div>
                        
                        <div class="text-end mt-2">
                            <form method="POST" onsubmit="return confirm('Delete this feedback?');" style="display:inline;">
                                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $f['id'] ?>">
                                <button class="btn btn-sm text-danger p-0 small fw-bold" style="font-size:0.75rem; text-decoration:none;">
                                    <i class="bi bi-trash me-1"></i> Delete
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    </div>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>