<?php
include_once('../global.php');

class FinanceManagePage extends Page
{
  var $FullTitle = 'Správa financí';
  var $ShortTitle = 'Správa financí';

  function Show()
  {
    if(!$this->System->Modules['User']->CheckPermission('Finance', 'Manage')) return('Nemáte oprávnění');

    if(array_key_exists('Operation', $_GET)) $Operation = $_GET['Operation']; else $Operation = '';
	  //$Operation = 'ImportOldData';
    switch($Operation)
    {
      case 'Bills':
        $Output = $this->BillManage();
        break;
      case 'ConvertPDFToFile':
        $Output = $this->ConvertPDFDataToFiles();
        break;
      //case 'ImportOldData':
      //  $Output = $this->ImportOldData();
      //  break;
      case 'NewDeviceForm':
        $Output = $this->ShowNewDeviceForm();
        break;
      case 'NewDeviceInsert':
        $Output = $this->ShowNewDeviceInsert();
        break;
      case 'NewDeviceHistoryForm':
        $Output = $this->ShowNewDeviceHistoryForm();
        break;
      case 'NewDeviceHistoryInsert':
        $Output = $this->ShowNewDeviceHistoryInsert();
        break;
      case 'NewPaymentInsert':
        $Output = $this->ShowNewPaymentInsert();
        break;
      case 'NewPaymentForm':
        $Output = $this->ShowNewPaymentForm();
        break;
      case 'NewInvoiceInsert':
        $Output = $this->ShowNewInvoiceInsert();
        break;
      case 'NewInvoiceForm':
        $Output = $this->ShowNewInvoiceForm();
        break;
      case 'Recalculate':
        $Output = $this->System->Modules['Finance']->RecalculateSegmentParameters();
        $Output .= $this->System->Modules['Finance']->RecalculateMemberPayment();
        break;
      case 'MonthlyPayment':
        $Output = $this->ShowMonthlyPayment();
        break;
      default:
        $Output = '<a href="?Operation=NewDeviceForm">Přidat nové zařízení</a><br />';
        $Output .= '<a href="?Operation=NewDeviceHistoryForm">Přidat nový záznam historie zařízení</a><br />';
        $Output .= '<a href="?Operation=NewPaymentForm">Přidat novou platbu</a><br />';
        $Output .= '<a href="?Operation=NewInvoiceForm">Přidat novou fakturu</a><br />';
        //$Output .= '<a href="?Operation=ImportOldData">Importovat stará data</a><br />';
        $Output .= '<a href="?Operation=ConvertPDFToFile">Převést data z databáze do souborů</a><br />';
        $Output .= '<a href="?Operation=Bills">Správa dokladů</a><br />';
        //$Output .= '<a href="?Operation=ConvertData">Převést tabulky</a><br />';
        $Output .= '<a href="?Operation=Recalculate">Přepočet financí</a><br />';
        $Output .= '<a href="?Operation=MonthlyPayment">Měsíční vyúčtování</a><br />';
        $Output .= '<a href="clenove.php">Seznam členů</a><br />';
        $Output .= '<a href="zivnost.php">Živnost</a><br />';
    }
    return($Output);
  }

  function BillManage()
  {
    $Output = '';
    if(array_key_exists('subject', $_GET))
    {
      $DbResult = $this->Database->select('FinanceBills', '*', 'Subject='.$_GET['subject']);
      while($Item = $DbResult->fetch_array())
      {
        $Output .= '<a href="?Operation=Bills&amp;bill='.$Item['Id'].'">faktura '.$Item['Id'].'</a> <a href="?Operation=Bills&amp;billpdf='.$Item['Id'].'">Uložené PDF</a> <a href="?Operation=Bills&amp;billpdf2='.$Item['Id'].'">Generované PDF</a> <a href="?Operation=Bills&amp;regenerate='.$Item['Id'].'">Přegenerovat</a><br />';
      }
    } else
    if(array_key_exists('billpdf', $_GET))
    {
      $Output .= $this->System->Modules['Bill']->ShowStoredBill($_GET['billpdf']);
    } else
    if(array_key_exists('billpdf2', $_GET))
    {
      $Output .= $this->System->Modules['Bill']->ShowGeneratedBill($_GET['billpdf2']);
    } else
    if(array_key_exists('regenerate', $_GET))
    {
      $Output .= $this->System->Modules['Bill']->RegeneratePDF($_GET['regenerate']);
    } else
    if(array_key_exists('bill', $_GET))
    {
      $Output .= $this->System->Modules['Bill']->GenerateBill($_GET['bill']);
    } else
    if(array_key_exists('generate', $_GET))
    {
      $Output .= $this->System->Modules['Bill']->CreateBill(1, array(array('Description' => 'Poplatek za připojení k síti', 'Price' => 1000, 'Quantity' => 1)), time(), time());
    } else 
    {
      //ShowHeader('Faktury', 'Faktury');
      $Output .= 'Faktury:<br />';
      $DbResult = $this->Database->select('Subject', '*', '1 ORDER BY Name');
      while($Subject = $DbResult->fetch_array())
      {
        $Output .= '<a href="?Operation=Bills&amp;subject='.$Subject['Id'].'">'.$Subject['Name'].'</a><br />';
      }
      //ShowFooter();
    }
    return($Output);
  }

  function CheckAdvancesAndLiabilities($Subject)
  {
    global $LastInsertTime;

    do {
      $DbResult = $this->Database->select('FinanceAdvances', 'SUM(Value)', 'Subject='.$Subject.' AND Direction = "In"');
      $DbRow = $DbResult->fetch_array();
      $Advances = $DbRow[0];
      $DbResult = $this->Database->select('FinanceClaimsLiabilities', '*', 'Subject='.$Subject.' AND TimePayment IS NULL AND Value > 0 ORDER BY TimeCreation LIMIT 1');
      //echo($Database->error);
      if($DbResult->num_rows > 0)
      {
        $OpenedClaim = $DbResult->fetch_array();
        if($Advances > $OpenedClaim['Value'])
        {
          $this->Database->update('FinanceClaimsLiabilities', 'Id='.$OpenedClaim['Id'], array('TimePayment' => TimeToMysqlDateTime($LastInsertTime)));
          $this->Database->insert('FinanceAdvances', array('Subject' => $OpenedClaim['Subject'], 'Value' => -$OpenedClaim['Value'], 'TimeCreation' => TimeToMysqlDateTime($LastInsertTime), 'CashFlowId' => $OpenedClaim['Id'], 'Direction' => 'In'));
          //echo($Database->LastQuery);
        } else break;
      } else break;
    } while(($Advances > $OpenedClaim['Value']));
  }

  function InsertLiability($Subject, $Value, $Time, $BillId, $Text, $TimePayment = '')
  {
    global $LastInsertTime;

    if($TimePayment != '') $TimePayment = TimeToMysqlDateTime($TimePayment);
    $this->Database->insert('FinanceClaimsLiabilities', array('Text' => $Text, 'Subject' => $Subject, 'TimeCreation' => TimeToMysqlDateTime($Time), 'TimeDue' => TimeToMysqlDateTime($Time + 3600*24*15), 'TimePayment' => $TimePayment, 'Value' => $Value, 'Bill' => $BillId));
    $Output = '.'; //$this->Database->LastQuery.'<br />';
    $LastInsertTime = $Time;
    $this->CheckAdvancesAndLiabilities($Subject);
    return($Output);
  }

  function InsertMoney($Subject, $Value, $Cash, $Taxable, $Time, $Text)
  {
    global $LastInsertTime;

    $this->Database->insert('FinanceCashFlow', array('Text' => $Text, 'Subject' => $Subject, 'Cash' => $Cash, 'Value' => $Value, 'Time' => TimeToMysqlDateTime($Time), 'Taxable' => $Taxable));
    if($Value >= 0)
    {
      $this->Database->insert('FinanceAdvances', array('Subject' => $Subject, 'Value' => $Value, 'TimeCreation' => TimeToMysqlDateTime($Time), 'CashFlowId' => $this->Database->insert_id, 'Direction' => 'In'));
    }
    $LastInsertTime = $Time;
    $this->CheckAdvancesAndLiabilities($Subject);
  }

  function ShowNewDeviceForm()
  {
    $Form = new Form('NewNetworkDevice');
    $Form->OnSubmit = '?Operation=NewDeviceInsert';
    $Output = $Form->ShowEditForm();
    return($Output);
  }

  function ShowNewDeviceInsert()
  {
    $Form = new Form('NewNetworkDevice');
    $Form->LoadValuesFromForm();
    $Form->SaveValuesToDatabase(0);
    $Output = $this->SystemMessage('Finance', 'Zařízení vloženo.');
    $this->System->Modules['Log']->NewRecord('Finance', 'NewDeviceInserted');
    return($Output);
  }

  function ShowNewDeviceHistoryForm()
  {
    $Form = new Form('NewNetworkDeviceHistory');
    $Form->OnSubmit = '?Operation=NewDeviceHistoryInsert';
    $Output = $Form->ShowEditForm();
    return($Output);
  }

  function ShowNewDeviceHistoryInsert()
  {
    $Form = new Form('NewNetworkDeviceHistory');
    $Form->LoadValuesFromForm();
    $Form->SaveValuesToDatabase(0);
    $Output = $this->SystemMessage('Finance', 'Záznam historie zařízení vložen.');
    $this->System->Modules['Log']->NewRecord('Finance', 'NewDeviceHistoryInserted');
    return($Output);
  }

  function ShowNewPaymentForm()
  {
    $Form = new Form('NewPayment');
    $Form->OnSubmit = '?Operation=NewPaymentInsert';
    $Output = $Form->ShowEditForm();
    return($Output);
  }

  function ShowNewPaymentInsert()
  {
    $Form = new Form('NewPayment');
    $Form->LoadValuesFromForm();
    $this->InsertMoney($Form->Values['Subject'], $Form->Values['Value'], $Form->Values['Cash'], $Form->Values['Taxable'], $Form->Values['Time'], $Form->Values['Text']);
    $Output = $this->SystemMessage('Finance', 'Platba vložena.');
    $this->System->Modules['Log']->NewRecord('Finance', 'NewPaymentInserted');
    return($Output);
  }

  function ShowNewInvoiceForm()
  {
    $Form = new Form('NewInvoice');
    $Form->OnSubmit = '?Operation=NewInvoiceInsert';
    $Output = $Form->ShowEditForm();
    return($Output);
  }

  function ShowNewInvoiceInsert()
  {
    $Form = new Form('NewInvoice');
    $Form->LoadvaluesFromForm();
    //print_r($Form->Values);
    //$this->InsertLiability($Form->Values['Subject'], $Form->Values['Value'], $Form->Values['Time'], $BillId, $Text, $TimePayment = '')
    $Output = $this->SystemMessage('Finance', 'Faktura vložena..');
    $this->System->Modules['Log']->NewRecord('Finance', 'NewInvoiceInserted');
    return($Output);
  }

  /*
  function ImportOldData()
  {
    $Output = '';
    $this->Database->query('TRUNCATE TABLE FinanceCashFlow');
    $this->Database->query('TRUNCATE TABLE FinanceClaimsLiabilities');
    $this->Database->query('TRUNCATE TABLE FinanceAdvances');
    $this->Database->query('TRUNCATE TABLE FinanceSmallAssets');

    // Move time of device price transformation 
    $this->Database->query('UPDATE finance_operations SET date="2007-11-30" WHERE comment = "Jednorázový poplatek za společné zařízení"');

    // Transfer finance before era
    $DbResult = $this->Database->query('SELECT * FROM Subject');
    while($Subject = $DbResult->fetch_assoc())
    {
      $DbResult2 = $this->Database->query('SELECT SUM(money) FROM finance_operations WHERE user='.$Subject['Id'].' AND date < "2007-12-01"');
      $Row = $DbResult2->fetch_row();
      $TotalAdvance = $Row[0];
      //echo($User['second_name'].' '.$User['first_name'].' '.$TotalAdvance.'<br />');
      // Záloha
      if($TotalAdvance > 0) 
      {
        $this->InsertMoney($Subject['Id'], $TotalAdvance, 0, 1, mktime(0, 0, 0, 12, 1, 2007), 'Přijatá záloha (z období před daňovou evidencí)');
      }
      // Dluh
      if($TotalAdvance < 0) 
      {
        $this->InsertLiability($Subject['Id'], (-$Row[0]), mktime(0, 0, 0, 12, 1, 2007), 0, 'Připojení k síti (z období před daňovou evidencí)');
        //echo($Database->LastQuery.'<br />');
      }
    }

    // Transfer finance after era
    //  $DbResult = $Database->query('SELECT * FROM users WHERE role=2');
    //  while($User = $DbResult->fetch_array())
    //  {
    $DbResult2 = $this->Database->query('SELECT finance_operations.* FROM finance_operations JOIN Subject ON Subject.Id = finance_operations.user WHERE finance_operations.date >= "2007-12-01"');
    while($Operation = $DbResult2->fetch_assoc())
    {
      //echo($Operation['comment'].'<br />');
      if(substr($Operation['comment'], 0, 19) == 'Poplatek za měsíc')
      {
        $this->InsertLiability($Operation['user'], -$Operation['money'], MysqlDateToTime($Operation['date']), $Operation['bill_id'], 'Připojení k síti');
        $Output .= $Operation['user'].' '.$Operation['money'].' Připojení k síti<br />';
      } else
      if($Operation['comment'] == 'Vklad')
      {
        $this->InsertMoney($Operation['user'], $Operation['money'], 0, 1, MysqlDateToTime($Operation['date']), 'Přijatá záloha');
        //echo($Operation['user'].' '.$Operation['money'].' Přijatá záloha<br />');
      } else
      if($Operation['comment'] == 'Internet')
      {
        $this->InsertLiability($Operation['user'], $Operation['money'], MysqlDateToTime($Operation['date']), $Operation['bill_id'], 'Měsíční paušál za Internet', MysqlDateToTime($Operation['date']));
        $this->InsertMoney($Operation['user'], $Operation['money'], 0, 1, MysqlDateToTime($Operation['date']), 'Měsíční paušál za Internet');
      } else
      if($Operation['comment'] == 'Sociální pojištění')
      {
        $this->InsertLiability($Operation['user'], $Operation['money'], MysqlDateToTime($Operation['date']), $Operation['bill_id'], $Operation['comment'], MysqlDateToTime($Operation['date']));
        $this->InsertMoney($Operation['user'], $Operation['money'], 0, 1, MysqlDateToTime($Operation['date']), $Operation['comment']);
      } else
      {
        $DbResult = $this->Database->query('SELECT Id FROM Subject WHERE Id='.$Operation['user']);
        while($User = $DbResult->fetch_array())
        $this->InsertLiability($Operation['user'], -$Operation['money'], MysqlDateToTime($Operation['date']), $Operation['bill_id'], $Operation['comment'], MysqlDateToTime($Operation['date']));
        $Output .= $Operation['user'].' '.$Operation['comment'].' '.MysqlDateToTime($Operation['date']).'<br />';

//        if(($Operation['role'] == 2))
       // {
          $Output .= 'A';
          $this->Database->insert('FinanceAdvances', array('Subject' => $Operation['user'], 'Value' => $Operation['money'], 'TimeCreation' => MysqlDateToTime($Operation['date']), 'CashFlowId' => 0, 'Direction' => 'In'));
          $this->CheckAdvancesAndLiabilities($Operation['user']);
        //} else InsertMoney($Operation['user'], $Operation['money'], 0, 1, MysqlDateToTime($Operation['date']), $Operation['comment']);
      }
    }
    //  }

    // Import small asset
    $Subject = 1;

    // Převod pro minulý rok
    $Time = mktime(0, 0, 0, 12, 10, 2007);
    $DbResult = $this->Database->query('SELECT * FROM network_devices WHERE used <> 0 AND date < "'.TimeToMysqlDateTime($Time).'" AND (id <> 73)');
    $Items = array();
    $TotalPrice = 0;
    while($Device = $DbResult->fetch_array())
    {
      //$Database->insert('FinanceSmallAsset', array());
      $Items[] = array('Description' => $Device['name'], 'Quantity' => $Device['count'], 'Price' => 0); //$Device['price']); 
      $LastId = $Device['id'];
      $TotalPrice += $Device['price'] * $Device['count'];
      if($TotalPrice > 55000) break;
    }
    //print_r($Items);
    $BillId = $this->System->Modules['Bill']->CreateBill($Subject, $Items, $Time, $Time);
    $DbResult = $this->Database->query('UPDATE network_devices SET TimeEnlistment = "'.TimeToMysqlDateTime($Time).'" WHERE used <> 0 AND date < "'.TimeToMysqlDateTime($Time).'" AND (id <> 73) AND (id <= '.$LastId.')');
    //echo($Database->error);
    $this->InsertLiability($Subject, 0, $Time, $BillId, 'Nákup infrastruktury', $Time);
    //InsertMoney($Subject, 0, 0, 1, $Time, 'Nákup infrastruktury');

    //echo($LastId);

    // Převod tento rok
    $Time = mktime(0, 0, 0, 1, 14, 2008);
    $DbResult = $this->Database->query('SELECT * FROM network_devices WHERE (used <> 0) AND (id > '.$LastId.') AND date < "'.TimeToMysqlDateTime($Time).'"');
    $Items = array();
    $TotalPrice = 0;
    while($Device = $DbResult->fetch_array())
    {
      // $Database->insert('FinanceSmallAsset', array());
      $Items[] = array('Description' => $Device['name'], 'Quantity' => $Device['count'], 'Price' => 0); //$Device['price']);
      $TotalPrice += $Device['price'] * $Device['count'];
    }
    //print_r($Items);
    $BillId = $this->System->Modules['Bill']->CreateBill($Subject, $Items, $Time, $Time);
    $DbResult = $this->Database->query('UPDATE network_devices SET TimeEnlistment = "'.TimeToMysqlDateTime($Time).'" WHERE used <> 0 AND date < "'.TimeToMysqlDateTime($Time).'" AND (id > '.$LastId.')');
    $this->InsertLiability($Subject, 0, $Time, $BillId, 'Nákup infrastruktury', $Time);
    //InsertMoney($Subject, 0, 0, 1, $Time, 'Nákup infrastruktury');


    // Make absolute value in monthly overall  
    //$Database->query('UPDATE finance_monthly_overall SET total_paid = ABS(total_paid)');
    //$Database->query('UPDATE finance_monthly_overall SET member_count = (SELECT COUNT(*) FROM users WHERE users.role=2 AND users.membership_date < finance_monthly_overall.date)'); 
    return($Output);
  }
  */
  
  function ConvertPDFDataToFiles()
  {
    $DbResult = $this->Database->query('SELECT * FROM FinanceBills');
    while($Bill = $DbResult->fetch_assoc())
    {
      file_put_contents('doklady/doklad_'.$Bill['id'].'.pdf', $Bill['pdf']);
      echo($Bill['id'].',');
    }
  }

  function CheckPDFFiles()
  {
    global $InvoiceGenerator;

    $DbResult = $this->Database->query('SELECT * FROM FinanceBills');
    while($Bill = $DbResult->fetch_assoc())
    {
      file_put_contents('doklady2/doklad-'.$Bill['id'].'.pdf', file_get_contents('doklady/doklad-'.$Bill['id'].'.pdf'));
      //echo($InvoiceGenerator->HasPDFFile($Bill['id']).',');
    }
  }

  /*
  function ConvertData()
  {
    $Finance = $this->System->Modules['Finance'];
	  $Output = '';
	  $this->Database->query('TRUNCATE TABLE FinanceOperation');
	  $this->Database->query('TRUNCATE TABLE FinanceClaimsLiabilities');

    // Move time of device price transformation 
    $this->Database->query('UPDATE finance_operations SET date="2007-11-30" WHERE comment = "Jednorázový poplatek za společné zařízení"');

    // Transform old operations
	  $DbResult = $this->Database->query('SELECT * FROM finance_operations WHERE finance_operations.date >= "2007-12-01" AND (Source = '.$Finance->ExternalSubject.')');
	  while($DbRow = $DbResult->fetch_assoc())
	  {
	    $this->Database->insert('FinanceOperation', array('Id' => $DbRow['id'], 'Subject' => $DbRow['Destination'], 'Cash' => $DbRow['cash'], 'Value' => abs($DbRow['money']), 'Time' => $DbRow['date'], 'BillCode' => $DbRow['BillCode'], 'Taxable' => $DbRow['Taxable'], 'Text' => $DbRow['comment'], 'Bill' => $DbRow['bill_id']));
	    $Output .= '.';
	  }
	  $DbResult = $this->Database->query('SELECT * FROM finance_operations WHERE finance_operations.date >= "2007-12-01" AND (Destination = '.$Finance->ExternalSubject.')');
	  while($DbRow = $DbResult->fetch_assoc())
	  {
	    $this->Database->insert('FinanceOperation', array('Id' => $DbRow['id'], 'Subject' => $DbRow['Source'], 'Cash' => $DbRow['cash'], 'Value' => -abs($DbRow['money']), 'Time' => $DbRow['date'], 'BillCode' => $DbRow['BillCode'], 'Taxable' => $DbRow['Taxable'], 'Text' => $DbRow['comment'], 'Bill' => $DbRow['bill_id']));
	    $Output .= '.';
	  }

    // Transform old invoices
	  $DbResult = $this->Database->query('SELECT * FROM finance_operations WHERE finance_operations.date >= "2007-12-01" AND (Source = '.$Finance->MainSubject.')');
	  while($DbRow = $DbResult->fetch_assoc())
	  {
	    $this->Database->insert('FinanceClaimsLiabilities', array('Id' => $DbRow['id'], 'Subject' => $DbRow['Destination'], 'Value' => -abs($DbRow['money']), 'TimeCreation' => $DbRow['date'], 'BillCode' => $DbRow['BillCode'], 'Text' => $DbRow['comment'], 'Bill' => $DbRow['bill_id']));
	    $Output .= 'FV '.$DbRow['comment'].'<br />';
	  }
	  $DbResult = $this->Database->query('SELECT * FROM finance_operations WHERE finance_operations.date >= "2007-12-01" AND (Destination = '.$Finance->MainSubject.')');
	  while($DbRow = $DbResult->fetch_assoc())
	  {
	    $this->Database->insert('FinanceClaimsLiabilities', array('Id' => $DbRow['id'], 'Subject' => $DbRow['Source'], 'Value' => abs($DbRow['money']), 'TimeCreation' => $DbRow['date'], 'BillCode' => $DbRow['BillCode'], 'Text' => $DbRow['comment'], 'Bill' => $DbRow['bill_id']));
	    $Output .= 'FP '.$DbRow['comment'].'<br />';
	  }

    // Transfer finance before era
    $DbResult = $this->Database->query('SELECT * FROM Subject');
    while($Subject = $DbResult->fetch_assoc())
    {
      $DbResult2 = $this->Database->query('SELECT SUM(money) as money FROM finance_operations WHERE user='.$Subject['Id'].' AND date < "2007-12-01"');
      $DbRow2 = $DbResult2->fetch_assoc();

	    $DbRow2['date'] = TimeToMysqlDateTime(mktime(0, 0, 0, 12, 1, 2007));
	    if($DbRow2['money'] > 0)
	    {
		    $Comment = 'Přijatá záloha (z období před daňovou evidencí)';
   	    $this->Database->insert('FinanceOperation', array('Subject' => $Subject['Id'], 'Cash' => 0, 'Value' => abs($DbRow2['money']), 'Time' => $DbRow2['date'], 'Taxable' => 1, 'Text' => $Comment));
} else
	    {
		    $Comment = 'Připojení k síti (z období před daňovou evidencí)';
  	    $this->Database->insert('FinanceClaimsLiabilities', array('Subject' => $Subject['Id'], 'Value' => abs($DbRow2['money']), 'TimeCreation' => $DbRow2['date'], 'Text' => $Comment));
	    }
	    $Output .= '#';
    }

	return($Output);
  }
  */

	
	function GetBillingPeriod($Period)
	{
    $MonthCount = $this->System->Modules['Finance']->BillingPeriods[$Period]['MonthCount'];
    $PeriodFrom = mktime(0, 0, 0, date('n'), 1, date('Y'));
    $PeriodTo = mktime(0, 0, 0, date('n') + $MonthCount - 1, date('t', mktime(0, 0, 0, date('n') + $MonthCount - 1, 1, date('Y'))) , date('Y'));
		return(array('From' => $PeriodFrom, 'To' => $PeriodTo, 'MonthCount' => $MonthCount));
	} 

  function ShowMonthlyPayment()
  {
    if(!$this->System->Modules['User']->CheckPermission('Finance', 'Manage')) return('Nemáte oprávnění');
	  $Output = '';

    $Finance = &$this->System->Modules['Finance'];
	  
    // Načti poslední měsíční přehled a nastavení
    $DbResult = $this->Database->select('finance_monthly_overall', '*', '1 ORDER BY date DESC LIMIT 1');
    $Overall = $DbResult->fetch_array();

    $Output -= 'Datum: '.date('j.n.Y').'<br />';
    
    $Datum = explode('-', $Overall['date']);
    $Mesic = date('m') + 0;

    $Output .= $Finance->RecalculateSegmentParameters();
    $Output .= $Finance->LoadTariffs();
    //$InvoiceGenerator->CustomGenerate();
    $Output .= $Finance->RecalculateMemberPayment();

    // Celkovy prehled
    $DbResult = $this->Database->query('SELECT SUM(price) FROM network_devices WHERE used = 1');
    $Row = $DbResult->fetch_row();
		$TotalDeviceCost = $Row[0];
    $Output .= 'Celková cena zařízení: Zařízení('.$TotalDeviceCost;
		
    $DbResult = $this->Database->query('SELECT SUM(price) FROM network_segments');
    $Row = $DbResult->fetch_row();
		$TotalSegmentDeviceCost = $Row[0];
    $Output .= '), Segmenty('.$TotalSegmentDeviceCost;
		
    $DbResult = $this->Database->query('SELECT SUM(NetworkDevice) FROM MemberPayment');
    $Row = $DbResult->fetch_row();
		$TotalMemberDeviceCost = $Row[0];
    $Output .= '), Členové('.$TotalMemberDeviceCost.')<br />';
		
    $DbResult = $this->Database->query('SELECT SUM(Cash) FROM MemberPayment');
    $Row = $DbResult->fetch_row();
		$TotalMemberCash = $Row[0];
    $Output .= 'Stav pokladny: Členové('.$TotalMemberCash.')';   

    $DbResult = $this->Database->query('SELECT SUM(consumption) FROM network_devices WHERE used=1');
    $Row = $DbResult->fetch_row();
		$TotalConsumption = $Row[0];
    $TotalConsumptionCost = $Finance->W2Kc($TotalConsumption);

    $SpravaCelkem = $Finance->Sprava * $Finance->SpravaUsers;
    $Output .= 'Kontrola placení (Zaplaceno-Sprava-Internet): '.$Finance->TotalPaid.'-'.$SpravaCelkem.'-'.$Finance->Internet.'='.($Finance->TotalPaid - $SpravaCelkem - $Finance->Internet).'<br />';

    // Zkontrolovat odečtení měsíčního poplatku
    //$Mesic = '1';
    $Output .= 'Kontrola odečtení poplatků: Poslední měsíc-'.round($Datum[1]).' Aktuální měsíc-'.$Mesic.'<br />';
    if($Mesic != $Datum[1])
    {
      $Output .= 'Odečítám měsíční poplatek...<br />';

      // Generuj účetní položky
      $DbResult = $this->Database->query('SELECT Member.*, MemberPayment.MonthlyTotal, UNIX_TIMESTAMP(Member.BillingPeriodLastDate), Subject.Name AS SubjectName FROM MemberPayment JOIN Member ON Member.Id=MemberPayment.Member JOIN Subject ON Subject.Id=Member.Subject');
      while($Member = $DbResult->fetch_array())
      {
        $Output .= $Member['SubjectName'].': ';
				$Period = $this->GetBillingPeriod($Member['BillingPeriodNext']);
				if($Period['From'] > $Member['UNIX_TIMESTAMP(Member.BillingPeriodLastDate)'])
				{
					$this->Database->update('Member', 'Id='.$Member['Id'], array('BillingPeriod' => $Member['BillingPeriodNext'], 'InternetTariffCurrentMonth' => $Member['InternetTariffNextMonth']));
					$Member['BillingPeriod'] = $Member['BillingPeriodNext'];
				}
				$Period = $this->GetBillingPeriod($Member['BillingPeriod']);
				$PayPerPeriod = $Member['MonthlyTotal'] * $Period['MonthCount'];
        if(($Period['From'] > $Member['UNIX_TIMESTAMP(Member.BillingPeriodLastDate)']) and ($Member['InternetTariffCurrentMonth'] != 6) and ($PayPerPeriod > 0))
        {
          //echo($Mesic.'%'.$MonthCount.'='.($Mesic % $MonthCount).' ');         					
          $TimePeriodText = date('j.n.Y', $Period['From']).' - '.date('j.n.Y', $Period['To']);
          $Output .= $TimePeriodText.': '.$Member['MonthlyTotal'].' * '.$Period['MonthCount'].' = '.$PayPerPeriod.'<br />';
          $BillCode = $Finance->GetNextDocumentLineNumber(6); // Faktury vydané
          $BillId = $this->System->Modules['Bill']->CreateBill($Member['Subject'], array(array('Description' => 'Připojení k síti', 'Price' => $PayPerPeriod, 'Quantity' => 1)), $Period['From'], $Period['To'], $BillCode);
          $this->Database->insert('FinanceClaimsLiabilities', array('Value' => $PayPerPeriod, 'Subject' => $Member['Subject'], 'TimeCreation' => 'NOW()', 'Text' => 'Připojení k síti za období '.$TimePeriodText, 'Bill' => $BillId, 'BillCode' => $BillCode));
					$this->Database->update('Member', 'Id='.$Member['Id'], array('BillingPeriodLastDate' => TimeToMysqlDateTime($Period['To'])));
        } else $Output .= '<br />';
      }
			
      // Update finance charge
      $Output .= 'Měním aktuální parametry sítě...<br>';
      $this->Database->delete('finance_charge', 'period = 0');
      $DbResult = $this->Database->select('finance_charge', '*', 'period = 1');
      $Charge = $DbResult->fetch_assoc();
      //print_r($Charge);
      $DbResult = $this->Database->insert('finance_charge', array('period' => 0, 'internet' => $Charge['internet'], 'internet_speed' => $Charge['internet_speed'], 'internet_speed_reserve' => $Charge['internet_speed_reserve'], 'administration_per_user' => $Charge['administration_per_user'], 'kWh' => $Charge['kWh'], 'base_speed_element' => $Charge['base_speed_element'], 'BaseTariffPrice' => $Charge['BaseTariffPrice'], 'TopTariffPrice' => $Charge['TopTariffPrice']));

      $Output .= 'Přidávám měsíční přehled...<br />';
      $this->Database->insert('finance_monthly_overall', array('date' => 'NOW()', 'money' => $Finance->Internet, 'kWh' => $Finance->kWh, 'administration' => $Finance->Sprava, 'administration_total' => $SpravaCelkem, 'consumption_total' => $TotalConsumptionCost, 'total_paid' => $Finance->TotalPaid, 'BaseTariffPrice' => $Charge['BaseTariffPrice'], 'TopTariffPrice' => $Charge['TopTariffPrice'], 'member_count' => $Finance->InternetUsers));

      $Output .= 'Měním aktuální tarify....<br>';
      // Update tarrifs
      $this->Database->delete('FinanceTariff', 'Period=0');
      $DbResult = $this->Database->select('FinanceTariff', '*', 'Period = 1');
      while($Tariff = $DbResult->fetch_array())
      {
        $this->Database->insert('FinanceTariff', array('Period' => 0, 'Name' => $Tariff['Name'], 'Tariff' => $Tariff['Tariff'], 'UploadAsymmetry' => $Tariff['UploadAsymmetry'], 'MemberCount' => $Tariff['MemberCount'], 'Group' => $Tariff['Group'], 'SpeedMin' => $Tariff['SpeedMin'], 'SpeedMax' => $Tariff['SpeedMax'], 'Price' => $Tariff['Price']));
      }

	    $Finance->RecalculateMemberPayment();
      //CreateMonthlyOverallBill();
      //$Finance->RecalculateUsersFinance();

      // Restart traffic shaping
      //$this->Database->update('NetworkConfiguration', 'Id = 3', array('Changed' => 1));
    }
    return($Output);
  }
}

$System->AddModule(new FinanceManagePage());
$System->Modules['FinanceManagePage']->GetOutput();

?>
