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

// Fetch unread messages for the specific surveyor
$surveyor_id = $_SESSION['userid'];  // Assuming surveyor ID is stored in the session

$sql = "SELECT assignment_id, message, status, sent_at 
        FROM messages 
        WHERE sender_type = 'admin' 
        AND recipient_id = ? 
        AND is_read = 0 
        ORDER BY sent_at DESC";

$stmt = $con->prepare($sql);
$stmt->bind_param('i', $surveyor_id);
$stmt->execute();
$result = $stmt->get_result();

$messages = [];

while ($row = $result->fetch_assoc()) {
    $messages[] = [
        'assignment_id' => $row['assignment_id'],
        'message' => $row['message'],
        'status' => $row['status'],
        'sent_at' => date('d-m-Y H:i', $row['sent_at'])
    ];
}

echo json_encode(['messages' => $messages]);
$con->close();
?>