<?php
if (file_exists('../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../' . $_REQUEST['tenant'] . '/config.php');
}

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

$userId = (int)($_SESSION['userid'] ?? 0);
if (($_SESSION['usertype'] ?? '') === 'admins') {
    $userId = 0;
}

$sinceId = isset($_REQUEST['since_id']) ? max(0, (int)$_REQUEST['since_id']) : 0;

function notificationRows(mysqli $con, int $recipientId, string $extraWhere = '', string $order = 'm.sent_at DESC, m.id DESC', int $limit = 25): array
{
    $sql = "
        SELECT
            m.id,
            m.message,
            m.is_read,
            m.status,
            m.assignment_id,
            m.sender_type,
            m.sent_at,
            CASE
                WHEN m.sender_type = 'admin' THEN 'Admin Team'
                WHEN m.sender_type = 'surveyor' THEN TRIM(CONCAT(COALESCE(s.forename, ''), ' ', COALESCE(s.surname, ''), ' - ', COALESCE(cd.clientname, '')))
                ELSE 'Unknown Sender'
            END AS sender_name
        FROM messages m
        LEFT JOIN admin_assignments aa ON aa.id = m.assignment_id
        LEFT JOIN surveyor s ON aa.surveyor_id = s.id
        LEFT JOIN clientdetails cd ON aa.client_id = cd.clientnumber
        WHERE m.recipient_id = ? $extraWhere
        ORDER BY $order
        LIMIT $limit
    ";
    $stmt = $con->prepare($sql);
    if (!$stmt) return [];
    $stmt->bind_param('i', $recipientId);
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = [];
    while ($row = $result->fetch_assoc()) {
        if (trim((string)$row['sender_name']) === '-' || trim((string)$row['sender_name']) === '') {
            $row['sender_name'] = $row['sender_type'] === 'admin' ? 'Admin Team' : 'Surveyor';
        }
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

$countStmt = $con->prepare("SELECT COUNT(*) AS unread_count FROM messages WHERE recipient_id = ? AND is_read = 0");
$countStmt->bind_param('i', $userId);
$countStmt->execute();
$countRow = $countStmt->get_result()->fetch_assoc();
$unreadCount = (int)($countRow['unread_count'] ?? 0);
$countStmt->close();

$latestStmt = $con->prepare("SELECT COALESCE(MAX(id), 0) AS latest_id FROM messages WHERE recipient_id = ?");
$latestStmt->bind_param('i', $userId);
$latestStmt->execute();
$latestRow = $latestStmt->get_result()->fetch_assoc();
$latestId = (int)($latestRow['latest_id'] ?? 0);
$latestStmt->close();

echo json_encode([
    'unread_count' => $unreadCount,
    'latest_id' => $latestId,
    'messages' => notificationRows($con, $userId),
    'new_messages' => $sinceId > 0
        ? notificationRows($con, $userId, "AND m.is_read = 0 AND m.id > $sinceId", 'm.id ASC', 5)
        : []
]);

$con->close();
?>
