<?php
require_once '../../core/bootstrap.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$user_id = $_SESSION['user_id'];
$notificationModel = new Notification();
$action = $_GET['action'] ?? 'fetch';

if ($action === 'fetch') {
    $notifications = $notificationModel->getUnreadByUser($user_id, 10); // Fetch latest 10
    $unread_count = $notificationModel->getUnreadCountByUser($user_id);
    
    echo json_encode([
        'notifications' => $notifications,
        'unread_count' => $unread_count
    ]);
} elseif ($action === 'mark_as_read') {
    $input = json_decode(file_get_contents('php://input'), true);
    $notification_ids = $input['ids'] ?? [];
    
    if (!empty($notification_ids)) {
        $notificationModel->markAsRead($notification_ids, $user_id); // Pass user_id for security
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'no_ids']);
    }
}
exit();