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

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Messaging.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $messaging = new Messaging($conn);
    $unreadCount = $messaging->getUnreadCount((int)$_SESSION['user_id']);
    echo json_encode(['success' => true, 'unread_count' => $unreadCount]);
} catch (Throwable $e) {
    error_log('Fetching unread message count failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to load unread count.']);
}
