<?php

  session_start();
  
  include ('include_fns.php');

  function ibdateformat($date)
  {
    $year  = substr($date, 0, 4);
    $month = substr($date, 4, 2);
    $day   = substr($date, 6, 2);
    
    switch($month)
    {
     case '01': $newmonth = 'JAN';break;
     case '02': $newmonth = 'FEB';break;
     case '03': $newmonth = 'MAR';break;
     case '04': $newmonth = 'APR';break;
     case '05': $newmonth = 'MAY';break;
     case '06': $newmonth = 'JUN';break;
     case '07': $newmonth = 'JUL';break;
     case '08': $newmonth = 'AUG';break;
     case '09': $newmonth = 'SEP';break;
     case '10': $newmonth = 'OCT';break;
     case '11': $newmonth = 'NOV';break;
     case '12': $newmonth = 'DEC';break;
    } 

    
    return $day.'-'.$newmonth.'-'.$year;  
  }

  function GetDescription($code)
  {

    switch($code)
    {
     case '001': $desc = 'PAID IN FULL';break;
     case '002': $desc = 'PART PAID';break;
     case '003': $desc = 'PEP TARIFF EXISTS FOR NON PEP PROVIDER';break;
     case '004': $desc = 'TX DATE AFTER MEMBER RESIGN DATE';break;
     case '005': $desc = 'TX DATE BETWEEN SUSPENDED AND RESUMED DATES';break;
     case '006': $desc = 'MANUAL INTERVENTION REQUIRED';break;
     case '007': $desc = 'BONITAS FAMILY LIMIT EXCEEDED';break;
     case '008': $desc = 'INVALID TARIFF';break;
     case '009': $desc = 'TARIFF 93800 OR 03PEP FOR BONITAS 01 05 07 08';break;
     case '010': $desc = 'TARIFF 02PEP FOR BONITAS 01 05 07 08';break;
     case '011': $desc = 'TARIFF 01PEP OR 03PEP';break;
     case '012': $desc = 'SV SPHERE OR CYL REQUIRED';break;
     case '013': $desc = 'MULTI OR BI FOCAL FOR PATIENT UNDER 38';break;
     case '014': $desc = 'RIGHT OR LEFT ADD REQUIRED';break;
     case '015': $desc = 'RIGHT ADD LESS THAN 1';break;
     case '016': $desc = 'LEFT ADD LESS THAN 1';break;
     case '017': $desc = 'STALE CLAIM';break;
     case '018': $desc = 'TARIFF NOT VALID';break;     
     case '019': $desc = 'CONSULTATION ALREADY CAPTURED';break;
     case '020': $desc = 'CONTACT BUT FRAME PREV CAPTURED';break;
     case '021': $desc = 'FRAME BUT CONTACT PREV CAPTURED';break;
     case '022': $desc = 'TX DATE IS AFTER CURRENT DATE';break;
     case '023': $desc = 'MAX QTY FOR CONSULTS/FRAMES 1 AND FOR LENSES 2';break;
     case '024': $desc = 'MAXIMUM QTY EXCEEDED FOR BENEFIT';break;

    } 
    
    return $desc;
  }

  function WriteLogFile($fp, $claimslog)
  {
    fwrite($fp, $claimslog);
    fclose($fp);
  }


  function CaptureManaulIntervention($filecontents, $hbswitchid, $account, $medicalaid, $administrator,
                                     $initials,$firstnames,$surname,$depno, $em_account, $provider)  /* write to editx table */
  {
      $Data = explode("\n", $filecontents); //parse the rows
    
      $patient = '';
    
      $PATFound  = 'F';
      $PROFound  = 'F';
      $CLMFound  = 'F';
      $TermFound = 'F';

      $claimitems  = 0;
      $updateseqno = 0;
      $batchno     = 0;
      
      $retupdateseqno = 0;
      $retclaimno     = 0;
      $totalpaid      = 0;
      $itemresponses  = '';


      $claimheadertotal = 0;
      $claimlinetotal   = 0;
      $headeritemstotal = 0;
      $lineitemstotal = 0;

      foreach($Data as $Row) 
      {  
        $iberror = '';

        $Row = explode("|", $Row); //parse the items in rows
     
        if ($Row[0] == 'CLM')
        {
          $claimitems   = $Row[1];
          $hbswitchid   = $Row[3];
        }

        if ($Row[0] == 'ITM')
        {
          $itemno    = $Row[1];
          $txdate    = ibdateformat($Row[2]);
          $tariff    = $Row[3];
          $narrative = $Row[4];
          $qty       = $Row[5];
          $claimed   = $Row[6]; 
          $discount  = $Row[7]; 
          $authno    = $Row[8];
          $RCyl      = $Row[9];
          $RSphere   = $Row[10];
          $RAdd      = $Row[11];
          $LCyl      = $Row[12];
          $LSphere   = $Row[13];
          $LAdd      = $Row[14];
          $diag      = $Row[15];
          $em_docno  = $Row[16]; 
          $em_txno   = $Row[17]; 
            
         
          if ($itemno == $claimitems)
          {
           $linestatus = 'L';
           $updateseqno = $retupdateseqno;
          }  
          else
          if ($itemno == 1)
          {
           $linestatus  = 'F';
           $updateseqno = 0;  
          }  
          else
          {
           $linestatus  = '';
           $updateseqno = $retupdateseqno;
          }; 

          $narrative = substr($narrative, 0, 40);
  
          $combinedscript = 'R:'.$RSphere.' '.$RCyl.' '.$RAdd.' L:'.$LSphere.' '.$LCyl.' '.$LAdd;

          $query = "SELECT RET_UPDATESEQNO, RET_BATCHNO FROM SP_EDITX('I','$linestatus','$updateseqno', NULL, -1,  '$medicalaid',
                    $itemno, '$account', '$surname', '$initials', '$firstnames', '$provider', '$em_account', '$txdate', '$qty', '$claimed',
                    0, '$narrative', '$tariff',  $em_docno, NULL, $em_txno, '$authno', 'F',  '$diag', '$provider', NULL, NULL, '$combinedscript', null,
                    'sysdba', 'F', NULL, NULL, '$account', '$provider', NULL,'$hbswitchid')";

          echo $query; 

          $claimslog .= 'MI QUERY:'.$query."\r\n";

          if($conn = db_connect())
          {  
            $result = ibase_query($conn, $query); 

            if (ibase_errmsg()) 
            {
              $iberror = ibase_errmsg();
              $claimslog .= 'CLA|12|Could not post manual intervention line:'. $itemno.' ERROR:'.$iberror.'|0|0|E|'.$hbswitchid."\r\n";  
              WriteLogFile($fp, $claimslog);  

              return 'CLA|12|Could not post manual intervention line:'. $itemno.' ERROR:'.$iberror.'|0|0|E|'.$hbswitchid;
            }
            else
            if (!$result) 
            {
              $claimslog .= 'CLA|12|Could not post manual intervention line:'. $itemno.'|0|0|E|'.$hbswitchid."\r\n";  
              WriteLogFile($fp, $claimslog);  
              return 'CLA|12|Could not post manual intervention line:'. $itemno.'|0|0|E|'.$hbswitchid;
            }
            else
            {
              $row = ibase_fetch_row ($result);
            
              $retupdateseqno = $row[0];
              $retbatchno     = $row[1];
              
            }
          }     
        } 
      }

    return $claimslog;
  }





  function CaptureClaim($username, $password, $practiceno, $filecontents)
  {
     $ipaddr = $_SERVER['REMOTE_ADDR'];

     $fp = fopen($_SERVER['DOCUMENT_ROOT']."/e2/claimslog.txt", "a");
     $claimslog = '---------------------------------------------------------------------------'."\r\n";
     $claimslog .= 'NEW CLAIM'.date("dmY H:i:s").'|'.$username.'|'.$password.'|'.$ipaddr."\r\n";

    $login = login($username, $password, 0);

    if (!$login)
    {
      $claimslog .= 'INCORRECT LOGIN'."\r\n";
      
      WriteLogFile($fp, $claimslog);

      return "999|Incorrect Login Details";
    }
    else
    {  

      $Data = explode("\n", $filecontents); //parse the rows
    
      $patient = '';
      $provider = '';
    
      $PATFound  = 'F';
      $PROFound  = 'F';
      $CLMFound  = 'F';
      $TermFound = 'F';

      $claimitems  = 0;
      $updateseqno = 0;
      $batchno     = 0;
      
      $retupdateseqno = 0;
      $retclaimno     = 0;
      $totalpaid      = 0;
      $hbswitchid     = '';
      $itemresponses  = '';


      $claimheadertotal = 0;
      $claimlinetotal   = 0;
      $headeritemstotal = 0;
      $lineitemstotal	= 0;


      // first obtain the hbswitchid, needs to go to end of every response
      foreach($Data as $Row) 
      {  
        $Row = explode("|", $Row); //parse the items in rows
 
        if ($Row[0] == 'CLM')
        {  
            $hbswitchid   = $Row[3];
            $claimheadertotal = $Row[2];
            $headeritemstotal = $Row[1];
        }  
        else
	      if ($Row[0] == 'ITM')
        {
          $claimlinetotal = $claimlinetotal + $Row[6];
          $lineitemstotal = $lineitemstotal + 1;

        }
	      else
        if ($Row[0] == '@@@')
        {
          $TermFound = 'T'; 
                  }    
      }    
      
      if ($hbswitchid == '')
      { 
       $claimslog .= 'CLA|14|Healthbridge Switch ID not populated|0|0|E|99999'."\r\n"; 
       WriteLogFile($fp, $claimslog);
       return 'CLA|14|Healthbridge Switch ID not populated|0|0|E|99999'; 
      }
      else
      if ($TermFound == 'F')
      {
       $claimslog .= 'CLA|15|Claim Terminator Not Found|0|0|E|'.$hbswitchid."\r\n";  
       WriteLogFile($fp, $claimslog);
       return 'CLA|15|Claim Terminator Not Found|0|0|E|'.$hbswitchid;
      }
  /*    else	
      if ($claimheadertotal <> $claimlinetotal)
      {
       $claimslog .= 'CLA|99|CLAIM HEADER TOTAL ITEM TOTAL MISMATCH|0|0|E|'.$hbswitchid.'HEAD'.$claimheadertotal.'ITEM'.$claimlinetotal."\r\n";  
       WriteLogFile($fp, $claimslog);
       return 'CLA|99|CLAIM HEADER TOTAL ITEM TOTAL MISMATCH|0|0|E|'.$hbswitchid;
      }
      else
      if ($headeritemstotal <> $lineitemstotal)
      {
       $claimslog .= 'CLA|99|CLAIM HEADER LINES ITEM LINES MISMATCH|0|0|E|'.$hbswitchid.'HEAD'.$headeritemstotal.'ITEM'.$lineitemstotal."\r\n";  
       WriteLogFile($fp, $claimslog);
       return 'CLA|99|CLAIM HEADER LINES ITEM LINES MISMATCH|0|0|E|'.$hbswitchid;
      }
*/

      foreach($Data as $Row) 
      {  
        $iberror = '';

        $Row = explode("|", $Row); //parse the items in rows
     
        if ($Row[0] == 'PRO')
        {
          $PROFound = 'T'; 
          $provider = $Row[1];

          if ($provider == '') 
          {  
            $claimslog .= 'CLA|1|Provider Practice No. Required|0|0|E|'.$hbswitchid."\r\n";  
            WriteLogFile($fp, $claimslog);
            return 'CLA|1|Provider Practice No. Required|0|0|E|'.$hbswitchid;
          }
          $query = "SELECT PRACNUM, UPPER(DISPUTE), UPPER(CONTRACTED)
                    FROM PROVIDER
                    WHERE PRACNUM = '$provider' ";
         
          $result = ExecuteQuery($query);

          if (ibase_errmsg()) 
          {
            $iberror = ibase_errmsg();
            
            $claimslog .= 'CLA|2|Database Error'.$iberror.'|0|0|E|'.$hbswitchid."\r\n";  
            WriteLogFile($fp, $claimslog);
            
            return 'CLA|2|Database Error'.$iberror.'|0|0|E|'.$hbswitchid;
          }
          else
          if (!$result)
          {
            $claimslog .= 'CLA|2|Provider Not Found|0|0|E|'.$hbswitchid."\r\n";  
            WriteLogFile($fp, $claimslog);
              
            return 'CLA|2|Provider Not Found|0|0|E|'.$hbswitchid;
          }  
          else
          {  
            $dispute    = trim($result[0][1]) ;
            $contracted = trim($result[0][2]) ;

            if (($dispute == 'TRUE'))
            {  
              $claimslog .= 'CLA|16|PROVIDER IN DISPUTE|0|0|E|'.$hbswitchid."\r\n";  
              WriteLogFile($fp, $claimslog);
              return 'CLA|16|PROVIDER IN DISPUTE|0|0|E|'.$hbswitchid;
            }  
            else
              $provider = trim($result[0][0]);
          }
        }          
        else
        if ($Row[0] == 'PAT')
        {
          if ($PROFound == 'F')
          { 
            $claimslog .= 'CLA|3|Provider Line must first be populated before Patient Line|0|0|E|'.$hbswitchid."\r\n";  
            WriteLogFile($fp, $claimslog);  
            return 'CLA|3|Provider Line must first be populated before Patient Line|0|0|E|'.$hbswitchid;
          }

          $PATFound = 'T'; 
         
          $birthday     = ibdateformat($Row[1]);
          $membershipno = $Row[2];
          $depno        = $Row[3];
          $em_account   = $Row[4];
                   
          if ($membershipno == '') 
            return 'CLA|4|Membership No. Required|0|0|E|'.$hbswitchid;
          else
          if ($birthday == '') 
            return 'CLA|5|Birthday Required|0|0|E|'.$hbswitchid;
          else 
          if ($depno == '') 
            return 'CLA|6|Dependant No. Required|0|0|E|'.$hbswitchid;

          $query = "SELECT * FROM SP_VALIDATEPATIENT('$membershipno','$birthday', $depno) ";

          $result = ExecuteQuery($query);

          if (ibase_errmsg()) 
          {
            $iberror = ibase_errmsg();
            return 'CLA|7|Could not retrieve patient ERROR:'.$iberror.'|0|0|E|'.$hbswitchid;
          }
          else
          if ((!$result)||(trim($result[0][0]) == ''))
            return 'CLA|7|Patient Not Found|0|0|E|'.$hbswitchid;
        
          else
	        if (trim($result[0][6]) == 'T')
            return 'CLA|7|Patient Resigned|0|0|E|'.$hbswitchid;
          else
	        if (trim($result[0][7]) == 'T')
            return 'CLA|7|Patient Suspended|0|0|E|'.$hbswitchid;
          else
          {
            $account       = trim($result[0][0]);
	          $medicalaid    = trim($result[0][1]);
   	        $administrator = trim($result[0][2]);
  	        $initials 	   = trim($result[0][3]);
  	        $firstnames    = trim($result[0][4]);
  	        $surname 	     = trim($result[0][5]);
  	        $depno	       = trim($result[0][8]);

          }  
          
        }  
        else
        if ($Row[0] == 'CLM')
        {
          if ($PATFound == 'F')
            return 'CLA|8|Patient Line must first be populated before Claim Header Line|0|0|E|'.$hbswitchid;
          
          $CLMFound = 'T'; 

          $claimitems   = $Row[1];
          $totalclaimed = $Row[2];
          $hbswitchid   = $Row[3];
          $laborderno	  = $Row[4];

          $claimstatus     = 'F'; /* fully paid */
          $paidclaimexists = 'F';

          if ($claimitems == '')
              return 'CLA|9|No. of Claim Lines required|0|0|E|'.$hbswitchid;
        }
        else
        if ($Row[0] == 'ITM')
        {

          if ($CLMFound == 'F')
            return 'CLA|10|Claim Header Line must first be populated before Items Line|0|0|E|'.$hbswitchid;
          
          $itemno    = $Row[1];
          $txdate    = ibdateformat($Row[2]);
          $tariff    = $Row[3];
          $narrative = $Row[4];
          $qty       = $Row[5];
          $claimed   = $Row[6]; 
          $discount  = $Row[7]; 
          $authno    = $Row[8];
          $RCyl      = $Row[9];
          $RSphere   = $Row[10];
          $RAdd      = $Row[11];
          $LCyl      = $Row[12];
          $LSphere   = $Row[13];
          $LAdd      = $Row[14];
          $diag      = $Row[15];
          $em_docno  = $Row[16]; 
          $em_txno   = $Row[17]; 

/* check for issing mandatory field here 
	      
	      CLA|11|Missing Mandatory Item Field: item#|0|0|E|
*/
            
         
          if ($itemno == $claimitems)
          {
           $linestatus = 'L';
           $updateseqno = $retupdateseqno;
          }  
          else
          if ($itemno == 1)
          {
           $linestatus  = 'F';
           $updateseqno = 0;  
          }  
          else
          {
           $linestatus  = '';
           $updateseqno = $retupdateseqno;
          }; 

          $narrative = substr($narrative, 0, 40);
  
          $query = "SELECT RET_UPDATESEQNO, RET_CLAIMNO, RET_REJECT, RET_PAID, RET_REJECTCODE  
                    FROM SP_POSTWEBPATIENTX('I', '$linestatus', '$updateseqno', '$username','$provider', '$account',
          	        '$membershipno', $depno, '$em_account', '$medicalaid', $administrator, '$initials', '$firstnames', '$surname', '$laborderno',
          	        $itemno, '$txdate', '$tariff', '$qty', '$narrative', '$claimed', '$RSphere', '$RCyl', '$RAdd', '$LSphere', '$LCyl', '$LAdd', '$diag')";


          $claimslog .= 'QUERY:'.$query."\r\n";

          if($conn = db_connect())
          {  
            $result = ibase_query($conn, $query); 

            if (ibase_errmsg()) 
            {
              $iberror = ibase_errmsg();
              $claimslog .= 'CLA|12|Could not post invoice line:'. $itemno.' ERROR:'.$iberror.'|0|0|E|'.$hbswitchid."\r\n";  
              WriteLogFile($fp, $claimslog);  

              return 'CLA|12|Could not post invoice line:'. $itemno.' ERROR:'.$iberror.'|0|0|E|'.$hbswitchid;
            }
            else
            if (!$result) 
            {
              $claimslog .= 'CLA|12|Could not post invoice line:'. $itemno.'|0|0|E|'.$hbswitchid."\r\n";  
              WriteLogFile($fp, $claimslog);  
              return 'CLA|12|Could not post invoice line:'. $itemno.'|0|0|E|'.$hbswitchid;
            }
            else
            {
              $row = ibase_fetch_row ($result);
            
              $retupdateseqno = $row[0];
              $retclaimno     = $row[1];
              $retreject      = $row[2];
              $retpaid        = $row[3];
              $retrejectcode  = $row[4];

              if ($retpaid == '')
                 $retpaid = 0;

               $totalpaid = $totalpaid + $retpaid;



               if ($retreject == 'M')  /* if one line is Manual intervention, make whole claim manual intervention */
                  $claimstatus = 'M';
               else 
               if ($retreject == 'F')
               {
                 $paidclaimexists = 'T';

                 if ($claimstatus == 'R') /* if a line was prev rejected and current line is accepted then make claim partially paid */
                    $claimstatus = 'P';
               }
               else 
               if ($retreject == 'R') 
               {
                 if ($paidclaimexists == 'T') /* if a line was prev accepted and curr line is rejected, make claim partially paid */
                  $claimstatus = 'P';  
                 else
                  $claimstatus = 'R';  
               } 
               else 
               if ($retreject == 'P') /* if one line is PART PAID, make whole claim PART PAID */
		            $claimstatus = 'P';  

              $itemdesc = GetDescription($retrejectcode);

              $retpaid = number_format((float)$retpaid, 2, '.', '');
              $itemresponses .= "\r\n".'ITM|'.$itemno.'|'.$tariff.'|'.$claimed.'|'.$retpaid.'|'.$retreject.'|'.$itemdesc.'|'.$retrejectcode;
              $claimno   = $retclaimno;
              
              $claimslog .= 'RESULT:'.$retupdateseqno.'|'.$retclaimno.'|'.$retreject.'|'.$retpaid."\r\n";

            }          
          }

        }
                
      
      }

      if ($claimstatus == 'M')
        $mi = CaptureManaulIntervention($filecontents, $hbswitchid, $account, $medicalaid, $administrator,$initials,$firstnames,$surname,$depno, 
                                  $em_account, $provider);




      if (($PATFound == 'T')&&
          ($PROFound == 'T')&&
          ($CLMFound == 'T')&&
          ($TermFound == 'T'))
      {	
        $totalpaid = number_format((float)$totalpaid, 2, '.', '');
        $claimheaderresponse = 'CLA|0|Claim Received|'.$totalclaimed.'|'.$totalpaid.'|'.$claimstatus.'|'.$hbswitchid.'|'.$claimno;

        $claimslog .= $mi;
        $claimslog .= $claimheaderresponse.$itemresponses."\r\n";

        WriteLogFile($fp, $claimslog); 
        return $claimheaderresponse.$itemresponses;


      }  
      else
        WriteLogFile($fp, $claimslog); 
  
    }  
          

  }


//TEST

/*
$e = CaptureClaim("7034288", "TEST", "000179710", "PRO|7034776|
PAT|19830310|708771|0|NULL|NULL
CLM|3|600.00|H12345|L11122
ITM|1|20161110|11001|CONSULT 1|1|100.00|0.00|A12345|1.00|2.00|3.00|4.00|5.00|6.00|J45|NULL|NULL
ITM|2|20161110|80011|CONSULT 2|1|200.00|0.00|A12345|1.00|2.00|3.00|4.00|5.00|6.00|J45|NULL|NULL
ITM|3|20161110|80011|CONSULT 3|1|300.00|0.00|A12345|1.00|2.00|3.00|4.00|5.00|6.00|J45|NULL|NULL
@@@");
  echo $e;
*/






//soap

/* ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache

  $server = new SoapServer("CaptureClaimWS.wsdl");
  $server->addFunction("CaptureClaim");
  $server->handle();
*/
 
  $username     = $_POST['username'] ;
  $password     = $_POST['password'] ; 
  $practiceno   = '';
  $filecontents =  urldecode($_POST['filecontents']);

  $result = CaptureClaim($username, $password, $practiceno, $filecontents);
  echo $result;


?>
