<?php
// ==========================
// notifications.php - DemoBank (FINAL)
// ==========================

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

// Ensure user is logged in
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    header("Location: /auth/login.php");
    exit;
}

// Database connection
$conn = db();
if (!$conn) die("Database connection failed");

// ==========================
// Fetch notifications
// ==========================
$notifications = [];

$stmt = $conn->prepare("
    SELECT id, message, is_read, created_at
    FROM notifications
    WHERE user_id = ?
    ORDER BY created_at DESC
");

if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $notifications = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// ==========================
// Mark all as read
// ==========================
$stmt = $conn->prepare("UPDATE notifications SET is_read=1 WHERE user_id=?");
if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();
}

// ==========================
// Capture content
// ==========================
ob_start();
?>

<h1>🔔 Notifications</h1>

<?php if (empty($notifications)): ?>
    <p>No notifications available.</p>
<?php else: ?>

<div style="display:flex;flex-direction:column;gap:15px;margin-top:20px;">

    <?php foreach ($notifications as $note): 
        $is_unread = ($note['is_read'] == 0);
    ?>

    <div style="
        padding:15px;
        border-radius:10px;
        background: <?= $is_unread ? '#eef5ff' : '#ffffff'; ?>;
        border-left: 5px solid <?= $is_unread ? '#1a73e8' : '#ddd'; ?>;
        box-shadow:0 2px 6px rgba(0,0,0,0.05);
    ">

        <div style="display:flex;justify-content:space-between;align-items:center;">
            <p style="margin:0;font-weight:500;">
                <?= htmlspecialchars($note['message']); ?>
            </p>

            <?php if ($is_unread): ?>
                <span style="
                    background:#1a73e8;
                    color:white;
                    font-size:11px;
                    padding:3px 8px;
                    border-radius:12px;
                ">NEW</span>
            <?php endif; ?>
        </div>

        <small style="color:#777;">
            <?= htmlspecialchars($note['created_at']); ?>
        </small>

    </div>

    <?php endforeach; ?>

</div>

<?php endif; ?>

<?php
$content = ob_get_clean();

// ==========================
// Render layout
// ==========================
renderLayout("Notifications", $content, $conn);