<?php

// API specification: https://www.fio.cz/docs/cz/API_Bankovnictvi.pdf

include('GPC.php');

function RemoveComma(string $Text): string
{
  if ((mb_strlen($Text) >= 2) and ($Text[0] == '"') and (mb_substr($Text, -1, 1) == '"')) return mb_substr($Text, 1, -1);
    else return $Text;
}

class FioAPI
{
  public string $Token;
  public string $Encoding;
  public string $Format;

  function __construct()
  {
    $this->Encoding = 'utf-8';
    $this->Format = 'csv';
  }

  function Import(int $TimeFrom, int $TimeTo): array
  {
    if ($this->Token == '') throw new Exception('Missing value for Token property.');

    // URL format: https://fioapi.fio.cz/v1/rest/periods/{token}/{datum od}/{datum do}/transactions.{format}
    // Send request
    $RequestURL = '/v1/rest/periods/'.$this->Token.'/'.
      date('Y-m-d', $TimeFrom).'/'.date('Y-m-d', $TimeTo).'/transactions.'.$this->Format;
    $Response = '';
    $Response = @file_get_contents('https://fioapi.fio.cz'.$RequestURL);
    if ($Response == FALSE)
    {
      throw new Exception('Connection error');
    } else
    {
      if ($this->Format == 'gpc') $Response = iconv('windows-1250', $this->Encoding, $Response);
      $Response = explode("\n", $Response);

      if ($this->Format == 'gpc')
      {
        // 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;
        }
      } else
      if ($this->Format == 'csv')
      {
        $Result = array(
          'Items' => array(),
        );

        // CVS header
        while ((count($Response) > 0) and ($Response[0] != ''))
        {
          $Line = explode(';', $Response[0]);
          if ($Line[0] == 'accountId') $Result['AccountNumber'] = $Line[0];
          else if ($Line[0] == 'bankId') $Result['BankId'] = $Line[0];
          else if ($Line[0] == 'currency') $Result['Currency'] = $Line[0];
          else if ($Line[0] == 'iban') $Result['IBAN'] = $Line[0];
          else if ($Line[0] == 'bic') $Result['BIC'] = $Line[0];
          else if ($Line[0] == 'openingBalance') $Result['OpeningBalance'] = $Line[0];
          else if ($Line[0] == 'closingBalance') $Result['ClosingBalance'] = $Line[0];
          else if ($Line[0] == 'dateStart') $Result['DateStart'] = $Line[0];
          else if ($Line[0] == 'dateEnd') $Result['DateEnd'] = $Line[0];
          else if ($Line[0] == 'idFrom') $Result['IdFrom'] = $Line[0];
          else if ($Line[0] == 'idTo') $Result['IdTo'] = $Line[0];
          array_shift($Response);
        }
        array_shift($Response); // Remove empty line

        if ((count($Response) == 0) or
          ($Response[0] != 'ID pohybu;Datum;Objem;Měna;Protiúčet;Název protiúčtu;Kód banky;Název banky;KS;VS;SS;Uživatelská identifikace;Zpráva pro příjemce;Typ;Provedl;Upřesnění;Komentář;BIC;ID pokynu')
          ) throw new Exception('Unsupported CSV header');
        array_shift($Response);
        array_pop($Response);
        foreach ($Response as $Index => $Line)
        {
          $Line = explode(';', $Line);
          $Date = explode('.', $Line[1]);
          $Date = mktime(0, 0, 0, $Date[1], $Date[0], $Date[2]);
          $NewRecord = array('ID' => $Line[0], 'Date' => $Date, 'Value' => $Line[2], 'CurrencyCode' => $Line[3],
            'OffsetAccount' => $Line[4], 'OffsetAccountName' => $Line[5], 'BankCode' => $Line[6], 'BankName' => RemoveComma($Line[7]),
            'ConstantSymbol' => $Line[8], 'VariableSymbol' => $Line[9], 'SpecificSymbol' => $Line[10],
            'UserIdent' => RemoveComma($Line[11]), 'Message' => RemoveComma($Line[12]), 'Type' => RemoveComma($Line[13]),
            'User' => RemoveComma($Line[14]), 'Details' => RemoveComma($Line[15]), 'Comment' => RemoveComma($Line[16]),
            'BIC' => $Line[17], 'OrderID' => $Line[18]);
          $Result['Items'][] = $NewRecord;
        }
      }
      return $Result;
    }
  }

  function NoValidDataError(array $Response): void
  {
    // Try to get error message
    // If something go wrong fio show 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);
  }
}
