<?php

include('GPC.php');

class Fio
{
  public string $UserName;
  public string $Password;
  public int $Account;

  function Import(int $TimeFrom, int $TimeTo): array
  {
    if ($this->UserName == '') throw new Exception('Missing value for UserName property.');
    if ($this->Password == '') throw new Exception('Missing value for Password property.');
    if (!is_numeric($this->Account)) throw new Exception('Missing or not numeric value for Account property.');

    $fp = fsockopen('ssl://www.fio.cz', 443, $errno, $errstr, 30);
    if (!$fp)
    {
      throw new Exception('Connection error: '.$errstr);
    } else
    {
      // Send request
      $RequestURL = "/scgi-bin/hermes/dz-pohyby.cgi?ID_ucet=".$this->Account.
        "&LOGIN_USERNAME=".$this->UserName."&SUBMIT=Odeslat&LOGIN_TIME=".time().
        "&LOGIN_PASSWORD=".$this->Password."&pohyby_DAT_od=".date('d.m.Y', $TimeFrom).
        "&pohyby_DAT_do=".date('d.m.Y', $TimeTo)."&export_gpc=1";
      $Request = "GET ".$RequestURL." HTTP/1.1\r\n";
      $Request .= "Host: www.fio.cz\r\n";
      $Request .= "User-Agent: PHP Script\r\n";
      $Request .= "Content-Type: text/html\r\n";
      $Request .= "Connection: Close\r\n\r\n";
      fwrite($fp, $Request);

      // Read response
      $Response = array();
      while (!feof($fp))
      {
        $Response[] = trim(fgets($fp, 1024));
      }
      fclose($fp);

      // Strip HTTP header
      while ($Response[0] != '') array_shift($Response);
      array_shift($Response); // Remove empty line

      // Parse all GPC lines
      $GPC = new GPC();
      $Result = array();
      foreach ($Response as $Index => $Line)
      {
        if (($Index == 0) and (substr($Line, 0, strlen(GPC_TYPE_REPORT)) != GPC_TYPE_REPORT)) $this->NoValidDataError($Response);
        $GPCLine = $GPC->ParseLine($Line);
        if ($GPCLine != NULL) $Result[] = $GPCLine;
      }
      return $Result;
    }
  }

  function NoValidDataError(array $Response): void
  {
    // Try to get error message
    // If something go wrong fio shows HTML login page and display error message
    $Response = implode('', $Response);
    $ErrorMessageStart = '<div id="oldform_warning">';
    if (strpos($Response, $ErrorMessageStart) !== false)
    {
      $Response = substr($Response, strpos($Response, $ErrorMessageStart) + strlen($ErrorMessageStart));
      $ErrorMessage = trim(substr($Response, 0, strpos($Response, '</div>')));
    } else $ErrorMessage = '';
    throw new Exception('No valid GPC data: '.$ErrorMessage);
  }
}
