<?php

class Bill extends Module
{
  var $SpecificSymbol = 1; // počítačová sít
  var $FileFolder = 'doklady';
  var $FileNamePrefix = 'doklad-';

  function GenerateBill($BillId)
  {
    global $SpecificSymbol;
  
    $DbResult = $this->Database->select('FinanceBills', '*', 'Id='.$BillId);
    $Bill = $DbResult->fetch_assoc();
 
    $DbResult = $this->Database->select('Subject', '*', 'Id='.$Bill['Subject']);
    $Subject = $DbResult->fetch_assoc();

    $Dodavka = array();
    $DbResult = $this->Database->select('FinanceBillsItems', '*', 'Bill='.$BillId);
    while($Item = $DbResult->fetch_assoc())
    {
      $Dodavka[$Item['Id']] = $Item; 
    }
  
    $PaymentType = array('převodem', 'hotově');
    
    switch($Bill['Type'])
    {
    case 'invoice':
        $Output = '<table width="100%"><tr><td colspan="2">'.
        '<font size="6"><div align="center">Faktura - daňový doklad</font></div>'.
        '<hr></td></tr>'.
        '<tr><td valign="top" width="50%"><strong>Dodavatel:</strong><br>'.
        'Ing. Jiří Hajda<br>'.
        'Zděchov 208<br>'.
        '75607 Zděchov<br>'.
        'IČ: 75904535<br>'.
        'DIČ: CZ8303255884<br>'.
        'Účet: 218098370 / 0300<br>'.
        'Neplátce DPH<br>'.
        '</td><td valign="top">'.
        '<strong>Odběratel:</strong><br>'.
        $Subject['Name'].'<br>'.
        $Subject['AddressStreet'].'<br>'.
        $Subject['AddressPSC'].' '.$Subject['AddressTown'].'<br>';
        if($Subject['IC'] != 0) $Output .= 'IČ: '.$Subject['IC'].'<br>';
        if($Subject['DIC'] != '') $Output .= 'DIČ: '.$Subject['DIC'].'<br>';
        $Output .= 
        '</td></tr>'.
        '<tr><td colspan="2"><hr></td></tr>'.
        '<tr><td width="50%" valign="top">'.
        '<strong>Platební podmínky:</strong><br>'.
        'Číslo dokladu: '.$Bill['BillCode'].'<br>'.
        'Variabilní symbol: '.$Subject['Id'].'<br>'.
        'Specifický symbol: '.$this->SpecificSymbol.'<br>'.
        'Konstantní symbol:<br>'.
        'Způsob úhrady: '.$PaymentType[$Bill['Cash']].
        '</td><td valign="top">'.
        '<br>'.
        'Datum vystavení: '.HumanDate($Bill['TimeCreate']).'<br>'.
        'Datum zdanitel. plnění: '.HumanDate($Bill['TimeCreate']).'<br>'.
        'Datum splatnosti: '.HumanDate($Bill['TimeDue']).'<br>';
        $Output .= '</td></tr>'.
        '<tr><td colspan="2">'.
        '<hr>'.
        '<br>'.
        '<table border="0" width="100%">'.
        '<tr><th align="left">Dodávka</th><th align="right">Množství</th><th align="right">Cena/MJ</th><th align="right">Celkem</th></tr>'.
        '<tr><td colspan="4"><hr></td></tr>';
    
        $Total = 0;
        foreach($Dodavka as $Polozka)
        {
          $Output .= '<tr><td>'.$Polozka['Description'].'</td><td align="right">'.$Polozka['Quantity'].'</td><td align="right">'.$Polozka['Price'].'&nbsp;Kč</td><td align="right">'.($Polozka['Quantity'] * $Polozka['Price']).'&nbsp;Kč</td></tr>';
          $Total += ($Polozka['Quantity'] * $Polozka['Price']);
        }
        $Output .= '<tr><th colspan="3" align="left">Celkem</th><th align="right">'.$Total.'&nbsp;Kč</th></tr>';
        $Output .= '</table>'.
        '</td></tr>'.
        '<tr><td colspan="2"><hr></td></tr>'.
        '</table>';
      break;
    case 'income':
    $Output = '<table width="100%" border="1" cellspacing="0" cellpadding="3"><tr><td width="50%">'.
        '<strong>Firma:</strong><br>'.
        'Ing. Jiří Hajda<br>'.
        'Zděchov 208<br>'.
        '75607 Zděchov<br>'.
        'IČ: 75904535<br>'.
        'DIČ: CZ8303255884<br>'.
        'Účet: 218098370 / 0300<br>'.
        'Neplátce DPH</td><td width="50%" valign="top">'.
        '<font size="5"><strong>PŘÍJMOVÝ POKLADNÍ DOKLAD</strong></font><br><br>'.
        'Číslo dokladu: '.$Bill['BillCode'].'<br>'.
        'Datum vystavení: '.HumanDate($Bill['TimeCreate']).'<br>'.
        '</td></tr>'.
        '<tr><td colspan="2"><strong>Přijato od:</strong><br>'.
        $Subject['Name'].'<br>'.
        $Subject['AddressStreet'].'<br>'.
        $Subject['AddressPSC'].' '.$Subject['AddressTown'].'<br>';
        if($Subject['IC'] != 0) $Output .= 'IČ: '.$Subject['IC'].'<br>';
        if($Subject['DIC'] != '') $Output .= 'DIČ: '.$Subject['DIC'].'<br>';
        $Total = 0;
    $Description = '';
        foreach($Dodavka as $Polozka)
        {
          $Description .= $Polozka['Description'].'<br>';
          $Total += ($Polozka['Quantity'] * $Polozka['Price']);
        }
        $Output .= '</td></tr>'.
        '<tr><td colspan="2"><strong>Částka:</strong> '.$Total.' Kč<br><br>'.
        '</td></tr>'.    
        '<tr><td colspan="2"><strong>Účel platby:</strong><br>'.$Description.'</td></tr>'.    
    '<tr><td><br><br>Podpis příjemce:</td><td><br><br>Podpis pokladníka:</td></tr>';
        $Output .= '</table>';
      break;  
    }
  return($Output);
  }

  function CreateBill($SubjectId, $Items, $TimeCreate, $TimeDue, $BillCode = '', $Type = 'invoice')
  {
    $this->Database->insert('FinanceBills', array('TimeCreate' => TimeToMysqlDateTime($TimeCreate), 'Subject' => $SubjectId, 'TimeDue' => TimeToMysqlDateTime($TimeDue), 'BillCode' => $BillCode, 'Type' => $Type));
    $BillId = $this->Database->insert_id;
    foreach($Items as $Item)
    {
      $this->Database->insert('FinanceBillsItems', array('Bill' => $BillId, 'Description' => $Item['Description'], 'Price' => $Item['Price'], 'Quantity' => $Item['Quantity']));
    }
    //Header('Content-Type: application/pdf');
    $PdfData = $this->HtmlToPdf($this->GenerateBill($BillId));
    //echo($PdfData);
    file_put_contents($this->FileFolder.'/'.$this->FileNamePrefix.$BillId.'.pdf', $PdfData);
    //$this->Database->query('UPDATE finance_bills SET pdf = 0x'.bin2hex($PdfData).' WHERE id='.$BillId);
    return($BillId);
  } 

  function CreateIncomeBill($SubjectId, $Description, $Price, $BillCode)
  {
    $this->Database->insert('FinanceBills', array('TimeCreate' => TimeToMysqlDateTime(time()), 'Subject' => $SubjectId, 'BillCode' => $BillCode, 'Type' => 'income'));
    $BillId = $this->Database->insert_id;
    $this->Database->insert('FinanceBillsItems', array('Bill' => $BillId, 'Description' => $Description, 'Price' => $Price, 'Quantity' => 1));
    //Header('Content-Type: application/pdf');
    $PdfData = $this->HtmlToPdf($this->GenerateBill($BillId));
    //echo($PdfData);
    file_put_contents($this->FileFolder.'/'.$this->FileNamePrefix.$BillId.'.pdf', $PdfData);
    //$this->Database->query('UPDATE finance_bills SET pdf = 0x'.bin2hex($PdfData).' WHERE id='.$BillId);
    return($BillId);
  } 

  function RegeneratePDF($BillId)
  {
    global $Database;

    $PdfData = $this->HtmlToPdf($this->GenerateBill($BillId));
    //echo($this->FileFolder.'/'.$this->FileNamePrefix.$BillId.'.pdf');
    echo(file_put_contents($this->FileFolder.'/'.$this->FileNamePrefix.$BillId.'.pdf', $PdfData));
    //$this->Database->query('UPDATE finance_bills SET pdf = 0x'.bin2hex($PdfData).' WHERE id='.$BillId);
  }

  function ShowStoredBill($BillId)
  {
    global $Database;
    
    //$DbResult = $this->Database->select('finance_bills', 'pdf', 'id='.$BillId);
    //if($DbResult->num_rows == 1)
    //{
    //  $DbRow = $DbResult->fetch_array();
    $FileName = $this->FileFolder.'/'.$this->FileNamePrefix.$BillId.'.pdf';
    if(file_exists($FileName))
    {
      Header('Content-Type: application/pdf');
      Header('Content-Disposition: attachment; filename="'.$this->FileNamePrefix.$BillId.'.pdf"');
      echo(file_get_contents($FileName));
    } else echo('Faktura nenalezena');
  }

  function ShowGeneratedBill($BillId)
  {
    global $Database;
    
    Header('Content-Type: application/pdf');
    Header('Content-Disposition: attachment; filename="'.$this->FileNamePrefix.$BillId.'.pdf"');
    echo($this->HtmlToPdf($this->GenerateBill($BillId)));
  }

  function HasPDFFile($BillId)
  {
    return(file_exists($this->FileFolder.'/'.$this->FileNamePrefix.$BillId.'.pdf'));
  }

  function HtmlToPdf($HtmlCode)
  {
    $Output = shell_exec('echo "'.addslashes(FromUTF8($HtmlCode)).'"|htmldoc --no-numbered --webpage --charset 8859-2 -t pdf -');
    return($Output);
  }

  function CustomGenerate()
  {
    global $Database;
    
    $DbResult = $this->Database->select('finance_operations', '*', '(date="2008-02-01" AND comment="Poplatek za měsíc Únor") OR '.
    '(date="2008-01-01" AND comment="Poplatek za měsíc Leden") OR (date="2007-12-01" AND comment="Poplatek za měsíc Prosinec") AND (bill_id = 0)');
    while($Row = $DbResult->fetch_array())
    {
      echo($Row['id']."<br>\n");
      $Time = MysqlDateToTime($Row['date']);
      $BillId = $this->CreateBill($Row['user'], array(array('Description' => 'Poplatek za připojení k síti', 'Price' => (-$Row['money']), 'Quantity' => 1)), $Time, $Time + (date("t", time()) - 1) * 24 * 3600);  
     $this->Database->update('finance_operations', 'id='.$Row['id'], array('bill_id' => $BillId));
    }
  }

  function ShowPage()
  {
    global $Database;
    if(array_key_exists('subject', $_GET))
    {
  
      $DbResult = $this->Database->select('FinanceBills', '*', 'Subject='.$_GET['subject']);
      while($Item = $DbResult->fetch_array())
      {
        echo('<a href="?bill='.$Item['Id'].'">faktura '.$Item['Id'].'</a> <a href="?billpdf='.$Item['Id'].'">Uložené PDF</a> <a href="?billpdf2='.$Item['Id'].'">Generované PDF</a> <a href="?regenerate='.$Item['Id'].'">Přegenerovat</a><br>');
      } 
    } else
    if(array_key_exists('billpdf', $_GET))
    {
      $this->ShowStoredBill($_GET['billpdf']);
    } else
    if(array_key_exists('billpdf2', $_GET))
    {
      $this->ShowGeneratedBill($_GET['billpdf2']);
    } else
    if(array_key_exists('regenerate', $_GET))
    {
      $this->RegeneratePDF($_GET['regenerate']);
    } else
    if(array_key_exists('bill', $_GET))
    {
      echo($this->GenerateBill($_GET['bill']));
    } else
    if(array_key_exists('generate', $_GET))
    {
      $this->CreateBill(1, array(array('Description' => 'Poplatek za připojení k síti', 'Price' => 1000, 'Quantity' => 1)), time(), time());
    } else 
    {
      ShowHeader('Doklady', 'Doklady');
      echo('Faktury:<br />');
      $DbResult = $this->Database->select('Subject', '*', '1 ORDER BY Name');
      while($Subject = $DbResult->fetch_assoc())
      {
        echo('<a href="?user='.$Subject['Id'].'">'.$Subject['Name'].'</a><br />');
      }
      ShowFooter();
    }
  }
}

?>
