<?php

include_once(dirname(__FILE__).'/../../Common/Global.php');

class BankImport
{
  var $System;
  var $Database;
  var $BankAccount;
  
  function __construct($System)
  {
    $this->Database = &$System->Database;
    $this->System = &$System;
  }
     
  function Import()
  {
  }
  
  function ImportFile($Content, $Ext)
  {   
  }
  
  function PairOperations()
  {
    $DbResult = $this->Database->select('FinanceBankImport', '*', 'FinanceOperation IS NULL');
    while($DbRow = $DbResult->fetch_assoc())
    {
      if(is_numeric($DbRow['VariableSymbol']))
      {
        $DbResult2 = $this->Database->select('Subject', 'Id', 'Id='.$DbRow['VariableSymbol']);
        if($DbResult2->num_rows == 1)
        { 
          $DbRow2 = $DbResult2->fetch_assoc();
          if($DbRow['Value'] >= 0) $DocumentLine = 3; // Receive money
            else $DocumentLine = 4; // Send money
          $Year = date('Y', MysqlDateToTime($DbRow['Time']));
          $BillCode = $this->System->Modules['Finance']->GetNextDocumentLineNumber($DocumentLine, $Year);
          $DbResult3 = $this->Database->insert('FinanceOperation', array('Subject' => $DbRow2['Id'], 'Cash' => 0, 
            'Value' => $DbRow['Value'], 'Taxable' => 1, 'BankAccount' => $DbRow['BankAccount'], 'Network' => 1,
            'Time' => $DbRow['Time'], 'Text' => $DbRow['Description'], 'BillCode' => $BillCode, 'DocumentLine' => $DocumentLine));
          $this->Database->update('FinanceBankImport', 'Id='.$DbRow['Id'], array('FinanceOperation' => $this->Database->insert_id));
        }
      }
    }
  }
}

class PageImportAPI extends Page
{
  var $FullTitle = 'Import plateb přes API';
  var $ShortTitle = 'Import plateb přes API';
  var $ParentClass = 'PageFinance';

  function Show()
  {   
    $Output = '';
    if(!$this->System->User->CheckPermission('Finance', 'SubjectList')) return('Nemáte oprávnění');
     
    $DbResult = $this->Database->select('FinanceBankAccount', '*', 'Id='.$_GET['i']);
    $BankAccount = $DbResult->fetch_assoc();
    
    $DbResult = $this->Database->select('FinanceBank', '*', 'Id='.$BankAccount['Bank']);
    $Bank = $DbResult->fetch_assoc();
    $Output .= 'Účet: '.$BankAccount['Number'].'/'.$Bank['Code'].' ('.$Bank['Name'].')';
    
    if($Bank['Code'] == '2010') $Import = new ImportFio($this->System);
      else if($Bank['Code'] == '0300') $Import = new ImportPS($this->System);
      else $Output = $this->SystemMessage('Nepodporované API', 'Pro zvolenou banku není import podporován');
    if(isset($Import))
    {
      $Import->BankAccount = $BankAccount;
      $Output .= $Import->Import();
      $Import->PairOperations();
    } 
    return($Output);
  }
}
  
class PageImportFile extends Page
{
  var $FullTitle = 'Import plateb ze souboru';
  var $ShortTitle = 'Import plateb ze souboru';
  var $ParentClass = 'PageFinance';
  
  function Show()
  {
    $Output = '';
    if(!$this->System->User->CheckPermission('Finance', 'SubjectList')) return('Nemáte oprávnění');
    if(array_key_exists('Operation', $_GET))
    {
      if($_GET['Operation'] == 'prepare') $Output .= $this->Prepare();
      else if($_GET['Operation'] == 'insert') $Output .= $this->Insert();
      else $Output .= 'Neplatná akce';
    } else $Output .= $this->ShowForm();
    return($Output);
  }
  
  function ShowForm()
  {
    $Form = new Form($this->System->FormManager);
    $Form->SetClass('ImportBankFile');
    $Form->OnSubmit = '?Operation=prepare';
    $Form->Values['BankAccount'] = $_GET['id'];
    $Output = $Form->ShowEditForm();
    return($Output);
  }
  
  function Prepare()
  {   
    $Form = new Form($this->System->FormManager);
    $Form->SetClass('ImportBankFile');
    $Form->LoadValuesFromForm();
    $File = $Form->Values['File'];
    $Output = $File->Name.'<br/>';
    $Output .= $File->GetFullName().'<br/>';

    $DbResult = $this->Database->select('FinanceBankAccount', '*', 'Id='.$Form->Values['BankAccount']);
    $BankAccount = $DbResult->fetch_assoc();
    
    $DbResult = $this->Database->select('FinanceBank', '*', 'Id='.$BankAccount['Bank']);
    $Bank = $DbResult->fetch_assoc();
    $Output .= 'Účet: '.$BankAccount['Number'].'/'.$Bank['Code'].' ('.$Bank['Name'].')';
    
    if($Bank['Code'] == '2010') $Import = new ImportFio($this->System);
      else if($Bank['Code'] == '0300') $Import = new ImportPS($this->System);
      else $Output = $this->SystemMessage('Nepodporované API', 'Pro zvolenou banku není import podporován');
    $Import->BankAccount = $BankAccount;
    $Output .= $Import->ImportFile($File->GetContent(), $File->GetExt());
   
    return($Output);
  }
  
  function InsertMoney($Subject, $Value, $Cash, $Taxable, $Time, $Text, $DocumentLine)
  {
    $Year = date('Y', $Time);     
    $BillCode = $this->System->Modules['Finance']->GetNextDocumentLineNumber($DocumentLine, $Year);
    $this->Database->insert('FinanceOperation', array('Text' => $Text, 'Subject' => $Subject, 'Cash' => $Cash, 'Value' => $Value, 'Time' => TimeToMysqlDateTime($Time), 'Taxable' => $Taxable, 'BillCode' => $BillCode));
  }

  function Insert()
  {
    $Finance = $this->System->Modules['Finance'];
    $Output = '';
    
    for($I = $_POST['ItemCount'] - 1; $I >= 0 ; $I--)
    {
      if($_POST['Money'.$I] < 0) $DocumentLine = 4;
        else $DocumentLine = 3;
      $Date = explode('-', $_POST['Date'.$I]);
      $Date = mktime(0, 0, 0, $Date[1], $Date[2], $Date[0]);
      $this->InsertMoney($_POST['Subject'.$I], $_POST['Money'.$I], 0, $_POST['Taxable'.$I], $Date, $_POST['Text'.$I], $DocumentLine);
      $Output .= $I.', ';
      $this->System->ModuleManager->Modules['Log']->NewRecord('Finance', 'NewPaymentInserted');
    }
    return($Output);
  }
}
