<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT'] . '/digital_pos/includes/config.php');

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401); // Unauthorized
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized',
        'threads' => [],
        'count' => 0
    ]);
    exit;
}

$user_id = $_SESSION['user_id'];

// Query to get unread message counts grouped by thread
$query = "
    SELECT COALESCE(reply_to, id) AS thread_id, COUNT(*) AS unread_count
    FROM messages
    WHERE receiver_id = ? AND is_read = 0
    GROUP BY thread_id
";

$stmt = $conn->prepare($query);
if (!$stmt) {
    http_response_code(500); // Internal Server Error
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $conn->error,
        'threads' => [],
        'count' => 0
    ]);
    exit;
}

$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$threads = [];
$totalUnread = 0;

while ($row = $result->fetch_assoc()) {
    $threadId = (int)$row['thread_id'];
    $count = (int)$row['unread_count'];

    $threads[] = [
        'thread_id' => $threadId,
        'unread_count' => $count
    ];
    $totalUnread += $count;
}

$stmt->close();
$conn->close();

// Return JSON response with total unread count and threads details
echo json_encode([
    'success' => true,
    'threads' => $threads,
    'count' => $totalUnread
]);
