<?php

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

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


  function CaptureProvider($filecontents)
  {
     $ipaddr = $_SERVER['REMOTE_ADDR'];

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

    $login = login('', '', 0);
   // $login = true;

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

      return "999|Incorrect Login Details";
    }
    else
    { 
     
      $claimslog .= $filecontents;
	
      $Data = explode("\n", $filecontents); //parse the rows
    
      $provider = '';
      
      $PROFound  = 'F';
      $TermFound = 'F';
      $OPTFound  = 'F';

      // do prelim checks to make sure PRO and Term Rows exist
      foreach($Data as $Row) 
      {  
        $Row = explode("|", $Row); //parse the items in rows
     
        if (trim($Row[0]) == 'PRO')
        {  
          $PROFound = 'T'; 
        }
        else  
        if (trim($Row[0]) == 'OPT')
        {  
          $OPTFound = 'T'; 
        }
        else            
        if (trim($Row[0]) == '@@@')
        {
          $TermFound = 'T'; 
        }    
      }    

      if ($TermFound == 'F')
      {
       $claimslog .= 'RSP|4|Terminator Not Found|E|-1'."\r\n";  
       WriteLogFile($fp, $claimslog);
       return 'RSP|4|Terminator Not Found|E|-1';
      }
      
      if ($OPTFound == 'F')
      {
       $claimslog .= 'RSP|5|Optometrist Line Not Found|E|-1'."\r\n";  
       WriteLogFile($fp, $claimslog);
       return 'RSP|5|Optometrist Line Not Found|E|-1';
      }


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

        $Row = explode("|", $Row); //parse the items in rows
     
        if ($Row[0] == 'OPT')
        {
          $optomtitle       = trim($Row[1]); 
          $optomfirstname   = trim($Row[2]); 
          $optomsurname     = trim($Row[3]); 
          $optomsamdcno     = trim($Row[4]); 

          if (trim($optomfirstname) == '') 
          {  
            $claimslog .= 'RSP|6|Optometrist First Name Required|E|-1'."\r\n";  
            WriteLogFile($fp, $claimslog);
            return 'RSP|6|Optometrist First Name Required|E|-1';
          }

          if (trim($optomsurname) == '') 
          {  
            $claimslog .= 'RSP|7|Optometrist Surname Required|E|-1'."\r\n";  
            WriteLogFile($fp, $claimslog);
            return 'RSP|7|Optometrist Surname Required|E|-1';
          }

          if (trim($optomsamdcno) == '')
          {  
            $claimslog .= 'RSP|8|Optometrist HPCSA No Required|E|-1'."\r\n";  
            WriteLogFile($fp, $claimslog);
            return 'RSP|8|Optometrist HPCSA No Required|E|-1';
          }

        }
        else
        if ($Row[0] == 'PRO')
        {
         
          $practiceno       = trim($Row[1]);
          $practicename     = trim($Row[2]);
          $phone1           = trim($Row[3]);
          $phone2           = trim($Row[4]);
          $email            = trim($Row[5]); 
          $postaladdr1      = trim($Row[6]); 
          $postaladdr2      = trim($Row[7]);
          $postaladdr3      = trim($Row[8]);
          $postalprovince   = trim($Row[9]);
          $postalpcode      = trim($Row[10]);
          $physaddr1        = trim($Row[11]);
          $physaddr2        = trim($Row[12]);
          $physaddr3        = trim($Row[13]);
          $physprovince     = trim($Row[14]);
          $physpcode        = trim($Row[15]); 
          $chiasma          = trim($Row[16]);  
          $contracted       = trim($Row[17]); 
          $contractjoindate = trim($Row[18]); 
          $commsemail		 = trim($Row[19]); 
          $commssms		 = trim($Row[20]); 

        

          if ($chiasma == 'T')       
           $chiasma = 'True';
          else
           $chiasma = 'False';
         
          if ($contracted == 'T')       
           $contracted = 'True';
          else
           $contracted = 'False';
          
		$province = '';

		if ($physprovince <> '')
            $province = $physprovince;
		else
		if ($postalprovince <> '')
            $province = $postalprovince;


          if (trim($practiceno) == '') 
          {  
            $claimslog .= 'RSP|1|Provider Practice No. Required|E|-1'."\r\n";  
            WriteLogFile($fp, $claimslog);
            return 'RSP|1|Provider Practice No. Required|E|-1';
          }
          
          if (trim($practicename) == '') 
          {  
            $claimslog .= 'RSP|2|Provider Practice Name Required|E|-1'."\r\n";  
            WriteLogFile($fp, $claimslog);
            return 'RSP|2|Provider Practice Name Required|E|-1';
          }
         
          $query = "SELECT COUNT(*)
                    FROM PROVIDER
                    WHERE PRACNUM = '$practiceno' ";
         
          $result = ExecuteQuery($query);

          if (ibase_errmsg()) 
          {
            $iberror = ibase_errmsg();
            
            $claimslog .= 'RSP|3|Database Error'.$iberror.'|E|-1'."\r\n";  
            WriteLogFile($fp, $claimslog);
            
            return 'RSP|3|Database Error'.$iberror.'|E|-1';
          }
          else
          {  
            $provcount  = $result[0][0];

            if ($provcount == 0)
              $status = 'I';
            else
              $status = 'U';
          }
        }
        }          
       
         // $contractjoindate = '2018-02-02';
		      $query = "SELECT RET_UNIQUEID  
                    FROM SP_CAPTUREPROVIDER('$status', '$practiceno', '$practicename','$phone1','$phone2','$email',
                      '$postaladdr1','$postaladdr2','$postaladdr3','$province','$postalpcode',
                      '$physaddr1','$physaddr2','$physaddr3','$province','$physpcode',
                      '$optomtitle','$optomfirstname','$optomsurname','$optomsamdcno', '$chiasma', '$contracted', '$contractjoindate',
				 '$commsemail', '$commssms')";

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

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

            if (ibase_errmsg()) 
            {
              $iberror = ibase_errmsg();
              $claimslog .= 'RSP|3|Could not save provider ERROR:'.$iberror.'|E|-1'."\r\n";  
              WriteLogFile($fp, $claimslog);  

              return 'RSP|3|Could not save provider ERROR:'.$iberror.'|E|-1'."\r\n".$query ;
            }
            else
            if (!$result) 
            {
              $claimslog .= 'RSP|3|Could not save provider|E|-1'."\r\n";  
              WriteLogFile($fp, $claimslog);  
              return 'RSP|3|Could not save provider|E|-1'."\r\n".$query ;
            }
            else
            {
              $row = ibase_fetch_row ($result);
            
              $retuniqueid = $row[0];
              
              $claimslog .= 'RESULT:'.$retuniqueid."\r\n";
            }          
          }
      }

     
      if (($PROFound == 'T')&&
          ($TermFound == 'T'))
      {	
        
        $claimheaderresponse = 'RSP|0|PROVIDER CAPTURED|'.$status.'|'.$retuniqueid;

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

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


      }  
      else
        WriteLogFile($fp, $claimslog); 

  }


  $filecontents =  urldecode($_POST['filecontents']);

  $result = CaptureProvider($filecontents);
  echo $result;


?>
