<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireLogin();

$page_title = 'Notifications';
$uid = $_SESSION['user_id'];

// Mark all read
if (isset($_POST['mark_all_read'])) {
    $conn->query("UPDATE notifications SET status='read' WHERE user_id=$uid");
}

// Bulk delete
if (isset($_POST['bulk_delete']) && !empty($_POST['notif_ids'])) {
    $ids = array_map('intval', $_POST['notif_ids']);
    $ids_str = implode(',', $ids);
    $conn->query("DELETE FROM notifications WHERE id IN ($ids_str) AND user_id=$uid");
}

// Mark single read
if (isset($_GET['read'])) {
    $nid = (int)$_GET['read'];
    $conn->query("UPDATE notifications SET status='read' WHERE id=$nid AND user_id=$uid");
    header("Location: notifications.php");
    exit;
}

$notifications = $conn->query("SELECT * FROM notifications WHERE user_id=$uid ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK</title>
<link rel="stylesheet" href="/lostfound_relink/assets/css/style.css">
</head>
<body>
<div class="layout">
    <?php include '../includes/user_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">
            <div class="card">
                <div class="card-header">
                    <h3>🔔 My Notifications</h3>
                    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                        <button type="button" class="btn btn-sm btn-light" onclick="toggleSelectAll()">☑ Select All</button>
                        <form method="POST" id="userBulkDeleteForm" onsubmit="return confirmBulkDelete()">
                            <button name="bulk_delete" class="btn btn-sm btn-danger" id="userDeleteBtn" disabled>🗑 Delete Selected (<span id="userSelCount">0</span>)</button>
                        </form>
                        <form method="POST"><button name="mark_all_read" class="btn btn-sm btn-secondary">✓ Mark All Read</button></form>
                    </div>
                </div>
                <?php if($notifications->num_rows === 0): ?>
                <div class="text-center" style="padding:60px;color:var(--text-muted)">
                    <div style="font-size:48px;margin-bottom:12px">🔔</div>
                    <p>No notifications yet.</p>
                </div>
                <?php endif; ?>
                <?php while($n=$notifications->fetch_assoc()): ?>
                <div class="notif-item <?= $n['status'] ?>" style="cursor:default">
                    <input type="checkbox" name="notif_ids[]" value="<?= $n['id'] ?>" class="notif-checkbox" form="userBulkDeleteForm"
                           style="width:16px;height:16px;flex-shrink:0;cursor:pointer;accent-color:var(--danger)">
                    <a href="?read=<?= $n['id'] ?>" style="display:contents">
                        <div class="notif-icon"><?= $n['notification_type']==='match'?'🤝':($n['notification_type']==='approved'?'✅':($n['notification_type']==='rejected'?'❌':'🔔')) ?></div>
                        <div class="notif-content" style="flex:1">
                            <div class="msg"><?= htmlspecialchars($n['message']) ?></div>
                            <div class="time"><?= date('M d, Y H:i', strtotime($n['created_at'])) ?> · <span class="badge badge-<?= $n['status'] ?>"><?= $n['status'] ?></span></div>
                        </div>
                    </a>
                </div>
                <?php endwhile; ?>
            </div>
        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
<script>
function toggleSelectAll() {
    const boxes = document.querySelectorAll('.notif-checkbox');
    const allChecked = [...boxes].every(b => b.checked);
    boxes.forEach(b => b.checked = !allChecked);
    updateDeleteBtn();
}

function updateDeleteBtn() {
    const checked = document.querySelectorAll('.notif-checkbox:checked').length;
    const btn = document.getElementById('userDeleteBtn');
    const count = document.getElementById('userSelCount');
    if (btn) { btn.disabled = checked === 0; count.textContent = checked; }
}

function confirmBulkDelete() {
    const count = document.querySelectorAll('.notif-checkbox:checked').length;
    return count > 0 && confirm('Delete ' + count + ' selected notification(s)? This cannot be undone.');
}

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.notif-checkbox').forEach(cb => cb.addEventListener('change', updateDeleteBtn));
});
</script>
