/**
 * Transmit HL7 for the specified lab.
 *
 * @param  integer $ppid  Procedure provider ID.
 * @param  string  $out   The HL7 text to be sent.
 * @return string         Error text, or empty if no errors.
 */
function send_hl7_order($ppid, $out)
{
    global $srcdir;
    $d0 = "\r";
    $pprow = sqlQuery("SELECT * FROM procedure_providers " . "WHERE ppid = ?", array($ppid));
    if (empty($pprow)) {
        return xl('Procedure provider') . " {$ppid} " . xl('not found');
    }
    $protocol = $pprow['protocol'];
    $remote_host = $pprow['remote_host'];
    // Extract MSH-10 which is the message control ID.
    $segmsh = explode(substr($out, 3, 1), substr($out, 0, strpos($out, $d0)));
    $msgid = $segmsh[9];
    if (empty($msgid)) {
        return xl('Internal error: Cannot find MSH-10');
    }
    if ($protocol == 'DL' || $pprow['orders_path'] === '') {
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=order_{$msgid}.hl7");
        header("Content-Description: File Transfer");
        echo $out;
        exit;
    } else {
        if ($protocol == 'SFTP') {
            // Compute the target path/file name.
            $filename = $msgid . '.txt';
            if ($pprow['orders_path']) {
                $filename = $pprow['orders_path'] . '/' . $filename;
            }
            // Connect to the server and write the file.
            $sftp = new \phpseclib\Net\SFTP($remote_host);
            if (!$sftp->login($pprow['login'], $pprow['password'])) {
                return xl('Login to this remote host failed') . ": '{$remote_host}'";
            }
            if (!$sftp->put($filename, $out)) {
                return xl('Creating this file on remote host failed') . ": '{$filename}'";
            }
        } else {
            if ($protocol == 'FS') {
                // Compute the target path/file name.
                $filename = $msgid . '.txt';
                if ($pprow['orders_path']) {
                    $filename = $pprow['orders_path'] . '/' . $filename;
                }
                $fh = fopen("{$filename}", 'w');
                if ($fh) {
                    fwrite($fh, $out);
                    fclose($fh);
                } else {
                    return xl('Cannot create file') . ' "' . "{$filename}" . '"';
                }
            } else {
                return xl('This protocol is not implemented') . ": '{$protocol}'";
            }
        }
    }
    // Falling through to here indicates success.
    newEvent("proc_order_xmit", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "ID: {$msgid} Protocol: {$protocol} Host: {$remote_host}");
    return '';
}