<?php
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';

header('Content-Type: application/json');
startSecureSession();
if (!isLoggedIn()) { echo json_encode(['error' => 'Unauthorized']); exit; }

$user   = currentUser();
$action = $_GET['action'] ?? 'list';
$pdo    = db();

if ($action === 'list') {
    $s = $pdo->prepare("SELECT * FROM notifications WHERE user_id=? ORDER BY created_at DESC LIMIT 15");
    $s->execute([$user['id']]);
    echo json_encode($s->fetchAll());

} elseif ($action === 'read') {
    $id = (int)($_GET['id'] ?? 0);
    $pdo->prepare("UPDATE notifications SET is_read=1 WHERE id=? AND user_id=?")->execute([$id, $user['id']]);
    echo json_encode(['success' => true]);

} elseif ($action === 'read_all') {
    $pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=?")->execute([$user['id']]);
    echo json_encode(['success' => true]);

} elseif ($action === 'count') {
    $cnt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND is_read=0");
    $cnt->execute([$user['id']]);
    echo json_encode(['count' => (int)$cnt->fetchColumn()]);
}
