<?php
require_once __DIR__ . '/db.php';
require_login();

$action = trim($_POST['action'] ?? '');
$selectedIds = $_POST['selected_notifications'] ?? [];
$userId = current_user_id();

if (!is_array($selectedIds)) {
    $selectedIds = [];
}

$selectedIds = array_values(array_filter(array_map('intval', $selectedIds), static fn($id) => $id > 0));

if (empty($selectedIds)) {
    header('Location: notifications.php?error=no_selection');
    exit();
}

$placeholders = implode(',', array_fill(0, count($selectedIds), '?'));
$types = str_repeat('i', count($selectedIds) + 1);
$params = array_merge([$userId], $selectedIds);

if ($action === 'mark_read') {
    $sql = "
        UPDATE notifications
        SET is_read = 1, read_at = NOW()
        WHERE user_id = ? AND id IN ({$placeholders})
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    header('Location: notifications.php?success=marked');
    exit();
}

if ($action === 'delete') {
    $sql = "
        DELETE FROM notifications
        WHERE user_id = ? AND id IN ({$placeholders})
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    header('Location: notifications.php?success=deleted');
    exit();
}

header('Location: notifications.php');
exit();
