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

// Get POST data and validate
$surveyor_id = isset($_POST['surveyor_id']) ? intval($_POST['surveyor_id']) : 0;
$message = isset($_POST['message']) ? trim($_POST['message']) : '';

if ($surveyor_id <= 0 || empty($message)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid input']);
    exit;
}

// Prepare the SQL query to send a notification to the surveyor
$sql = "INSERT INTO messages (assignment_id, sender_type, recipient_id, message, status, sent_at)
        VALUES (0, 'admin', ?, ?, 'normal', UNIX_TIMESTAMP())";

$stmt = $con->prepare($sql);

if (!$stmt) {
    // Log error if statement preparation fails
    error_log("SQL Error: " . $con->error);
    echo json_encode(['status' => 'error', 'message' => 'Failed to prepare SQL']);
    exit;
}

// Bind parameters and execute the statement
$stmt->bind_param('is', $surveyor_id, $message);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success']);
} else {
    error_log("Execution Error: " . $stmt->error);
    echo json_encode(['status' => 'error', 'message' => 'Failed to send notification']);
}

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