<?php


  require('includes/application_top.php');

  require_once DIR_WS_CLASSES."search_cache.php";
  
  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies = new currencies();
  
  include(DIR_WS_INCLUDES .'languages/'.$language.'/'.FILENAME_ACCOUNTING);

?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<style type="text/css">
  tr#rowHdr td { border-bottom: 1px solid black }
  tr#rowFtr td { border-top: 1px solid black }
</style>
</head>
<body bgcolor="#FFFFFF">

  <table border="0" width="100%" cellspacing="0" cellpadding="2">
    <thead>
    <tr id="rowHdr">
      
  <td class="main" align="left" style="width:20px;"><?php echo TABLE_HEADING_DATE; ?></td>
  <td class="main" align="left" style="width:100px;"><?php echo TABLE_HEADING_VID; ?></td>
  <td class="main" align="left"><?php echo TABLE_HEADING_SPECS; ?></td>
  <td class="main" align="left"><?php echo TABLE_HEADING_DEBC; ?></td>
  <td class="main" align="left"><?php echo TABLE_HEADING_AID; ?></td>
  <td class="main" align="right"><?php echo TABLE_HEADING_VATPROC; ?></td>
  <td class="main" align="right"><?php echo TABLE_HEADING_VAT0; ?></td>
  <td class="main" align="right"><?php echo TABLE_HEADING_VATOSUUS; ?></td>
  <td class="main" align="right"><?php echo TABLE_HEADING_VATFULL; ?></td>
      
   

    </tr>
    </thead>
    <tbody>
<?php
  if ($HTTP_GET_VARS['search_id']) {
    $search_cache = new SearchCache ('invoice_search', $HTTP_GET_VARS['search_id']);
    $search_params = $search_cache->getParameters();
  } else
    $search_params = array();
  
  $show_q = "";
  if ($search_params['show']) {
    $show = $search_params['show'];
    if ($show == 'paid') {
      $show_q = 'and i.paid is not null';
    } else if ($show == 'unpaid') {
      $show_q = 'and i.paid is null';
    }
  }
  switch ($search_params['hold']) {
    case 'on':
      $show_q .= " and i.on_hold = '1'";
      break;
    case 'not':
      $show_q .= " and i.on_hold = '0'";
      break;
  }
  
  $benf_sql = '';
  if (is_array($search_params['benf']) && sizeof($search_params['benf'])) {
    foreach ($search_params['benf'] as $key => $value) {
      if ($value != '-') {
        if ($benf_sql)
          $benf_sql .= " or ";
        $benf_sql .= "i.receiver = '".addslashes($value)."'";
      }
    }
    if ($benf_sql)
      $show_q .= " and ($benf_sql)";
  }
  if (!$benf_sql && $search_params['recv']) {
    $show_q .= " and i.receiver like '%".addslashes($search_params['recv'])."%'";
  }
  if ($search_params['inv'])
    $show_q .= " and i.invoices_id = '".(int)$search_params['inv']."'";
  if ($search_params['comm'])
    $show_q .= " and i.comment like '%".addslashes($search_params['comm'])."%'";
  if ($search_params['sumfr']) {
    $sum_from = (float)str_replace(',', '.', $search_params['sumfr']);
    $show_q .= " and i.sum >= ".$sum_from;
  }
  if ($search_params['sumto']) {
    $sum_to = (float)str_replace(',', '.', $search_params['sumto']);
    $show_q .= " and i.sum <= ".$sum_to;
  }
  if ($search_params['invfr'])
    $show_q .= " and i.invoice_date >= '".addslashes($search_params['invfr'])."'";
  if ($search_params['invto'])
    $show_q .= " and i.invoice_date <= '".addslashes($search_params['invto'])." 23:59:59'";
  if ($search_params['expfr'])
    $show_q .= " and i.expires >= '".addslashes($search_params['expfr'])."'";
  if ($search_params['expto'])
    $show_q .= " and i.expires <= '".addslashes($search_params['expto'])." 23:59:59'";
  if ($search_params['paidfr'])
    $show_q .= " and i.paid >= '".addslashes($search_params['paidfr'])."'";
  if ($search_params['paidto'])
    $show_q .= " and i.paid <= '".addslashes($search_params['paidto'])." 23:59:59'";
  
  $sort = $HTTP_GET_VARS['sort'];
  $desc = $HTTP_GET_VARS['d'];
  $orderq = "order by expires";
  if ($sort != "") {
    $orderq = "order by $sort" .($desc? ' desc': '');
  }
  
  $n = 0;
  $sum_total = 0;
  $invoices_query = tep_db_query("select i.invoices_id, i.deb_cred, i.receiver, i.specifikation, i.account_class_booked, i.sum, i.vat_osuus, i.vat_percent, i.invoice_date, i.expires, i.paid, i.on_hold, i.comment, i.sum_vat_no from " .TABLE_ACCOUNTING ." as i where 1 $show_q $orderq");
  while ($invoices = tep_db_fetch_array($invoices_query)) {
    
     $sum_total1 += $invoices['sum_vat_no'];
     $sum_total2 += $invoices['vat_osuus'];
     $sum_total3 += $invoices['sum'];
    
    echo '    <tr class="prodRow'.($n++ % 2? 'Odd': 'Even').'">' . "\n".
       '      <td class="main" align="left">'.tep_date_short($invoices['invoice_date'])."</td>\n".
       '      <td class="main" align="left">'.$invoices['invoices_id']."</td>\n".
       '      <td class="main" align="left">'.$invoices['specifikation']."</td>\n".
       '      <td class="main" align="left">'.$invoices['deb_cred']."</td>\n".
       '      <td class="main" align="left">'.$invoices['receiver']."</td>\n".
       '      <td class="main" align="right">'.$invoices['vat_percent'].',00%'."</td>\n".
       '      <td class="main" align="right">'.$currencies->format($invoices['sum_vat_no'])."</td>\n".
       '      <td class="main" align="right">'.$currencies->format($invoices['vat_osuus'])."</td>\n".
       '      <td class="main" align="right">'.$currencies->format($invoices['sum'])."</td>\n".



     
  //    '      <td class="main" align="center">'.tep_date_short($invoices['expires'])."</td>\n".
      
      
      
      '      <td class="main" align="center">';
    if ($invoices['paid']) {
      echo tep_date_short($invoices['paid']);
    } else if ($invoices['on_hold']) {
      echo TEXT_ON_HOLD;
    } else
      echo '&nbsp;';
    echo "</td>\n".
    //  '      <td class="main" align="right">'.$currencies->format($invoices['sum'])."</td>\n".
      "    </tr>\n";
  }
?>
    <tr id="rowFtr">
      <td class="main" colspan="6"><?php echo TABLE_FOOTER_SUM_TOTAL; ?></td>
       <td class="main" align="right"><?php echo $currencies->format($sum_total1); ?></td>
       <td class="main" align="right"><?php echo $currencies->format($sum_total2); ?></td>
      <td class="main" align="right"><?php echo $currencies->format($sum_total3); ?></td>
    </tr>
      
      
      
      
      
      
      
      
      
      
         <tr>
            <td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '1', '50'); ?></td>
          </tr>
      
      
      
      
      
      
      
      
      
      
      
      
  <?php    
      
       if (isset($HTTP_GET_VARS['select'])) {
  
    $select = tep_db_prepare_input($HTTP_GET_VARS['select']);
    $module = tep_db_prepare_input($HTTP_GET_VARS['module']);
    $subtype = tep_db_prepare_input($HTTP_GET_VARS['subtype']);
    if ($select) {
      tep_db_query ("replace " .TABLE_ACCOUTING_CLASS_STATUS ." (module, subtype) values ('$module', '$subtype')");
    } else
      tep_db_query ("delete from " .TABLE_ACCOUTING_CLASS_STATUS ." where module = '$module' and subtype = '$subtype'");
  }

  $status_query = tep_db_query("select * from ". TABLE_ACCOUTING_CLASS_STATUS);
  $status_select = array();
  while ($row = tep_db_fetch_array($status_query))
    $status_select[$row['module']][] = $row['subtype'];

  $status_rows = array();
                                                                                                                                              
  $orders_status_query = tep_db_query ("select * from " .TABLE_ACCOUNTING_CLASS ." ");
  while ($os_row = tep_db_fetch_array($orders_status_query)) {
    $row['text'] = $os_row['name'];
    $row['module'] = 'orders_status';
    $row['subtype'] = $os_row['account_class'];
    $row['enabled'] = (array_key_exists('orders_status', $status_select) && in_array($os_row['account_class'], $status_select['orders_status'])? true: false);
    $status_rows[] = $row;
  }
                                                                                                                                              
  $status_rows[] = array('text'=>BOX_FUNDS_INVOICES, 'module'=>'invoices', 'subtype'=>'0', 'enabled'=>(array_key_exists('invoices', $status_select)? true: false));
  $status_rows[] = array('text'=>BOX_FUNDS_STOCKVALUE, 'module'=>'stock', 'subtype'=>'0', 'enabled'=>(array_key_exists('stock', $status_select)? true: false));
  $status_rows[] = array('text'=>BOX_FUNDS_CASHBOX, 'module'=>'funds', 'subtype'=>'0', 'enabled'=>(array_key_exists('funds', $status_select) && in_array('0', $status_select['funds'])? true: false));

?>

<?php
  $sum = 0;
  $output_rows = array();

  foreach ($status_rows as $row) {
    if ($row['enabled']) {
      switch ($row['module'])
      {
        
        
          
           case 'orders_status':
          $query = "select sum(sum) as value ".
          
          "from " .TABLE_ACCOUNTING ." where receiver = '".$row['subtype'].' '.$row['text']. "' ";
          
        
        
//         case 'orders_status':
//           $query = "select sum(op.final_price*op.products_quantity) as value ".
//             "from " .TABLE_ORDERS ." as o inner join ".TABLE_ORDERS_PRODUCTS." op ".
//             "using (orders_id) ".
//             "where o.orders_status = '" .$row['subtype'] ."' and o.webshop = '".WEBSHOP_ID."'";
          
          
          break;
        case 'invoices':
          $query = "select -sum(sum) as value from " .TABLE_INVOICES ." where paid is null";
          break;
        case 'funds':
          $query = "select sum as value from ". TABLE_FUNDS ." where type = '" .$row['subtype'] ."' order by funds_id desc limit 1";
          break;
        case 'stock':
          $query = "select count(distinct sp.product_id)*min(p.cost_price) as value ".
            "from ".TABLE_STOCK_PRODUCTS." sp inner join ".TABLE_PRODUCTS." p on (sp.code = p.products_model) ".
            "where sp.out_date is null group by sp.code";
          break;
      }
      $result = tep_db_query ($query);
      if (in_array($row['module'], array('orders_status', 'invoices', 'funds'))) {
        $value = tep_db_result ($result, 0, 'value');
      } else if ($row['module'] == 'stock') {
        $value = 0;
        while ($_data = tep_db_fetch_array($result)) 
          $value += $_data['value'];
      }
      if ($value == "") $value = 0;
      $sum += $value;
      ?>
              <tr class="dataTableRow">
                <td class="main" nowrap><?php echo $row['text']; ?></td>
                <td class="main" align="right"><?php echo $currencies->format($value); ?></td>
              </tr>
      <?php
    }
  }
?>
              <tr>
                <td colspan="2" class="dataTableRow"><?php echo tep_draw_separator(); ?></td>
              </tr>
              <tr class="dataTableRow">
                <td>&nbsp;</td>
                <td class="main" align="right"><b><?php echo $currencies->format($sum); ?></b></td>
              </tr>
              <tr>
                <td><?php echo tep_draw_separator('pixel_trans.gif', 1, 10); ?></td>
              </tr>
              <tr>
                <td class="smallText" colspan="2"><?php echo 'Accounts'; ?></td>
              </tr>
            </table></td>
            <td valign="top" align="center"><table border="0" cellpadding="2" cellspacing="0">
<?php
  foreach ($status_rows as $row) {
    ?>
              <tr>
                <td class="main" nowrap><?php echo $row['text']; ?></td>
                <td nowrap>
    <?php
    if ($row['enabled']) {
      echo tep_image(DIR_WS_IMAGES . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN, 10, 10) ." ";
      echo '<a href="' . tep_href_link(FILENAME_ACCOUNTING_PRINT, tep_get_all_get_params(array('select', 'module', 'subtype')) ."select=0&amp;module=" .$row['module'] ."&amp;subtype=" .$row['subtype']) .'">' .tep_image(DIR_WS_IMAGES . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED, 10, 10) ."</a>";
    } else {
      echo '<a href="' . tep_href_link(FILENAME_ACCOUNTING_PRINT, tep_get_all_get_params(array('select', 'module', 'subtype')) ."select=1&amp;module=" .$row['module'] ."&amp;subtype=" .$row['subtype']) .'">' .tep_image(DIR_WS_IMAGES . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN, 10, 10) ."</a> ";
      echo tep_image(DIR_WS_IMAGES . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED, 10, 10) ." ";
    }
    ?>
                </td>
              </tr>
    <?php
  }
?>
      
      
      
      
      
      
</tbody>
</table>

</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>