<?php
// modules/notifications/ajax.php
// Self-service notification actions for the logged-in web user.
// Scoped to the user's own employee_id AND/OR user_id — most logins only
// ever get notifications by employee_id, but superadmin logins (which may
// have no linked employee) receive theirs by user_id instead. See
// notify()/notifyAllSuperadmins() in includes/functions.php.
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
header('Content-Type: application/json');

$db     = Database::getInstance();
$user   = currentUser();
$empId  = (int)($user['emp_id'] ?? 0);
$userId = (int)($user['id'] ?? 0);

// Must be resolvable to at least one of the two — in practice always
// true since every logged-in user has a user_id.
if (!$empId && !$userId) {
    echo json_encode(['success' => false, 'message' => 'No employee or user linked to this login.']);
    exit;
}

$action = $_REQUEST['action'] ?? '';

// JSON-safe CSRF check for this endpoint. The shared verifyCsrf() dies
// with a full HTML error page on failure, which breaks fetch().json() on
// the client (the request looks like it silently did nothing) even
// though this file already declared Content-Type: application/json.
function requireJsonCsrf(): void {
    if (($_POST['csrf_token'] ?? '') !== ($_SESSION['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'message' => 'Your session has expired. Please refresh the page and try again.']);
        exit;
    }
}

try {
    if ($action === 'list') {
        $notifs = $db->fetchAll(
            "SELECT id,title,message,type,ref_id,is_read,created_at FROM notifications
              WHERE employee_id=? OR user_id=? ORDER BY created_at DESC LIMIT 30",
            [$empId, $userId]
        );
        echo json_encode(['success' => true, 'notifications' => $notifs]);

    } elseif ($action === 'unread_count') {
        $count = (int)$db->fetchValue(
            "SELECT COUNT(*) FROM notifications WHERE (employee_id=? OR user_id=?) AND is_read=0",
            [$empId, $userId]
        );
        echo json_encode(['success' => true, 'count' => $count]);

    } elseif ($action === 'mark_read') {
        requireJsonCsrf();
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) throw new Exception('id is required');
        $db->execute("UPDATE notifications SET is_read=1 WHERE id=? AND (employee_id=? OR user_id=?)", [$id, $empId, $userId]);
        echo json_encode(['success' => true]);

    } elseif ($action === 'mark_unread') {
        requireJsonCsrf();
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) throw new Exception('id is required');
        $db->execute("UPDATE notifications SET is_read=0 WHERE id=? AND (employee_id=? OR user_id=?)", [$id, $empId, $userId]);
        echo json_encode(['success' => true]);

    } elseif ($action === 'mark_all_read') {
        requireJsonCsrf();
        $db->execute("UPDATE notifications SET is_read=1 WHERE employee_id=? OR user_id=?", [$empId, $userId]);
        echo json_encode(['success' => true]);

    } elseif ($action === 'mark_all_unread') {
        requireJsonCsrf();
        $db->execute("UPDATE notifications SET is_read=0 WHERE employee_id=? OR user_id=?", [$empId, $userId]);
        echo json_encode(['success' => true]);

    } else {
        echo json_encode(['success' => false, 'message' => 'Unknown action']);
    }
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
