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

// Get POST data
$assignment_id = $_POST['assignment_id'];  // This links the message to the admin_assignments table
$recipient_id = $_POST['recipient_id'];    // The surveyor ID
$message = $_POST['message'];
$status = $_POST['status'];                // 'normal' or 'urgent'
$sender_type = 'admin';                    // Admin is sending the message

// Ensure all fields are filled
if (empty($assignment_id) || empty($recipient_id) || empty($message)) {
    echo 'error'; // Send an error response if any field is missing
    exit;
}

// Insert the message into the messages table
$sql = "INSERT INTO messages (assignment_id, sender_type, recipient_id, message, status, sent_at) 
        VALUES (?, ?, ?, ?, ?, UNIX_TIMESTAMP())";
$stmt = $con->prepare($sql);
$stmt->bind_param('isiss', $assignment_id, $sender_type, $recipient_id, $message, $status);

if ($stmt->execute()) {
    echo 'success';
} else {
    echo 'error';
}

$stmt->close();
$con->close();
?>