<?php
ini_set('display_errors',1);
ini_set('memory_limit', '-1');
if (!$_REQUEST['settings'] || $_REQUEST['settings']=="")
	die('Błąd parametrów');

$tmp = base64_decode($_REQUEST['settings']);
$settings = objectToArray(json_decode($tmp));
global $timedate; 

class export{
    
    public $db;
    public $moduleName;
    public $moduleObject;
    public $table;
    public $where;
    public $query;
    public $modules;
    public $fieldsListForModule;
    public $fp;
    public $filename;
    public $order;
    public $direction;
    public $ids;
    
    public function __construct($module,$table,$where,$ids,$order,$direction) {
        
        $this->db=$GLOBALS['db'];
        $this->table=$table;
        $this->where=$where;
        $this->moduleName=$module;
        $this->ids=$ids;
        $this->order=$order;
        $this->direction=$direction;
        $this->moduleObject=$this->constructObject();
        $this->modules=$this->setModules();
      
    }

    public function setModules(){
        $tmp=array();
        // bez dodatkowej tabeli
        $tmp[0][]='Accounts';
        $tmp[0][]='EcmProducts';     
        // z dodatkową tabelą  
          
        return $tmp;
    }
    
    public function constructObject(){
        if($this->moduleName!=''){
          $moduleObject=substr($this->moduleName, 0, -1);
          $this->moduleObject=new $moduleObject ();  
        }
        
      
    }
    
    public function setHeader($header){
        if($this->moduleName=='Accounts'){
            $name='lista_kontrahentow_'.date('d_m_y');
        }
        if($this->moduleName=='EcmProducts'){
            $name='lista_produktow_'.date('d_m_y');
        }
        if($this->moduleName=='EcmQuotes'){
            $name='lista_ofert_'.date('d_m_y');
        }
        if($this->moduleName=='EcmInvoiceOuts'){
            $name='lista_faktur_'.date('d_m_y');
        }
        if($this->moduleName=='EcmSales'){
            $name='lista_zamowien_sprzedazy'.date('d_m_y');
        }
         if($this->moduleName=='EcmPrepaymentInvoices'){
            $name='lista_faktur_zaliczkowych_'.date('d_m_y');
        }
           if($this->moduleName=='EcmPrepaymentInvoices'){
            $name='lista_faktur_zaliczkowych_'.date('d_m_y');
        }
             if($this->moduleName=='EcmAgreemets'){
            $name='lista_umow_'.date('d_m_y');
        }
             if($this->moduleName=='EcmWorkers'){
            $name='lista_prcownikow_'.date('d_m_y');
        }
             if($this->moduleName=='Documents'){
            $name='lista_dokumentow_'.date('d_m_y');
        }
        
               if($this->moduleName=='EcmPurchaseOrders'){
            $name='lista_zamowien_zakupu_'.date('d_m_y');
        }
             if($this->moduleName=='EcmPaymentStates'){
            $name='lista_sald_'.date('d_m_y');
        }
        
        
        
        $this->filename='modules/Home/Files/'.$name.'.csv';
        $this->fp=fopen($this->filename,'w');
          foreach ($header as $k=>$v){
             $header[$k]=iconv('UTF-8','windows-1250',$header[$k]);;
        }
        fwrite($this->fp, implode(";",$header).PHP_EOL);
    }
    
    public function writeLine($lines){
      
         foreach ($lines as $k=>$v){
             if(gettype($lines[$k])=='integer' || gettype($lines[$k])=='float' || gettype($lines[$k])=='double'){
                 $lines[$k]=str_replace(".",",",number_format($lines[$k], 2, '.', ''));   
             } else {
              
                 $lines[$k]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:@.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',$lines[$k]));
                 $lines[$k]='"=""'.$lines[$k].'"""';
   
             }
             $lines[$k]=iconv('UTF-8//IGNORE','windows-1250',$lines[$k]);
        }

        fwrite($this->fp, implode(";",$lines).PHP_EOL);
    }
    public function getResults(){
        
       if($this->moduleName=='Accounts'){
           
           
           global $app_list_strings;
           $header = array();
           $header[]='nazwa';
           $header[]='ulica';
           $header[]='kod';
           $header[]='nip';
           $header[]='główny email';
           $header[]='telefon';
           $header[]='regon';
           $header[]='rodzaj kontrahenta';
           $header[]='imie nazwisko kontaktu';
           $header[]='numer kontaktu';
           $header[]='email kontaktu';
           $this->setHeader($header);
           
           if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
            
                if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
               
           
          
           $this->query='SELECT id,name,register_address_street,concat(register_address_postalcode,", ",register_address_city) as inndex_dbf,to_vatid,phone_office as email1, phone_office,regon,account_type FROM '.$this->table.' WHERE  deleted=0'.$where.'  ';
    
           $z=$this->db->query($this->query);
  $i=1;
        $ac = new Account();
       $c = new Contact();
           while($dane=$this->db->fetchByAssoc($z)){
          
    
               $ac->retrieve($dane['id']);
              
               $dane['name']=  html_entity_decode($dane['name']);
               $dane['index_dbf']=  html_entity_decode($dane['index_dbf']);
               $dane['email1']=$ac->email1;
               $dane['account_type']=$app_list_strings['account_type_dom'][$dane['account_type']];
               $query2="select contact_id from accounts_contacts where deleted=0 and account_id='".$dane['id']."'";
               $z2=$this->db->query($query2);
           
               $dane['osoba']='';
                $dane['telefon']=''; 
                 $dane['email']='';
              
                 
               if($z2->num_rows>0){
   
                while($dane2=$this->db->fetchByAssoc($z2)){
                    
               
                    $c->retrieve($dane2['contact_id']);
                  $dane['osoba']=$c->first_name." ".$c->last_name;
                  $dane['telefon']=$dane2['phone_mobile'];
                  $dane['email']=$c->email1;

                  unset($dane['id']);
                  $this->writeLine($dane);
                
                }
               } else {
                     unset($dane['id']);
                   $this->writeLine($dane);
               }
      
               $i++;
               }
           header('Location: '. $this->filename);
         
           
       }
       
       if($this->moduleName=='EcmProducts'){
           global $app_list_strings;
           $header = array();
           $header[]='nazwa';
           $header[]='indeks';
           $header[]='grupa';
           $header[]='jednostka miary';

           $this->setHeader($header);
         if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
              if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
           $this->query='SELECT id,name,code,ks_group,unit_id FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
   
           while($dane=$this->db->fetchByAssoc($z)){
              
             $ac = new EcmProduct();
               $ac->retrieve($dane['id']);
               $dane['name']=  html_entity_decode($dane['name']);
               $dane['code']=  html_entity_decode($dane['code']);
               $dane['ks_group']=  $app_list_strings['ecmproducts_group_ks_dom'][$dane['ks_group']];
               $dane['unit_id']=  $app_list_strings['ecmproducts_unit_dom'][$dane['unit_id']];

                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
       if($this->moduleName=='EcmQuotes'){
           global $app_list_strings;
           $header = array();
           $header[]='numer oferty';
           $header[]='data';
           $header[]='kontrahent';
           $header[]='Wartość netto';
           $header[]='Wartość vat';
           $header[]='Wartość brutto';

           $this->setHeader($header);
           if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
         if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
          
           $this->query='SELECT id,document_no,register_date,parent_name,total_netto,vats_summary,total_brutto FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
   
           while($dane=$this->db->fetchByAssoc($z)){
               $dane['total_netto']=(float)$dane['total_netto'];
                $dane['total_brutto']=(float)$dane['total_brutto'];
                    $arr=  explode(':', $dane['vats_summary']);
                $dane['vats_summary']=(float)  str_replace(',', '', $arr[1]);
             $ac = new EcmProduct();
               $ac->retrieve($dane['id']);
               $dane['parent_name']=  html_entity_decode($dane['parent_name']);
                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
       if($this->moduleName=='EcmSales'){
           global $app_list_strings;
           $header = array();
           $header[]='data';
           $header[]='numer';
           $header[]='kontrahent';
           $header[]='Wartość netto';
           $header[]='Wartość vat';
           $header[]='Wartość brutto';
           $header[]='data realizacji';
           $header[]='status';

           $this->setHeader($header);
          if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
           if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
          
           $this->query='SELECT id,register_date,document_no,parent_name,total_netto,vats_summary,total_brutto,delivery_date,status FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
   
           while($dane=$this->db->fetchByAssoc($z)){
               $dane['total_netto']=(float)$dane['total_netto'];
                $dane['total_brutto']=(float)$dane['total_brutto'];
                $arr=  explode(':', $dane['vats_summary']);
                $dane['vats_summary']=(float)  str_replace(',', '', $arr[1]);
             $ac = new EcmProduct();
               $ac->retrieve($dane['id']);
                $dane['parent_name']=  html_entity_decode($dane['parent_name']);
                $dane['status']=$app_list_strings['ecmsales_status_dom'][$dane['status']];
                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
       if($this->moduleName=='EcmInvoiceOuts'){
           global $app_list_strings;
           $header = array();
           $header[]='typ';
           $header[]='numer';
           $header[]='kontrahent';
           $header[]='data';
           $header[]='netto';
           $header[]='vat';
           $header[]='brutto';
           $header[]='status';
           $header[]='nazwa produktu';
           $header[]='ilość';
           $header[]='jednostka miary';
           $header[]='cena netto';
           $header[]='stawka vat';
           $header[]='cena brutto';
           $header[]='wartość netto';
           $header[]='wartość vat';
           $header[]='wartość brutto';
           
           $this->setHeader($header);
           if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
             if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
           $this->query='SELECT id,type,document_no,parent_name,register_date,total_netto,total_vat,total_brutto,canceled as status FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
         
           while($dane=$this->db->fetchByAssoc($z)){
               $dane['total_netto']=(float)$dane['total_netto'];
                $dane['total_brutto']=(float)$dane['total_brutto'];
                $dane['total_vat']=(float)$dane['total_vat'];
               if($dane['type']=='normal'){
                   $dane['type']='faktura';
               } else {
                   $dane['type']='korekta';
               }
               $t = new EcmTransaction();
               $t->retrieve_by_string_fields(array('record_id' =>$dane['id']));
            if($t->settled==1){
            	$dane['status']='rozliczona';
            } else {
            	$v=$t->getRelations();
            	if($v==$t->value){
            		$dane['status']='nierozliczona';
            		
            	} else {
            		$dane['status']='pozostało do zapłaty';
            	}
            }
             
                 $dane['parent_name']=  html_entity_decode($dane['parent_name']);
                 $query2="select * from ecminvoiceoutitems where ecminvoiceout_id='".$dane['id']."'";
         
                 $z2=$this->db->query($query2);
                 
                 while($dane2=$this->db->fetchByAssoc($z2)){
                     $dane['product_name']=$dane2['name'];
                     $dane['quantity']=(float)$dane2['quantity'];
                     $dane['unit_name']=$dane2['dd_unit_name'];
                     $dane['price_netto2']=(float)$dane2['price_netto'];
                     $dane['vat_name']=$dane2['ecmvat_name'];
                     $dane['price_brutto2']=(float)$dane2['price_brutto'];
                     $dane['total_netto2']=(float)$dane2['total_netto'];
                     $dane['total_vat2']=(float)$dane2['total_vat'];
                     $dane['total_brutto2']=(float)$dane2['total_brutto'];
                         unset($dane['id']);
                   $this->writeLine($dane);
                 }
                 
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
          if($this->moduleName=='EcmPrepaymentInvoices'){
           global $app_list_strings;
           $header = array();
           $header[]='numer';
           $header[]='kontrahent';
           $header[]='data';
           $header[]='netto';
           $header[]='vat';
           $header[]='brutto';
           $header[]='status';

           $this->setHeader($header);
           if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
             if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
          
           $this->query='SELECT id,document_no,parent_name,register_date,total_netto,total_vat,total_brutto FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
   
           while($dane=$this->db->fetchByAssoc($z)){
              
         $dane['total_netto']=(float)$dane['total_netto'];
                $dane['total_brutto']=(float)$dane['total_brutto'];
                 $dane['total_vat']=(float)$dane['total_vat'];
                $dane['parent_name']=  preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($dane['parent_name']));
              $dane['status']='aktywna';
                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
        if($this->moduleName=='EcmPurchaseOrders'){
           global $app_list_strings;
           $header = array();
           $header[]='numer';
           $header[]='data dokumentu';
           $header[]='kontrahent';
           $header[]='netto';
           $header[]='vat';
           $header[]='brutto';
           $header[]='data dostawy';

           $this->setHeader($header);
         if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
             if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
          
           $this->query='SELECT id,document_no,register_date,parent_name,total_netto,total_netto as vat,total_netto as brutto,delivery_date FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
   
           while($dane=$this->db->fetchByAssoc($z)){
                       $query2="select * from ecmpurchaseorderitems where ecmpurchaseorder_id='".$dane['id']."'";
         
                 $z2=$this->db->query($query2);
                 $total_netto=0;
                 $total_vat=0;
                 $total_brutto=0;
        while($dane2=$this->db->fetchByAssoc($z2)){
            $total_netto+=$dane2['total_netto'];
                 $total_vat+=($dane2['total_netto']*$dane2['ecmvat_value'])/100;
                 $total_brutto+=(($dane2['total_netto']*$dane2['ecmvat_value'])/100)+$dane2['total_netto'];
        }
        $dane['total_netto']=$total_netto;
        $dane['vat']=$total_vat;
        $dane['brutto']=$total_brutto;
        if($dane['delivery_date']!=''){
             $dane['delivery_date']=date('Y-m-d',strtotime($dane['delivery_date']));
        }
       
                $dane['parent_name']=  preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($dane['parent_name']));
          
                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
              if($this->moduleName=='EcmAgreements'){
           global $app_list_strings;
           $header = array();
           $header[]='data';
           $header[]='kontrahent';
           $header[]='numer';

           $this->setHeader($header);
           if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
               if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
          
           $this->query='SELECT id,register_date,parent_id as parent_name,document_no FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
   
           while($dane=$this->db->fetchByAssoc($z)){
              $a = new Account();
              $a->retrieve($dane['parent_name']);
             $dane['parent_name']= preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($a->name));
              
                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
       if($this->moduleName=='EcmWorkers'){
           global $app_list_strings;
           $header = array();
           $header[]='imię';
           $header[]='nazwisko';
           $header[]='data urodzenia';
           $header[]='pesel';
           $header[]='dowód osobisty seria i numer';
           $header[]='adres zameldowania';
           $header[]='adres zamieszkania';
           $header[]='numer telefonu służbowy';
           $header[]='numer telefonu prywatny';
           $header[]='stan cywilny';
           $header[]='urząd skarbowy';
           $header[]='data zatrudnienia';
           $header[]='nazwa stanowiska';
           $header[]='numer konta bankowego';

           $this->setHeader($header);
            if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
           
           if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
          
           $this->query='SELECT id,first_name,last_name,birthday,pesel,person_id_series_number,concat(primary_address_city ," ", primary_address_postalcode," ", primary_address_street) as adr,concat(alt_address_city ," ", alt_address_postalcode," ", alt_address_street) as adr2,phone_work,phone_mobile,marital_status,inland_revenue,date_employment,position_office,bank_account_number FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
   
           while($dane=$this->db->fetchByAssoc($z)){
              $a = new Account();
              $a->retrieve($dane['parent_name']);
             $dane['parent_name']=  preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($a->name));
              
                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       
       if($this->moduleName=='Documents'){
           global $app_list_strings;
           $header = array();
           $header[]='data';
           $header[]='kontrahent';
           $header[]='numer';
           $header[]='kategoria';
           $header[]='netto';
           $header[]='vat';
           $header[]='brutto';
           $header[]='termin płatności'; 
           $header[]='status';

           $this->setHeader($header);
           if(strlen($this->where)>0){
               $this->where=str_replace("like '","like '%",$this->where);
               $where=' and '.$this->where;
           }
           if( $_SESSION[$this->moduleName.'_order']!=''){
                    $where.=' order by '.$_SESSION[$this->moduleName.'_order'];
                }
          
           $this->query='SELECT id,document_date,document_name as parent_name,document_name,category_id,value as netto,value as vat,value as brutto,payment_date,status_id FROM '.$this->table.' WHERE  deleted=0'.$where;
      
           $z=$this->db->query($this->query);
           
           while($dane=$this->db->fetchByAssoc($z)){ 
              
               $d = new Document();
               $dane['category_id']=  $app_list_strings['document_category_dom'][$dane['category_id']];
               $dane['transaction_type']=  $app_list_strings['transaction_type3_dom'][$dane['transaction_type']];
               $t = new EcmTransaction();
               $t->retrieve_by_string_fields(array('record_id' =>$dane['id']));
               if($t->settled==1){
               	$dane['status']='rozliczona';
               } else {
               	$v=$t->getRelations();
               	if($v==$t->value){
               		$dane['status']='nierozliczona';
               
               	} else {
               		$dane['status']='pozostało do zapłaty';
               	}
               }
                $dane['parent_name']=  html_entity_decode($dane['parent_name']);
                $query2="select * FROM documents_accounts WHERE document_id='" . $dane['id'] . "' and parent_type='Account' limit 1";
                 $dane['netto']=  '';
                         $dane['vat']= '';
                $z2=$this->db->query($query2);
                    while($dane2=$this->db->fetchByAssoc($z2)){
                        $a = new Account();
                        $a->retrieve($dane2['parent_id']);
                        $dane['parent_name']= preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($a->name));
                    }
                    $dane['brutto']=(float)  $dane['brutto'];
                      $query2="select * FROM documents_vat WHERE document_id='" . $dane['id'] . "' and netto>0";
                $z2=$this->db->query($query2);
             
                    while($dane2=$this->db->fetchByAssoc($z2)){

                        $dane['netto']=(float)  $dane2['netto'];
                         $dane['vat']=(float)  $dane2['vat'];
                           $dane['brutto']=(float)  $dane['brutto'];
                    }
                     unset($dane['id']);
                   $this->writeLine($dane);
               
           }
           header('Location: '. $this->filename);
         
           
       }
       if($this->moduleName=='EcmPaymentStates'){
           global $app_list_strings;
           $header = array();
           $header[]='rodzaj kontrahenta';
           $header[]='kontrahent';
           $header[]='saldo winien';
           $header[]='nazwa';
           $header[]='data płatności';
            $header[]='wartość';
           $header[]='saldo ma';
           $header[]='nazwa';
           $header[]='data płatności';
           $header[]='wartość';
            $header[]='numer konta bankowego';
           $this->setHeader($header);
          

           $this->query="SELECT id,account_type,name from accounts where id in('".implode("','",$this->ids)."')";
      
           $z=$this->db->query($this->query);

           while($dane=$this->db->fetchByAssoc($z)){
              $a = new Account();
              $a->retrieve($dane['parent_name']);
              
              $dane['account_type']=$app_list_strings['account_type_dom'][$dane['account_type']];
             $dane['name']= preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($dane['name']));
                      $query_w="
                SELECT * FROM ecmtransactions 
                WHERE deleted='0' AND 
                parent_id='".$dane['id']."' 
                AND type='0' 
                ORDER BY payment_date desc";
        $query_ma="
                SELECT * FROM ecmtransactions
                WHERE deleted='0' AND
                parent_id='".$dane['id']."'
                AND type='1'
                ORDER BY payment_date desc";
        
        // winien start
        
        
$res = $this->db->query($query_w);
$total_winien = 0;
global $timedate; 
$winien = array();
$totals_w['wartosc']=0;
$totals_w['roz']=0;
$totals_w['nie']=0;
while ($r = $this->db->fetchByAssoc($res)) {

	$tmp = array();
	$tmp['settled_with'] = array();
	$total_settled = 0;
	if($umowa_id!=''){
	    if($r['record_id']!=$umowa_id){
	        if($r['record_type']=='EcmInvoiceOuts'){
	            $m= new EcmInvoiceOut();
	            $m->retrieve($r['record_id']);
	            if($m->ecmagreement_id!=$umowa_id){
	                continue;
	            }
	        } else {
	            $rel = $this->db->query("SELECT * FROM ecmtransactions_rel WHERE ecmtransaction_a_id='".$r['id']."' OR ecmtransaction_b_id='".$r['id']."'");
	            $skip=true;
	            while ($rr = $this->db->fetchByAssoc($rel)) {
    	              	if ($rr['ecmtransaction_a_id'] == $r['id'])
                			$rel_id = $rr['ecmtransaction_b_id'];
                		else 
                			$rel_id = $rr['ecmtransaction_a_id'];
                		$t = $this->db->fetchByAssoc($this->db->query("SELECT * FROM ecmtransactions WHERE id='$rel_id'"));
                		
                		if($t['record_type']=='EcmInvoiceOuts'){
                		    $m= new EcmInvoiceOut();
                		    $m->retrieve($t['record_id']);
                		    if($m->ecmagreement_id==$umowa_id){
                		        $skip==false;
                		    }
                		} else {
                		
                		if($t['record_id']==$umowa_id){
                		    $skip=false;
                		}
                		}
	            }
	            if($skip==true){
	        continue;
	            } 
	        }
	    }
	}
	$rel = $this->db->query("SELECT * FROM ecmtransactions_rel WHERE ecmtransaction_a_id='".$r['id']."' OR ecmtransaction_b_id='".$r['id']."'");
	while ($rr = $this->db->fetchByAssoc($rel)) {

		if ($rr['ecmtransaction_a_id'] == $r['id'])
			$rel_id = $rr['ecmtransaction_b_id'];
		else 
			$rel_id = $rr['ecmtransaction_a_id'];
		$t = $this->db->fetchByAssoc($this->db->query("SELECT * FROM ecmtransactions WHERE id='$rel_id'"));
			$tmp2 = array();
			$tmp2['name'] = $t['name'];
			$tmp2['trans_id'] = $t['id'];
			$tmp2['value']=$rr['value'];
			if($t['type']==0 && $rel->num_rows==1){
			   
			    if(abs($rr['value'])==abs($r['value'])){
			     if($r['value']>0){
			        $rr['value']=abs($rr['value']);
			     } else {
			         $v = -1 * abs( $rr['value']);
			         $rr['value']=$v;
			     }
			    } else {
			        $rr['value']=abs($rr['value']);
			    }
			} else {

			    if(abs($rr['value'])==abs($r['value'])){
			        if($r['value']>0){
			            $rr['value']=abs($rr['value']);
			        } else {
			            $v = -1 * abs( $rr['value']);
			            $rr['value']=$v;
			        }
			    } else {
			        if($r['value']>0){
			            $rr['value']=abs($rr['value']);
			        }
			    }
			}
		$tmp['settled_with'][] = $tmp2;	 
		$total_settled+=floatval($rr['value']);
	}

	//date comparsion
	if ($r['settled'] == '1') {
		$d1 = new DateTime($r['register_date']);
		$d2 = new DateTime($change_date);
		if ($d1 < $d2)
			$total_settled = $r['value'];
	} else $r['settled'] = '0'; //prevent null
	
	
	$tmp['register_date'] = $timedate->to_display_date($r['payment_date']);
	if($r['record_type']!=''){
	    $module=substr($r['record_type'],0,strlen($r['record_type'])-1);
	    $m = new $module();

	    $m->retrieve($r['record_id']);

	    $add=' z dnia '.date('d.m.Y',strtotime($m->register_date));
	} else {
	    $add='';
	}
	$tmp['document_no'] = $r['name'];
	$tmp['total'] =(float) ($r['value']);
	$tmp['settled'] =(float) ($total_settled);
	$totals_w['wartosc']+=$r['value'];
	$totals_w['roz']+=$total_settled;
	$totals_w['nie']+=floatval(unsettledValue($total_settled,$r['value']));
	if($r['settled']==1){
	    if($_REQUEST['switch_show']==1){
	        $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);
	        $total_winien+=floatval($r['value']);
	      
	    } else {
    	    $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);
    	    $total_winien+=floatval(unsettledValue($total_settled,$r['value']));
	    }
	}else{
	    if($_REQUEST['switch_show']==1){
	 $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);
	        $total_winien+=floatval($r['value']);
	     
	    } else {
	       $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);
    	    $total_winien+=floatval(unsettledValue($total_settled,$r['value']));
	    }
	}
$tmp['name'] = $r['name'];
	$tmp['id'] = $r['id'];
	$tmp['sort_date']=date('Ymd',strtotime($r['payment_date']));
	$tmp['note']= $r['note'];
	$tmp['type']='0';
	$tmp['note_id']= $r['note_id'];
	$tmp['is_settled'] = $r['settled'];
	$winien[] = $tmp;
	
	
}
        //winien end


$res = $this->db->query($query_ma);
$ma = array();
$total_ma = 0;
$totals_m['wartosc']=0;
while ($r = $this->db->fetchByAssoc($res)) {
	$tmp = array();
	$tmp['settled_with'] = array();
	$total_settled = 0;
	if($umowa_id!=''){
	    if($r['record_id']!=$umowa_id){
	        if($r['record_type']=='EcmInvoiceOuts'){
	            $m= new EcmInvoiceOut();
	            $m->retrieve($r['record_id']);
	            if($m->ecmagreement_id!=$umowa_id){
	                continue;
	            }
	        } else {
	            $rel = $this->db->query("SELECT * FROM ecmtransactions_rel WHERE ecmtransaction_a_id='".$r['id']."' OR ecmtransaction_b_id='".$r['id']."'");
	            $skip=true;
	            while ($rr = $this->db->fetchByAssoc($rel)) {
	                if ($rr['ecmtransaction_a_id'] == $r['id'])
	                    $rel_id = $rr['ecmtransaction_b_id'];
	                else
	                    $rel_id = $rr['ecmtransaction_a_id'];
	                $t = $this->db->fetchByAssoc($this->db->query("SELECT * FROM ecmtransactions WHERE id='$rel_id'"));
	
	                if($t['record_type']=='EcmInvoiceOuts'){
	                    $m= new EcmInvoiceOut();
	                    $m->retrieve($t['record_id']);
	                    if($m->ecmagreement_id==$umowa_id){
	                        $skip==false;
	                    }
	                } else {
	
	                    if($t['record_id']==$umowa_id){
	                        $skip=false;
	                    }
	                }
	            }
	            if($skip==true){
	                continue;
	            }
	        }
	    }
	}
	$rel = $this->db->query("SELECT * FROM ecmtransactions_rel WHERE ecmtransaction_a_id='".$r['id']."' OR ecmtransaction_b_id='".$r['id']."'");
	while ($rr = $this->db->fetchByAssoc($rel)) {
		if ($rr['ecmtransaction_a_id'] == $r['id'])
			$rel_id = $rr['ecmtransaction_b_id'];
		else
			$rel_id = $rr['ecmtransaction_a_id'];
		$t = $this->db->fetchByAssoc($this->db->query("SELECT * FROM ecmtransactions WHERE id='$rel_id'"));
		$tmp2 = array();
		$tmp2['name'] = $t['name'];
		$tmp2['trans_id'] = $t['id'];
		$tmp2['value']=$rr['value'];
		if($t['type']==0 && $rel->num_rows==1){
		
		    if(abs($rr['value'])==abs($r['value'])){
		        if($r['value']>0){
		            $rr['value']=abs($rr['value']);
		        } else {
		            $v = -1 * abs( $rr['value']);
		            $rr['value']=$v;
		        }
		    }
		}else {
			        $rr['value']=abs($rr['value']);
			    }
		$tmp['settled_with'][] = $tmp2;
		$total_settled+=floatval($rr['value']);
	}
	
	
	//date comparsion
	if ($r['settled'] == '1') {
		$d1 = new DateTime($r['register_date']);
		$d2 = new DateTime($change_date);
		if ($d1 < $d2)
			$total_settled = $r['value'];
	} else $r['settled'] = '0'; //prevent null
	
	$tmp['register_date'] = $timedate->to_display_date($r['payment_date']);
	if($r['record_type']!=''){
	    $module=substr($r['record_type'],0,strlen($r['record_type'])-1);
	    $m = new $module();
	
	    $m->retrieve($r['record_id']);
	
	    $add=' z dnia '.date('d.m.Y',strtotime($m->register_date));
	} else {
	    $add='';
	}
	$tmp['sort_date']=date('Ymd',strtotime($r['payment_date']));
	$tmp['name'] = $r['name'];
	$tmp['total'] = (float)($r['value']);
	$tmp['settled'] = (float)($total_settled);
	$totals_m['wartosc']+=$r['value'];
	$totals_m['roz']+=$total_settled;
	$totals_m['nie']+=floatval(unsettledValue($total_settled,$r['value']));
	if($r['settled']==1){
	    if($_REQUEST['switch_show']==1){
	        $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);
	     
	        $total_ma+=floatval($r['value']);
	    } else {
	   $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);
	   $total_ma+=floatval(unsettledValue($total_settled,$r['value']));
	    }
        //$tmp['unsettled'] = format_number(abs($r['value'])-$total_settled); echo 'rozliczone';
	}else{
	    if($_REQUEST['switch_show']==1){
	 $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);

	        $total_ma+=floatval($r['value']);
	    } else {
	    	   $tmp['unsettled'] =  unsettledFormatValue($total_settled,$r['value']);
	   $total_ma+=floatval(unsettledValue($total_settled,$r['value']));
	    }
	}
	$tmp['is_settled'] = $r['settled'];
	$tmp['type']='1';
	$tmp['id'] = $r['id'];
	$ma[] = $tmp;
	
	//$total_ma+=floatval($r['value']);
}

echo count($ma).' ';
echo count($winien);
if(count($winien)>=count($ma)){
    foreach ($winien as $key=>$val){
        $dane['saldo_w']=$totals_w['wartosc'];
        $dane['nazwa']=$winien[$key]['name'];
         $dane['data']=$winien[$key]['register_date'];
          $dane['kwota']=$winien[$key]['total'];
        $dane['saldo_ma']=$totals_m['wartosc'];
         $dane['nazwa2']=$ma[$key]['name'];
         $dane['data2']=$ma[$key]['register_date'];
          $dane['kwota2']=$ma[$key]['total'];
             unset($dane['id']);
             $dane['bank']=$a->getFirstBankAccount();
                   $this->writeLine($dane);
    }
} else {
        foreach ($ma as $key=>$val){
        $dane['saldo_w']=$totals_w['wartosc'];
        $dane['nazwa']=$winien[$key]['name'];
         $dane['data']=$winien[$key]['register_date'];
          $dane['kwota']=$winien[$key]['total'];
        $dane['saldo_ma']=$totals_m['wartosc'];
                $dane['nazwa2']=$ma[$key]['name'];
         $dane['data2']=$ma[$key]['register_date'];
          $dane['kwota2']=$ma[$key]['total'];
             unset($dane['id']);
                  $dane['bank']=$a->getFirstBankAccount();
                   $this->writeLine($dane);
    }
}


      
               
           }
           header('Location: '. $this->filename);
         
           
       }
    }
}
$EcmSysInfo = new EcmSysInfo();
	if($EcmSysInfo->getDatabaseName() != 'preDb_5d9477918f845c6fdc25532d415f9e73'){
		if($_REQUEST['accounts_xls_id']){
		
			$ex= New export('EcmPaymentStates',$settings['table'],'',$_REQUEST['accounts_xls_id']);
		
			$ex->getResults();
		} else {
			$ex= New export($settings['module'],$settings['table'],base64_decode($settings['where']),'',$settings['order'],$settings['direction']);
		
			$ex->getResults();
		}
	}


/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function vd($v, $die = false) {
	echo '<pre>'; var_dump($v); echo '</pre>';
	if ($die == true) die();
}
function objectToArray($d) {
	if (is_object($d)) {
		// Gets the properties of the given object
		// with get_object_vars function
		$d = get_object_vars($d);
	}

	if (is_array($d)) {
		/*
		 * Return array converted to object
		 * Using __FUNCTION__ (Magic constant)
		 * for recursive call
		 */
		return array_map(__FUNCTION__, $d);
	}
	else {
		// Return array
		return $d;
	}
}


function array_sort_by_key($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
                break;
            case SORT_DESC:
                arsort($sortable_array);
                break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}
function unsettledFormatValue($settled,$val){
    if($settled<0 && $val>0){
        return format_number($val+$settled);
    }
    if($settled<0 && $val<0){
        return format_number($val+abs($settled));
    }
    if($settled>0 && $val>0){
        return format_number($val-abs($settled));
    }
    if($settled>0 && $val<0){
        return format_number($val+$settled);
    }
    if($settled==0 && $val<0){
        return format_number($val);
    }
    if($settled==0 && $val>0){
        return format_number($val);
    }
}

function getAgreements($id){
    $db=$GLOBALS['db'];  
    $zap="select id,document_no from ecmagreements where parent_id='".$id."' and deleted=0";
    $res=$db->query($zap);

    $as=array();
    while($dane=$db->fetchByAssoc($res)){

        $as[]=$dane;
    } 
    return $as;
}

function unsettledValue($settled,$val){
    if($settled<0 && $val>0){
        return ($val+$settled);
    }
    if($settled<0 && $val<0){
        return ($val+abs($settled));
    }
    if($settled>0 && $val>0){
        return ($val-abs($settled));
    }
    if($settled>0 && $val<0){
        return ($val+$settled);
    }
    return $val;
}
function getEmails ($id)
{
    $sea = new SugarEmailAddress();
    $addresses = $sea->getAddressesByGUID($id, 'Accounts');
    $return = array();
    foreach ($addresses as $address) {
        if ($address['email_address'] != '' && $address['opt_out'] == 1) {
            $return[] = $address['email_address'];
        }
    }
    return $return;
}