added support for the scanned_notes encounter form
[openemr.git] / library / Claim.class.php
blob5c53cb52d8e00e096ff6e0f86b8fd2f4abd0de69
1 <?php
2 // Copyright (C) 2007-2008 Rod Roark <rod@sunsetsystems.com>
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License
6 // as published by the Free Software Foundation; either version 2
7 // of the License, or (at your option) any later version.
9 require_once(dirname(__FILE__) . "/classes/Address.class.php");
10 require_once(dirname(__FILE__) . "/classes/InsuranceCompany.class.php");
11 require_once(dirname(__FILE__) . "/sql-ledger.inc");
12 require_once(dirname(__FILE__) . "/invoice_summary.inc.php");
14 // This enforces the X12 Basic Character Set. Page A2.
16 function x12clean($str) {
17 return preg_replace('/[^A-Z0-9!"\\&\'()+,\\-.\\/;?= ]/', '', strtoupper($str));
20 class Claim {
22 var $pid; // patient id
23 var $encounter_id; // encounter id
24 var $procs; // array of procedure rows from billing table
25 var $x12_partner; // row from x12_partners table
26 var $encounter; // row from form_encounter table
27 var $facility; // row from facility table
28 var $billing_facility; // row from facility table
29 var $provider; // row from users table (rendering provider)
30 var $referrer; // row from users table (referring provider)
31 var $insurance_numbers; // row from insurance_numbers table for current payer
32 var $patient_data; // row from patient_data table
33 var $billing_options; // row from form_misc_billing_options table
34 var $invoice; // result from get_invoice_summary()
35 var $payers; // array of arrays, for all payers
36 var $copay; // total of copays from the billing table
38 function loadPayerInfo(&$billrow) {
39 global $sl_err;
40 $encounter_date = substr($this->encounter['date'], 0, 10);
42 // Create the $payers array. This contains data for all insurances
43 // with the current one always at index 0, and the others in payment
44 // order starting at index 1.
46 $this->payers = array();
47 $this->payers[0] = array();
48 $query = "SELECT * FROM insurance_data WHERE " .
49 "pid = '{$this->pid}' AND provider != '' AND " .
50 "date <= '$encounter_date' " .
51 "ORDER BY type ASC, date DESC";
52 $dres = sqlStatement($query);
53 $prevtype = '';
54 while ($drow = sqlFetchArray($dres)) {
55 if (strcmp($prevtype, $drow['type']) == 0) continue;
56 $prevtype = $drow['type'];
57 $ins = count($this->payers);
58 if ($drow['provider'] == $billrow['payer_id'] && empty($this->payers[0]['data'])) $ins = 0;
59 $crow = sqlQuery("SELECT * FROM insurance_companies WHERE " .
60 "id = '" . $drow['provider'] . "'");
61 $orow = new InsuranceCompany($drow['provider']);
62 $this->payers[$ins] = array();
63 $this->payers[$ins]['data'] = $drow;
64 $this->payers[$ins]['company'] = $crow;
65 $this->payers[$ins]['object'] = $orow;
68 // This kludge hands most cases of a rare ambiguous situation, where
69 // the primary insurance company is the same as the secondary. It seems
70 // nobody planned for that!
72 for ($i = 1; $i < count($this->payers); ++$i) {
73 if ($billrow['process_date'] &&
74 $this->payers[0]['data']['provider'] == $this->payers[$i]['data']['provider'])
76 $tmp = $this->payers[0];
77 $this->payers[0] = $this->payers[$i];
78 $this->payers[$i] = $tmp;
82 $this->using_modifiers = true;
84 // Get payment and adjustment details if there are any previous payers.
86 $this->invoice = array();
87 if ($this->payerSequence() != 'P') {
88 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
89 $this->invoice = ar_get_invoice_summary($this->pid, $this->encounter_id, true);
91 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
92 SLConnect();
93 $arres = SLQuery("select id from ar where invnumber = " .
94 "'{$this->pid}.{$this->encounter_id}'");
95 if ($sl_err) die($sl_err);
96 $arrow = SLGetRow($arres, 0);
97 if ($arrow) {
98 $this->invoice = get_invoice_summary($arrow['id'], true);
100 SLClose();
102 // Secondary claims might not have modifiers in SQL-Ledger data.
103 // In that case, note that we should not try to match on them.
104 $this->using_modifiers = false;
105 foreach ($this->invoice as $key => $trash) {
106 if (strpos($key, ':')) $this->using_modifiers = true;
111 // Constructor. Loads relevant database information.
113 function Claim($pid, $encounter_id) {
114 $this->pid = $pid;
115 $this->encounter_id = $encounter_id;
116 $this->procs = array();
117 $this->copay = 0;
119 // We need the encounter date before we can identify the payers.
120 $sql = "SELECT * FROM form_encounter WHERE " .
121 "pid = '{$this->pid}' AND " .
122 "encounter = '{$this->encounter_id}'";
123 $this->encounter = sqlQuery($sql);
125 // Sort by procedure timestamp in order to get some consistency. In particular
126 // we determine the provider from the first procedure in this array.
127 $sql = "SELECT * FROM billing WHERE " .
128 "encounter = '{$this->encounter_id}' AND pid = '{$this->pid}' AND " .
129 "(code_type = 'CPT4' OR code_type = 'HCPCS' OR code_type = 'COPAY') AND " .
130 "activity = '1' ORDER BY date, id";
131 $res = sqlStatement($sql);
132 while ($row = sqlFetchArray($res)) {
133 if ($row['code_type'] == 'COPAY') {
134 $this->copay -= $row['fee'];
135 continue;
137 if (!$row['units']) $row['units'] = 1;
138 // Load prior payer data at the first opportunity in order to get
139 // the using_modifiers flag that is referenced below.
140 if (empty($this->procs)) $this->loadPayerInfo($row);
141 // Consolidate duplicate procedures.
142 foreach ($this->procs as $key => $trash) {
143 if (strcmp($this->procs[$key]['code'],$row['code']) == 0 &&
144 (strcmp($this->procs[$key]['modifier'],$row['modifier']) == 0 ||
145 !$this->using_modifiers))
147 $this->procs[$key]['units'] += $row['units'];
148 $this->procs[$key]['fee'] += $row['fee'];
149 continue 2; // skip to next table row
152 $this->procs[] = $row;
155 $sql = "SELECT * FROM x12_partners WHERE " .
156 "id = '" . $this->procs[0]['x12_partner_id'] . "'";
157 $this->x12_partner = sqlQuery($sql);
159 $sql = "SELECT * FROM facility WHERE " .
160 "id = '" . addslashes($this->encounter['facility_id']) . "' " .
161 "LIMIT 1";
162 $this->facility = sqlQuery($sql);
164 $provider_id = $this->procs[0]['provider_id'];
165 $sql = "SELECT * FROM users WHERE id = '$provider_id'";
166 $this->provider = sqlQuery($sql);
168 $sql = "SELECT * FROM facility " .
169 "ORDER BY billing_location DESC, id ASC LIMIT 1";
170 $this->billing_facility = sqlQuery($sql);
172 $sql = "SELECT * FROM insurance_numbers WHERE " .
173 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
174 "' OR insurance_company_id is NULL) AND " .
175 "provider_id = '" . $this->provider['id'] .
176 "' order by insurance_company_id DESC LIMIT 1";
177 $this->insurance_numbers = sqlQuery($sql);
179 $sql = "SELECT * FROM patient_data WHERE " .
180 "pid = '{$this->pid}' " .
181 "ORDER BY id LIMIT 1";
182 $this->patient_data = sqlQuery($sql);
184 $sql = "SELECT fpa.* FROM forms JOIN form_misc_billing_options AS fpa " .
185 "ON fpa.id = forms.form_id WHERE " .
186 "forms.encounter = '{$this->encounter_id}' AND " .
187 "forms.pid = '{$this->pid}' AND " .
188 "forms.formdir = 'misc_billing_options' " .
189 "ORDER BY forms.date";
190 $this->billing_options = sqlQuery($sql);
192 $referrer_id = (empty($GLOBALS['MedicareReferrerIsRenderer']) ||
193 $this->insurance_numbers['provider_number_type'] != '1C') ?
194 $this->patient_data['providerID'] : $provider_id;
195 $sql = "SELECT * FROM users WHERE id = '$referrer_id'";
196 $this->referrer = sqlQuery($sql);
197 if (!$this->referrer) $this->referrer = array();
199 } // end constructor
201 // Return an array of adjustments from the designated prior payer for the
202 // designated procedure key (might be procedure:modifier), or for the claim
203 // level. For each adjustment give date, group code, reason code, amount.
204 // Note this will include "patient responsibility" adjustments which are
205 // not adjustments to OUR invoice, but they reduce the amount that the
206 // insurance company pays.
208 function payerAdjustments($ins, $code='Claim') {
209 $aadj = array();
211 // If we have no modifiers stored in SQL-Ledger for this claim,
212 // then we cannot use a modifier passed in with the key.
213 $tmp = strpos($code, ':');
214 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
216 // For payments, source always starts with "Ins" or "Pt".
217 // Nonzero adjustment reason examples:
218 // Ins1 adjust code 42 (Charges exceed ... (obsolete))
219 // Ins1 adjust code 45 (Charges exceed your contracted/ legislated fee arrangement)
220 // Ins1 adjust code 97 (Payment is included in the allowance for another service/procedure)
221 // Ins1 adjust code A2 (Contractual adjustment)
222 // Ins adjust Ins1
223 // adjust code 45
224 // Zero adjustment reason examples:
225 // Co-pay: 25.00
226 // Coinsurance: 11.46 (code 2) Note: fix remits to identify insurance
227 // To deductible: 0.22 (code 1) Note: fix remits to identify insurance
228 // To copay Ins1 (manual entry)
229 // To ded'ble Ins1 (manual entry)
231 if (!empty($this->invoice[$code])) {
232 $date = '';
233 $deductible = 0;
234 $coinsurance = 0;
235 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
236 $insnumber = substr($inslabel, 3);
238 // Compute this procedure's patient responsibility amount as of this
239 // prior payer, which is the original charge minus all insurance
240 // payments and "hard" adjustments up to this payer.
241 $ptresp = $this->invoice[$code]['chg'] + $this->invoice[$code]['adj'];
242 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
243 if (preg_match("/^Ins(\d)/i", $value['src'], $tmp)) {
244 if ($tmp[1] <= $insnumber) $ptresp -= $value['pmt'];
246 else if (trim(substr($key, 0, 10))) { // not an adjustment if no date
247 if (!preg_match("/Ins(\d)/i", $value['rsn'], $tmp) || $tmp[1] <= $insnumber)
248 $ptresp += $value['chg']; // adjustments are negative charges
251 if ($ptresp < 0) $ptresp = 0; // we may be insane but try to hide it
253 // Main loop, to extract adjustments for this payer and procedure.
254 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
255 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
256 if ($tmp) $date = $tmp;
257 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
258 $rsn = $value['rsn'];
259 $chg = 0 - $value['chg']; // adjustments are negative charges
261 $gcode = 'CO'; // default group code = contractual obligation
262 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
264 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
265 // From manual post. Take the defaults.
267 else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
268 $coinsurance = $ptresp; // from manual post
269 continue;
271 else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
272 $deductible = $ptresp; // from manual post
273 continue;
275 else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
276 $coinsurance = $tmp[1]; // from 835 as of 6/2007
277 continue;
279 else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
280 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
281 continue;
283 else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
284 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
285 continue;
287 else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
288 continue; // from 835 as of 6/2007
290 else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
291 $rcode = $tmp[1]; // from 835
293 else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
294 // Take the defaults.
296 else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
297 continue; // it's for some other payer
299 else if ($insnumber == '1') {
300 if (preg_match("/\$\s*adjust code (\S+)/i", $rsn, $tmp)) {
301 $rcode = $tmp[1]; // from 835
303 else if ($chg) {
304 // Other adjustments default to Ins1.
306 else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
307 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
308 $coinsurance = 0 + $tmp[1]; // from 835 before 6/2007
309 continue;
311 else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
312 $deductible = 0 + $tmp[1]; // from 835 before 6/2007
313 continue;
315 else {
316 continue; // there is no adjustment amount
319 else {
320 continue; // it's for primary and that's not us
323 if ($rcode == '42') $rcode= '45'; // reason 42 is obsolete
324 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
326 } // end if
327 } // end foreach
329 // If we really messed it up, at least avoid negative numbers.
330 if ($coinsurance > $ptresp) $coinsurance = $ptresp;
331 if ($deductible > $ptresp) $deductible = $ptresp;
333 // Find out if this payer paid anything at all on this claim. This will
334 // help us allocate any unknown patient responsibility amounts.
335 $thispaidanything = 0;
336 foreach($this->invoice as $codekey => $codeval) {
337 foreach ($codeval['dtl'] as $key => $value) {
338 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
339 $thispaidanything += $value['pmt'];
344 // Allocate any unknown patient responsibility by guessing if the
345 // deductible has been satisfied.
346 if ($thispaidanything)
347 $coinsurance = $ptresp - $deductible;
348 else
349 $deductible = $ptresp - $coinsurance;
351 if ($date && $deductible != 0)
352 $aadj[] = array($date, 'PR', '1', sprintf('%.2f', $deductible));
353 if ($date && $coinsurance != 0)
354 $aadj[] = array($date, 'PR', '2', sprintf('%.2f', $coinsurance));
356 } // end if
358 return $aadj;
361 // Return date, total payments and total "hard" adjustments from the given
362 // prior payer. If $code is specified then only that procedure key is
363 // selected, otherwise it's for the whole claim.
365 function payerTotals($ins, $code='') {
366 // If we have no modifiers stored in SQL-Ledger for this claim,
367 // then we cannot use a modifier passed in with the key.
368 $tmp = strpos($code, ':');
369 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
371 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
372 $paytotal = 0;
373 $adjtotal = 0;
374 $date = '';
375 foreach($this->invoice as $codekey => $codeval) {
376 if ($code && strcmp($codekey,$code) != 0) continue;
377 foreach ($codeval['dtl'] as $key => $value) {
378 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
379 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
380 $paytotal += $value['pmt'];
383 $aarr = $this->payerAdjustments($ins, $codekey);
384 foreach ($aarr as $a) {
385 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
386 if (!$date) $date = $a[0];
389 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
392 // Return the amount already paid by the patient.
394 function patientPaidAmount() {
395 // For primary claims $this->invoice is not loaded, so get the co-pay
396 // from the billing table instead.
397 if (empty($this->invoice)) return $this->copay;
399 $amount = 0;
400 foreach($this->invoice as $codekey => $codeval) {
401 foreach ($codeval['dtl'] as $key => $value) {
402 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
403 $amount += $value['pmt'];
407 return sprintf('%.2f', $amount);
410 // Return invoice total, including adjustments but not payments.
412 function invoiceTotal() {
413 $amount = 0;
414 foreach($this->invoice as $codekey => $codeval) {
415 $amount += $codeval['chg'];
417 return sprintf('%.2f', $amount);
420 // Number of procedures in this claim.
421 function procCount() {
422 return count($this->procs);
425 // Number of payers for this claim. Ranges from 1 to 3.
426 function payerCount() {
427 return count($this->payers);
430 function x12gsversionstring() {
431 return x12clean(trim($this->x12_partner['x12_version']));
434 function x12gssenderid() {
435 $tmp = $this->x12_partner['x12_sender_id'];
436 while (strlen($tmp) < 15) $tmp .= " ";
437 return $tmp;
440 function x12gsreceiverid() {
441 $tmp = $this->x12_partner['x12_receiver_id'];
442 while (strlen($tmp) < 15) $tmp .= " ";
443 return $tmp;
446 function cliaCode() {
447 return x12clean(trim($this->facility['domain_identifier']));
450 function billingFacilityName() {
451 return x12clean(trim($this->billing_facility['name']));
454 function billingFacilityStreet() {
455 return x12clean(trim($this->billing_facility['street']));
458 function billingFacilityCity() {
459 return x12clean(trim($this->billing_facility['city']));
462 function billingFacilityState() {
463 return x12clean(trim($this->billing_facility['state']));
466 function billingFacilityZip() {
467 return x12clean(trim($this->billing_facility['postal_code']));
470 function billingFacilityETIN() {
471 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
474 function billingFacilityNPI() {
475 return x12clean(trim($this->billing_facility['facility_npi']));
478 # The billing facility and the patient must both accept for this to return true.
479 function billingFacilityAssignment($ins=0) {
480 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
481 if (strcmp($tmp,'FALSE') == 0) return '0';
482 return !empty($this->billing_facility['accepts_assignment']);
485 function billingContactName() {
486 return x12clean(trim($this->billing_facility['attn']));
489 function billingContactPhone() {
490 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
491 $this->billing_facility['phone'], $tmp))
493 return $tmp[1] . $tmp[2] . $tmp[3];
495 return '';
498 function facilityName() {
499 return x12clean(trim($this->facility['name']));
502 function facilityStreet() {
503 return x12clean(trim($this->facility['street']));
506 function facilityCity() {
507 return x12clean(trim($this->facility['city']));
510 function facilityState() {
511 return x12clean(trim($this->facility['state']));
514 function facilityZip() {
515 return x12clean(trim($this->facility['postal_code']));
518 function facilityETIN() {
519 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
522 function facilityNPI() {
523 return x12clean(trim($this->facility['facility_npi']));
526 function facilityPOS() {
527 return x12clean(trim($this->facility['pos_code']));
530 function clearingHouseName() {
531 return x12clean(trim($this->x12_partner['name']));
534 function clearingHouseETIN() {
535 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
538 function providerNumberType() {
539 return $this->insurance_numbers['provider_number_type'];
542 function providerNumber() {
543 return x12clean(trim(str_replace('-', '', $this->insurance_numbers['provider_number'])));
546 function providerGroupNumber() {
547 return x12clean(trim(str_replace('-', '', $this->insurance_numbers['group_number'])));
550 // Returns 'P', 'S' or 'T'.
552 function payerSequence($ins=0) {
553 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
556 // Returns the HIPAA code of the patient-to-subscriber relationship.
558 function insuredRelationship($ins=0) {
559 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
560 if (strcmp($tmp,'self' ) == 0) return '18';
561 if (strcmp($tmp,'spouse') == 0) return '01';
562 if (strcmp($tmp,'child' ) == 0) return '19';
563 if (strcmp($tmp,'other' ) == 0) return 'G8';
564 return $tmp; // should not happen
567 function insuredTypeCode($ins=0) {
568 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
569 return '12'; // medicare secondary working aged beneficiary or
570 // spouse with employer group health plan
571 return '';
574 // Is the patient also the subscriber?
576 function isSelfOfInsured($ins=0) {
577 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
578 return (strcmp($tmp,'self') == 0);
581 function planName($ins=0) {
582 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
585 function policyNumber($ins=0) { // "ID"
586 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
589 function groupNumber($ins=0) {
590 return x12clean(trim($this->payers[$ins]['data']['group_number']));
593 function groupName($ins=0) {
594 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
597 // Claim types are:
598 // 16 Other HCFA
599 // MB Medicare Part B
600 // MC Medicaid
601 // CH ChampUSVA
602 // CH ChampUS
603 // BL Blue Cross Blue Shield
604 // 16 FECA
605 // 09 Self Pay
606 // 10 Central Certification
607 // 11 Other Non-Federal Programs
608 // 12 Preferred Provider Organization (PPO)
609 // 13 Point of Service (POS)
610 // 14 Exclusive Provider Organization (EPO)
611 // 15 Indemnity Insurance
612 // 16 Health Maintenance Organization (HMO) Medicare Risk
613 // AM Automobile Medical
614 // CI Commercial Insurance Co.
615 // DS Disability
616 // HM Health Maintenance Organization
617 // LI Liability
618 // LM Liability Medical
619 // OF Other Federal Program
620 // TV Title V
621 // VA Veterans Administration Plan
622 // WC Workers Compensation Health Plan
623 // ZZ Mutually Defined
625 function claimType($ins=0) {
626 if (empty($this->payers[$ins]['object'])) return '';
627 return $this->payers[$ins]['object']->get_freeb_claim_type();
630 function insuredLastName($ins=0) {
631 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
634 function insuredFirstName($ins=0) {
635 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
638 function insuredMiddleName($ins=0) {
639 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
642 function insuredStreet($ins=0) {
643 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
646 function insuredCity($ins=0) {
647 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
650 function insuredState($ins=0) {
651 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
654 function insuredZip($ins=0) {
655 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
658 function insuredPhone($ins=0) {
659 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
660 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
661 return $tmp[1] . $tmp[2] . $tmp[3];
662 return '';
665 function insuredDOB($ins=0) {
666 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
669 function insuredSex($ins=0) {
670 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
673 function payerName($ins=0) {
674 return x12clean(trim($this->payers[$ins]['company']['name']));
677 function payerAttn($ins=0) {
678 return x12clean(trim($this->payers[$ins]['company']['attn']));
681 function payerStreet($ins=0) {
682 if (empty($this->payers[$ins]['object'])) return '';
683 $tmp = $this->payers[$ins]['object'];
684 $tmp = $tmp->get_address();
685 return x12clean(trim($tmp->get_line1()));
688 function payerCity($ins=0) {
689 if (empty($this->payers[$ins]['object'])) return '';
690 $tmp = $this->payers[$ins]['object'];
691 $tmp = $tmp->get_address();
692 return x12clean(trim($tmp->get_city()));
695 function payerState($ins=0) {
696 if (empty($this->payers[$ins]['object'])) return '';
697 $tmp = $this->payers[$ins]['object'];
698 $tmp = $tmp->get_address();
699 return x12clean(trim($tmp->get_state()));
702 function payerZip($ins=0) {
703 if (empty($this->payers[$ins]['object'])) return '';
704 $tmp = $this->payers[$ins]['object'];
705 $tmp = $tmp->get_address();
706 return x12clean(trim($tmp->get_zip()));
709 function payerID($ins=0) {
710 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
713 function patientLastName() {
714 return x12clean(trim($this->patient_data['lname']));
717 function patientFirstName() {
718 return x12clean(trim($this->patient_data['fname']));
721 function patientMiddleName() {
722 return x12clean(trim($this->patient_data['mname']));
725 function patientStreet() {
726 return x12clean(trim($this->patient_data['street']));
729 function patientCity() {
730 return x12clean(trim($this->patient_data['city']));
733 function patientState() {
734 return x12clean(trim($this->patient_data['state']));
737 function patientZip() {
738 return x12clean(trim($this->patient_data['postal_code']));
741 function patientPhone() {
742 $ptphone = $this->patient_data['phone_home'];
743 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
744 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
745 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
746 return $tmp[1] . $tmp[2] . $tmp[3];
747 return '';
750 function patientDOB() {
751 return str_replace('-', '', $this->patient_data['DOB']);
754 function patientSex() {
755 return strtoupper(substr($this->patient_data['sex'], 0, 1));
758 // Patient Marital Status: M = Married, S = Single, or something else.
759 function patientStatus() {
760 return strtoupper(substr($this->patient_data['status'], 0, 1));
763 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
764 // indicate employed.
765 function patientOccupation() {
766 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
769 function cptCode($prockey) {
770 return x12clean(trim($this->procs[$prockey]['code']));
773 function cptModifier($prockey) {
774 return x12clean(trim($this->procs[$prockey]['modifier']));
777 // Returns the procedure code, followed by ":modifier" if there is one.
778 function cptKey($prockey) {
779 $tmp = $this->cptModifier($prockey);
780 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
783 function cptCharges($prockey) {
784 return x12clean(trim($this->procs[$prockey]['fee']));
787 function cptUnits($prockey) {
788 if (empty($this->procs[$prockey]['units'])) return '1';
789 return x12clean(trim($this->procs[$prockey]['units']));
792 // NDC drug ID.
793 function cptNDCID($prockey) {
794 $ndcinfo = $this->procs[$prockey]['ndc_info'];
795 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
796 $ndc = $tmp[1];
797 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
798 return sprintf('%05d-%04d-%02d', $tmp[1], $tmp[2], $tmp[3]);
800 return x12clean($ndc); // format is bad but return it anyway
802 return '';
805 // NDC drug unit of measure code.
806 function cptNDCUOM($prockey) {
807 $ndcinfo = $this->procs[$prockey]['ndc_info'];
808 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
809 return x12clean($tmp[2]);
810 return '';
813 // NDC drug number of units.
814 function cptNDCQuantity($prockey) {
815 $ndcinfo = $this->procs[$prockey]['ndc_info'];
816 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
817 return x12clean(ltrim($tmp[3], '0'));
819 return '';
822 function onsetDate() {
823 return str_replace('-', '', substr($this->encounter['onset_date'], 0, 10));
826 function serviceDate() {
827 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
830 function priorAuth() {
831 return x12clean(trim($this->billing_options['prior_auth_number']));
834 function isRelatedEmployment() {
835 return !empty($this->billing_options['employment_related']);
838 function isRelatedAuto() {
839 return !empty($this->billing_options['auto_accident']);
842 function isRelatedOther() {
843 return !empty($this->billing_options['other_accident']);
846 function autoAccidentState() {
847 return x12clean(trim($this->billing_options['accident_state']));
850 function isUnableToWork() {
851 return !empty($this->billing_options['is_unable_to_work']);
854 function offWorkFrom() {
855 return str_replace('-', '', substr($this->billing_options['off_work_from'], 0, 10));
858 function offWorkTo() {
859 return str_replace('-', '', substr($this->billing_options['off_work_to'], 0, 10));
862 function isHospitalized() {
863 return !empty($this->billing_options['is_hospitalized']);
866 function hospitalizedFrom() {
867 return str_replace('-', '', substr($this->billing_options['hospitalization_date_from'], 0, 10));
870 function hospitalizedTo() {
871 return str_replace('-', '', substr($this->billing_options['hospitalization_date_to'], 0, 10));
874 function isOutsideLab() {
875 return !empty($this->billing_options['outside_lab']);
878 function outsideLabAmount() {
879 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
882 function medicaidResubmissionCode() {
883 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
886 function medicaidOriginalReference() {
887 return x12clean(trim($this->billing_options['medicaid_original_reference']));
890 function frequencyTypeCode() {
891 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
894 function additionalNotes() {
895 return x12clean(trim($this->billing_options['comments']));
898 // Returns an array of unique diagnoses. Periods are stripped.
899 function diagArray() {
900 $da = array();
901 foreach ($this->procs as $row) {
902 $atmp = explode(':', $row['justify']);
903 foreach ($atmp as $tmp) {
904 if (!empty($tmp)) {
905 $diag = str_replace('.', '', $tmp);
906 $da[$diag] = $diag;
910 return $da;
913 // Compute one 1-relative index in diagArray for the given procedure.
914 // This function is obsolete, use diagIndexArray() instead.
915 function diagIndex($prockey) {
916 $da = $this->diagArray();
917 $tmp = explode(':', $this->procs[$prockey]['justify']);
918 if (empty($tmp)) return '';
919 $diag = str_replace('.', '', $tmp[0]);
920 $i = 0;
921 foreach ($da as $value) {
922 ++$i;
923 if (strcmp($value,$diag) == 0) return $i;
925 return '';
928 // Compute array of 1-relative diagArray indices for the given procedure.
929 function diagIndexArray($prockey) {
930 $dia = array();
931 $da = $this->diagArray();
932 $atmp = explode(':', $this->procs[$prockey]['justify']);
933 foreach ($atmp as $tmp) {
934 if (!empty($tmp)) {
935 $diag = str_replace('.', '', $tmp);
936 $i = 0;
937 foreach ($da as $value) {
938 ++$i;
939 if (strcmp($value,$diag) == 0) $dia[] = $i;
943 return $dia;
946 function providerLastName() {
947 return x12clean(trim($this->provider['lname']));
950 function providerFirstName() {
951 return x12clean(trim($this->provider['fname']));
954 function providerMiddleName() {
955 return x12clean(trim($this->provider['mname']));
958 function providerNPI() {
959 return x12clean(trim($this->provider['npi']));
962 function providerUPIN() {
963 return x12clean(trim($this->provider['upin']));
966 function providerSSN() {
967 return x12clean(trim(str_replace('-', '', $this->provider['federaltaxid'])));
970 function providerTaxonomy() {
971 if (empty($this->provider['taxonomy'])) return '207Q00000X';
972 return x12clean(trim($this->provider['taxonomy']));
975 function referrerLastName() {
976 return x12clean(trim($this->referrer['lname']));
979 function referrerFirstName() {
980 return x12clean(trim($this->referrer['fname']));
983 function referrerMiddleName() {
984 return x12clean(trim($this->referrer['mname']));
987 function referrerNPI() {
988 return x12clean(trim($this->referrer['npi']));
991 function referrerUPIN() {
992 return x12clean(trim($this->referrer['upin']));
995 function referrerSSN() {
996 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
999 function referrerTaxonomy() {
1000 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1001 return x12clean(trim($this->referrer['taxonomy']));