/**
 * create a display for an individual claim status response	
 * 
 * @uses csv_check_x12_obj()
 * @uses edih_271_transaction_html()
 * 
 * @param string  $filename the filename
 * @param string  $bht03 identifier from 837 CLM or BHT segment
 * 
 * @return string  either an error message or an html table 
 */
function edih_271_html($filename, $bht03 = '')
{
    // create a display for an individual 277 response
    $html_str = '';
    //
    if ($filename) {
        $obj271 = csv_check_x12_obj($filename, 'f271');
        if ('edih_x12_file' == get_class($obj271)) {
            if ($bht03) {
                // particular transaction
                $html_str .= edih_271_transaction_html($obj271, $bht03);
            } else {
                // file contents
                $env_ar = $obj271->edih_envelopes();
                if (!isset($env_ar['ST'])) {
                    $html_str .= "<p>edih_271_html: file parse error, envelope error</p>" . PHP_EOL;
                    $html_str .= $obj271->edih_message();
                    return $html_str;
                } else {
                    $html_str .= "<div id='accordion'>" . PHP_EOL;
                }
                foreach ($env_ar['ST'] as $st) {
                    foreach ($env_ar['GS'] as $gs) {
                        if ($gs['icn'] != $st['icn']) {
                            continue;
                        }
                        if ($gs['gsn'] == $st['gsn']) {
                            $gs_date = edih_format_date($gs['date']);
                            $gs_sender = $gs['sender'];
                            break;
                        }
                    }
                    //
                    // get each transaction
                    foreach ($st['bht03'] as $bht) {
                        $html_str .= "<h3>{$bht} Benefit Eligibility</h3>" . PHP_EOL;
                        $html_str .= "<div id='ac_{$bht}'>" . PHP_EOL;
                        //
                        $html_str .= edih_271_transaction_html($obj271, $bht);
                        //
                        $html_str .= "</div>" . PHP_EOL;
                    }
                    $html_str .= "</div>" . PHP_EOL;
                }
            }
        } else {
            $html_str .= "<p>edih_271_html: file parse error</p>" . PHP_EOL;
        }
    } else {
        csv_edihist_log("edih_271_html: error in file arguments");
        $html_str .= "Error: invalid file name<br />" . PHP_EOL;
        return $html_str;
    }
    //
    return $html_str;
}
/**
 * Main function in this script
 *
 * @uses csv_check_x12_obj()
 * @uses edih_997_errdata()
 * @uses edih_997_err_report()
 * 
 * @param string
 * @return string
 */
function edih_997_error($filepath)
{
    //
    $html_str = '';
    //
    $obj997 = csv_check_x12_obj($filepath, 'f997');
    if ($obj997 && 'edih_x12_file' == get_class($obj997)) {
        $data = edih_997_errdata($obj997);
        $html_str .= edih_997_err_report($data);
    } else {
        $html_str .= "<p>Error: invalid file path</p>" . PHP_EOL;
        csv_edihist_log("edih_997_error: invalid file path {$filepath}");
    }
    return $html_str;
}
/**
 * Display of x12 edi transaction listing or all segments in the files.
 * When using $err_info, you must use the filepath of the submitted file
 * 
 * @param string   $filepath path to desired file
 * @param string   $filetype used when filepath is just filename
 * @param string   optional $claimid CLM01, or BHT03 to identify a transaction or a trace value 
 * @param bool     false: $claimid is pt transaction, true: $claimid is trace from 835 or 999 
 * @param string   optional $err_info  the prepared error info from a 997/999 response
 * @return string  html for display of file segments
 */
function edih_display_text($filepath, $filetype = '', $claimid = '', $trace = false, $err_info = '')
{
    //
    $str_html = '';
    $de = '';
    $segments = '';
    $stsegkey = '';
    $ft = $filetype ? $filetype : '';
    $errs = strlen($err_info) ? $err_info : '';
    $bht03 = '';
    //
    // verify x12 file
    $x12obj = csv_check_x12_obj($filepath, $ft);
    //
    if ($x12obj && 'edih_x12_file' == get_class($x12obj)) {
        $ftype = $x12obj->edih_type();
        $ft = csv_file_type($ftype);
        $delims = $x12obj->edih_delimiters();
        $de = $delims['e'];
        $fn = $x12obj->edih_filename();
        $segs_ar = $x12obj->edih_segments();
        $env_ar = $x12obj->edih_envelopes();
        if (!$de || strlen($de) != 1) {
            // error in object
            // debug
            $str_html = 'edih_display_text(): error in delimiters<br />' . PHP_EOL;
            $str_html .= $x12obj->edih_message() . PHP_EOL;
            return $str_html;
        }
        if (!is_array($segs_ar) || !count($segs_ar)) {
            // unknown error
            $str_html = "<p>unknown error retrieving segments for {$fn}</p>" . PHP_EOL;
            $str_html .= $x12obj->edih_message() . PHP_EOL;
            return $str_html;
        }
    } else {
        //debug
        csv_edihist_log('edih_transaction_text(): invalid path ' . $filepath);
        $str_html = 'edih_display_text(): error accessing file<br />' . PHP_EOL;
        return $str_html;
    }
    //
    if ($claimid) {
        // claimid can be for transaction, payment, or error response
        if ($trace && array_key_exists($claimid, $env_ar['ISA'])) {
            $arg_ar = array('ISA13' => $claimid, 'keys' => true);
            $segments = $x12obj->edih_x12_slice($arg_ar);
        } else {
            // claimid alone can be clm01 or bht03, if trace=true, expect trn02 for claimid
            foreach ($env_ar['ST'] as $st) {
                if ($trace && $claimid == $st['trace']) {
                    $arg_ar = array('ISA13' => $st['icn'], 'GS06' => $st['gsn'], 'trace' => $claimid, 'keys' => true);
                    $segments = $x12obj->edih_x12_slice($arg_ar);
                    break;
                } elseif (in_array($claimid, $st['acct'])) {
                    if ($errs) {
                        $arg_ar = array('ST02' => $st['stn'], 'ISA13' => $st['icn'], 'GS06' => $st['gsn'], 'keys' => true);
                        $segments = $x12obj->edih_x12_slice($arg_ar);
                    } else {
                        // request for individual transaction segments
                        $segments = $x12obj->edih_x12_transaction($claimid);
                    }
                    break;
                } elseif (in_array($claimid, $st['bht03'])) {
                    // also possible that bht03 number is given for claimid
                    // this will likely be a 27x
                    if ($errs) {
                        $arg_ar = array('ST02' => $st['stn'], 'ISA13' => $st['icn'], 'GS06' => $st['gsn'], 'keys' => true);
                        $segments = $x12obj->edih_x12_slice($arg_ar);
                    } else {
                        $segments = $x12obj->edih_x12_transaction($claimid);
                    }
                    $bht03 = $claimid;
                    break;
                }
            }
        }
    } else {
        $segments = $segs_ar;
    }
    //
    // now check if we have segments
    if (empty($segments) || !count($segments)) {
        if ($claimid) {
            $str_html = "<p>error: transaction {$claimid} not found in {$fn}</p>" . PHP_EOL;
            $str_html .= $x12obj->edih_message() . PHP_EOL;
            return $str_html;
        } else {
            // unknown error
            $str_html = "<p>unknown error retrieving segments for {$fn}</p>" . PHP_EOL;
            $str_html .= $x12obj->edih_message() . PHP_EOL;
            return $str_html;
        }
    }
    // if the segments are from a slice or transaction
    // a multidimensional array  segs[i][j] must be flattened
    $ar_sngl = csv_singlerecord_test($segments);
    // false when segments are a transaction or trace only
    if (!$ar_sngl) {
        //
        // append segments to single array
        // keys should not duplicate since all segments
        // are from the same x12 file
        $trnsegs = array();
        for ($i = 0; $i < count($segments); $i++) {
            $trnsegs = array_merge($trnsegs, $segments[$i]);
        }
        $segments = $trnsegs;
        unset($trnsegs);
    }
    //
    $capstr = '';
    $tbl_id = $claimid ? $claimid : $fn;
    //
    //'HB'=>'271', 'HS'=>'270', 'HR'=>'276', 'HI'=>'278','HN'=>'277', 'HP'=>'835', 'FA'=>'999', 'HC'=>'837');
    switch ((string) $ftype) {
        case 'HC':
            $capstr = "Claim ";
            //$cls = "txt837";
            $trn_html = edih_837_text($segments, $de, $errs);
            break;
        case 'HP':
            $capstr = "Payment ";
            //$cls = "txt835";
            $trn_html = edih_835_text($segments, $de);
            break;
        case 'HR':
            $capstr = "Status Query ";
            //$cls = "txt276";
            $trn_html = edih_277_text($segments, $de, $errs);
            break;
        case 'HN':
            $capstr = "Claim Status ";
            //$cls = "txt277";
            $trn_html = edih_277_text($segments, $de, $stsegkey);
            break;
        case 'HS':
            $capstr = "Eligibility Query ";
            //$cls = "txt270";
            $trn_html = edih_271_text($segments, $de, $errs);
            break;
        case 'HB':
            $capstr = "Eligibility Report ";
            //$cls = "txt271";
            $trn_html = edih_271_text($segments, $de);
            break;
        case 'HI':
            $capstr = "Authorization ";
            //$cls = "txt278";
            $trn_html = edih_278_text($segments, $de, $errs);
            break;
        case 'FA':
            $capstr = "Batch Acknowledgment ";
            //$cls = "txt997";
            $trn_html = edih_997_text($segments, $de);
            break;
        default:
            $capstr = "x12 {$ftype} ";
            //$cls = "txt_x12";
            $trn_html = edih_segments_text($segments, $de);
            break;
    }
    //
    $capstr .= $claimid ? " <em>ID:</em> {$claimid}" : "";
    //
    $str_html .= "<table id={$tbl_id} cols=3 class='segtxt'><caption>{$capstr}</caption>" . PHP_EOL;
    $str_html .= "<thead>" . PHP_EOL;
    $str_html .= "<tr><th class='btloop'>Loop</th><th class='btloop'>Num</th>";
    $str_html .= "<th class='segtxt'>Segment (<em>File:</em> {$fn})</th></tr>" . PHP_EOL;
    $str_html .= "</thead>" . PHP_EOL . "<tbody>" . PHP_EOL;
    //
    $str_html .= $trn_html;
    //
    $str_html .= "</tbody></table>" . PHP_EOL;
    //
    return $str_html;
}
function edih_parse_select($file_path)
{
    $csvdata = array();
    // csvdata array design:
    //  $csvdata[$icn]['claims'][i]  [$icn]['files'][i]  [$icn]['type']
    //
    $x12_obj = csv_check_x12_obj($file_path);
    //$x12_obj = new edih_x12_file($file_path);
    if ($x12_obj instanceof edih_x12_file) {
        $ft = $x12_obj->edih_type();
    } else {
        csv_edihist_log('edih_parse_select: error in file path');
        return $csvdata;
    }
    //'HB'=>'271', 'HS'=>'270', 'HR'=>'276', 'HI'=>'278',
    //'HN'=>'277', 'HP'=>'835', 'FA'=>'999', 'HC'=>'837'
    //
    if ($ft == 'HP') {
        $csvdata = edih_835_csv_data($x12_obj);
    } elseif ($ft == 'HC') {
        $csvdata = edih_837_csv_data($x12_obj);
    } elseif ($ft == 'HN' || $ft == 'HR') {
        $csvdata = edih_277_csv_data($x12_obj);
    } elseif ($ft == 'FA') {
        $csvdata = edih_997_csv_data($x12_obj);
    } elseif ($ft == 'HB' || $ft == 'HS') {
        $csvdata = edih_271_csv_data($x12_obj);
    } elseif ($ft == 'HI') {
        $csvdata = edih_278_csv_data($x12_obj);
    } else {
        // debug
        csv_edihist_log('edih_parse_select(): unsupported file type ' . $ft . ' name: ' . basename($file_path));
    }
    //
    return $csvdata;
}
/**
 * create a display for an individual claim status response	
 *
 * @uses csv_check_x12_obj()
 * @uses edih_277_transaction_html()
 * 
 * @param string  $filename the filename
 * @param string  $clm01 identifier from 837 CLM of BHT segment
 * 
 * @return string  either an error message or a table with the information from the response
 */
function edih_277_html($filename, $bht03 = '')
{
    // create a display for an individual 277 response
    $html_str = '';
    //
    if ($filename) {
        $fn = $filename;
    } else {
        csv_edihist_log("edih_277_html: called with no file arguments");
        $html_str .= "Error, no file given<br />" . PHP_EOL;
        return $html_str;
    }
    if ($fn) {
        $obj277 = csv_check_x12_obj($fn, 'f277');
        if ($obj277 && 'edih_x12_file' == get_class($obj277)) {
            if ($bht03) {
                // particular transaction
                $html_str .= edih_277_transaction_html($obj277, $bht03);
            } else {
                // file contents
                $env_ar = $obj277->edih_envelopes();
                if (!isset($env_ar['ST'])) {
                    $html_str .= "<p>edih_277_html: file parse error, envelope error</p>" . PHP_EOL;
                    $html_str .= $obj277->edih_message();
                    return $html_str;
                } else {
                    $html_str .= "<div id='accordion'>" . PHP_EOL;
                }
                foreach ($env_ar['ST'] as $st) {
                    foreach ($env_ar['GS'] as $gs) {
                        if ($gs['icn'] != $st['icn']) {
                            continue;
                        } else {
                            $gs_date = edih_format_date($gs['date']);
                            $gs_sender = $gs['sender'];
                            break;
                        }
                    }
                    //
                    // get each transaction
                    foreach ($st['bht03'] as $bht) {
                        //$html_str .= "<h3>$bht Claim Status <em>Date</em> $gs_date <em>Source</em> $gs_sender</h3>".PHP_EOL;
                        //$html_str .= "<div id='ac_$bht'>".PHP_EOL;
                        //
                        $html_str .= edih_277_transaction_html($obj277, $bht, true);
                        //
                        //$html_str .= "</div>".PHP_EOL;
                    }
                }
                $html_str .= "</div>" . PHP_EOL;
            }
        } else {
            $html_str .= "<p>{$filename} : file parse error</p>" . PHP_EOL;
        }
    } else {
        $html_str .= "Error with file name or file parsing <br />" . PHP_EOL;
        csv_edihist_log("edih_277_html: error in retreiving file object");
        return $html_str;
    }
    //
    return $html_str;
}
/**
 * create a display for an individual authorization response	
 * 
 * @uses csv_check_x12_obj()
 * @uses edih_278_transaction_html
 * 
 * @param string  $filename the filename
 * @param string  $bht03 identifier from 837 CLM or27 BHT segment
 * 
 * @return string  either an error message or an html table
 */
function edih_278_html($filename, $bht03 = '')
{
    // create a display for an individual 277 response
    $html_str = '';
    //
    if (!$filename) {
        csv_edihist_log("edih_278_html: called with no file arguments");
        $html_str .= "Error, no file given<br />" . PHP_EOL;
        return $html_str;
    } else {
        $obj278 = csv_check_x12_obj($filename, 'f278');
        if ($obj278 && 'edih_x12_file' == get_class($obj278)) {
            if ($bht03) {
                // particular transaction
                $html_str .= edih_278_transaction_html($obj278, $bht03);
            } else {
                // file contents
                $env_ar = $obj278->edih_envelopes();
                if (!isset($env_ar['ST'])) {
                    $html_str .= "<p>edih_278_html: file parse error, envelope error</p>" . PHP_EOL;
                    $html_str .= $obj278->edih_message();
                    return $html_str;
                } else {
                    $html_str .= "<div id='accordion'>" . PHP_EOL;
                }
                foreach ($env_ar['ST'] as $st) {
                    foreach ($env_ar['GS'] as $gs) {
                        if ($gs['icn'] != $st['icn']) {
                            continue;
                        }
                        if ($gs['gsn'] == $st['gsn']) {
                            $gs_date = edih_format_date($gs['date']);
                            $gs_sender = $gs['sender'];
                            break;
                        }
                    }
                    //
                    // get each transaction
                    foreach ($st['bht03'] as $bht) {
                        $html_str .= "<h3>{$bht} Services Review</h3>" . PHP_EOL;
                        $html_str .= "<div id='ac_{$bht}'>" . PHP_EOL;
                        //
                        $html_str .= edih_278_transaction_html($obj278, $bht);
                        //
                        $html_str .= "</div>" . PHP_EOL;
                    }
                    $html_str .= "</div>" . PHP_EOL;
                }
            }
        } else {
            csv_edihist_log("edih_278_html: error in retreiving file object");
            $html_str .= "<p>x12 278 file parse error</p>" . PHP_EOL;
        }
    }
    //
    return $html_str;
}
/**
 * create a display for an 835 claim payment file or transaction
 *
 * @uses csv_check_x12_obj()
 * 
 * @param string  $filename the filename
 * @param string  TRN02 identifier from 835 check ir EFT
 * @param string  CLM01 identifier from 837 CLM
 * 
 * @return string  error message or a table with file information
 */
function edih_835_html($filename, $trace = '', $clm01 = '', $summary = false)
{
    //
    $html_str = '';
    //
    if (trim($filename)) {
        $obj835 = csv_check_x12_obj($filename, 'f835');
        if ($obj835 && 'edih_x12_file' == get_class($obj835)) {
            $fn = $obj835->edih_filename();
            $delims = $obj835->edih_delimiters();
            $env_ar = $obj835->edih_x12_envelopes();
            //
            $de = isset($delims['e']) ? $delims['e'] : '';
            $ds = isset($delims['s']) ? $delims['s'] : '';
            $dr = isset($delims['r']) ? $delims['r'] : '';
            // $dr is not used, but just in case
        } else {
            $html_str .= "<p>edih_835_html: invalid file name</p>" . PHP_EOL;
            return $html_str;
        }
    } else {
        $html_str .= "Error in file name or file parsing <br />" . PHP_EOL;
        csv_edihist_log("edih_835_html: error in parsing file {$filename}");
        return $html_str;
    }
    if ($de && $ds) {
        // note $dr, repetition separator, is not always available
        $cd27x = new edih_271_codes($ds, $dr);
        $cd835 = new edih_835_codes($ds, $dr);
    } else {
        csv_edihist_log("edih_835_html: Did not get delimiters");
        $html_str .= "<p>Did not get delimiters for {$fn}</p>" . PHP_EOL;
        return $html_str;
    }
    //
    // if given, one only of trace or clm01
    $pid = $chk = '';
    if ($clm01) {
        $pid = trim((string) $clm01);
    } elseif ($trace) {
        $chk = trim((string) $trace);
    }
    //
    if ($pid) {
        $clp_ar = $obj835->edih_x12_transaction($pid);
        // $clp_ar is array[i][j]
        if (count($clp_ar)) {
            if ($summary) {
                $html_str .= edih_835_clp_summary($clp_ar, $cd27x, $cd835, $delims, $fn);
            } else {
                // create a table for this transaction for jquery-ui dialog
                $html_str .= edih_835_transaction_html($clp_ar, $cd27x, $cd835, $delims, $fn);
            }
        } else {
            csv_edihist_log("edih_835_html: Did not find PtID {$pid} in {$fn}");
            $html_str .= "<p>Did not find PtID {$pid} in {$fn}</p>" . PHP_EOL;
            return $html_str;
        }
    } elseif ($chk) {
        // check detail
        if (isset($env_ar['ST']) && count($env_ar['ST'])) {
            $trans_ar = array();
            foreach ($env_ar['ST'] as $st) {
                if ($st['trace'] != $chk) {
                    continue;
                }
                $trans_ar[] = $obj835->edih_x12_slice(array('trace' => $chk));
            }
        } else {
            csv_edihist_log("edih_835_transaction_html: Did not get envelopes information for {$fn}");
            $html_str .= "<p>Did not get envelopes information for {$fn}</p>" . PHP_EOL;
            return $html_str;
        }
        if (is_array($trans_ar) && count($trans_ar)) {
            // $trans_ar is a slice, array[i]
            $html_str .= edih_835_payment_html($trans_ar, $cd27x, $cd835, $delims, $fn);
        } else {
            csv_edihist_log("edih_835_transaction_html: Did not find trace {$chk} in {$fn}");
            $html_str .= "<p>Did not find trace {$chk} in {$fn}</p>" . PHP_EOL;
            return $html_str;
        }
    } else {
        // entire file
        if (isset($env_ar['ST']) && count($env_ar['ST'])) {
            $trans_ar = array();
            foreach ($env_ar['ST'] as $st) {
                $trans_ar[] = $obj835->edih_x12_slice(array('trace' => $st['trace']));
            }
        } else {
            csv_edihist_log("edih_835_transaction_html: Did not envelopes information for {$fn}");
            $html_str .= "<p>Did not get envelopes information for {$fn}</p>" . PHP_EOL;
            return $html_str;
        }
        if (is_array($trans_ar) && count($trans_ar)) {
            // $trans_ar is a slice, array[i]
            $html_str .= edih_835_payment_html($trans_ar, $cd27x, $cd835, $delims, $fn);
        } else {
            csv_edihist_log("edih_835_transaction_html: Did not get ST envelopes for {$fn}");
            $html_str .= "<p>Did not get ST envelopes for {$fn}</p>" . PHP_EOL;
            return $html_str;
        }
    }
    //
    return $html_str;
}