<?php 
// helper functions
function getData2($id, $expired) {
    $db = $GLOBALS ['db'];

    $saldo = false;
    $settled = " t.settled!='1' AND ";
    switch ($expired) {
        case 1 :
            $date = new DateTime ( date ( "Y-m-d" ) );
            $d = $date->format ( 'Y-m-d' );
            $payment_date = " payment_date <= '$d'";
            break;
        case 2 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-30 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date >= '$d_f' AND payment_date < '$d_t'";
            break;
        case 3 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $date_to->modify ( '-31 days' );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-60 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date >= '$d_f' AND payment_date <= '$d_t'";
            break;
        case 4 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $date_to->modify ( '-61 days' );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-90 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date >= '$d_f' AND payment_date <= '$d_t'";
            break;
        case 5 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $date_to->modify ( '-91 days' );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-180 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date >= '$d_f' AND payment_date <= '$d_t'";
            break;
        case 6 :
            $date = new DateTime ( date ( "Y-m-d" ) );
            $date->modify ( '-181 days' );
            $d = $date->format ( 'Y-m-d' );
            $payment_date = " payment_date <= '$d'";
            break;
        case 9:
            $date = new DateTime ( date ( "Y-m-d" ) );
            $d = $date->format ( 'Y-m-d' );
            $payment_date = " payment_date <= '$d'";
            $settled = " ";
            $saldo = true;
            break;
    }
    //start WINIEN
    if($_REQUEST['account_type']=='rec')$typ=0;else $typ=1;
    $zap= $db->query ( "
            SELECT
            (
            t.value

    ) AS value,t.id
            FROM ecmtransactions AS t
            left JOIN ecmtransactions_rel AS rel
            ON (rel.ecmtransaction_a_id=t.id OR rel.ecmtransaction_b_id=t.id)
            WHERE
            t.parent_id = '$id' AND
            t.deleted='0' AND
            " .$settled. "
				t.type='0' AND

            " . $payment_date . " group by t.id
    " );
     
    $suma=0;
    $total_settled=0;
    while($r = $db->fetchByAssoc ($zap)){
        $rel = $db->query("SELECT * FROM ecmtransactions_rel WHERE ecmtransaction_a_id='".$r['id']."' OR ecmtransaction_b_id='".$r['id']."'");
        while ($rr = $db->fetchByAssoc($rel)) {
            if ($rr['ecmtransaction_a_id'] == $r['id'])
                $rel_id = $rr['ecmtransaction_b_id'];
            else
                $rel_id = $rr['ecmtransaction_a_id'];
            $t = $db->fetchByAssoc($db->query("SELECT * FROM ecmtransansactions WHERE id='$rel_id'"));
         
                   if($t['deleted']==1)continue;
            $tmp2 = array();
            $tmp2['name'] = $t['name'];
            $tmp2['trans_id'] = $t['id'];
            $tmp['settled_with'][] = $tmp2;
          if($t['type']==0){
                if($r['value']<0 && $rr['value']<0){
                     $total_settled+=abs(floatval($rr['value'])); 
                } else {
                      $total_settled+=floatval($rr['value']);
                }
                
            } else {
                  $total_settled+=abs(floatval($rr['value']));
            }
        }
        $suma+=$r['value'];
    }

    $zap= $db->query ( "
            SELECT
            (
            t.value

    ) AS value,t.id
            FROM ecmtransactions AS t
            left JOIN ecmtransactions_rel AS rel
            ON (rel.ecmtransaction_a_id=t.id OR rel.ecmtransaction_b_id=t.id)
            WHERE
            t.parent_id = '$id' AND
            t.deleted='0' AND
            " .$settled. "
				t.type='1' AND

            " . $payment_date . " group by t.id
    " );
    $suma2=0;
    $total_settled2=0;
    while($r = $db->fetchByAssoc ($zap)){
        $rel = $db->query("SELECT * FROM ecmtransactions_rel WHERE ecmtransaction_a_id='".$r['id']."' OR ecmtransaction_b_id='".$r['id']."'");
        while ($rr = $db->fetchByAssoc($rel)) {
            if ($rr['ecmtransaction_a_id'] == $r['id'])
                $rel_id = $rr['ecmtransaction_b_id'];
            else
                $rel_id = $rr['ecmtransaction_a_id'];
            $t = $db->fetchByAssoc($db->query("SELECT * FROM ecmtransansactions WHERE id='$rel_id'"));
            $tmp2 = array();
            $tmp2['name'] = $t['name'];
            $tmp2['trans_id'] = $t['id'];
            $tmp['settled_with'][] = $tmp2;
            $total_settled2+=floatval($rr['value']);
        }
        $suma2+=$r['value'];
    }

     
    return $total_settled-$suma+$suma2-$total_settled2;

    return $total_settled-$suma;

}
function getData($id, $expired) {
    $db = $GLOBALS ['db'];

    $saldo = false;
    $settled = " t.settled!='1' AND ";

    switch ($expired) {
        case 0 :
            $payment_date = "1=1";
            break;
        case 1 :
            $date = new DateTime ( date ( "Y-m-d" ) );
            $d = $date->format ( 'Y-m-d' );
            $payment_date = " payment_date <= '$d'";
            $saldo=true;
            break;
        case 2 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-30 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
            break;
        case 3 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $date_to->modify ( '-31 days' );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-60 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
            break;
        case 4 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $date_to->modify ( '-61 days' );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-90 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
            break;
        case 5 :
            $date_to = new DateTime ( date ( "Y-m-d" ) );
            $date_to->modify ( '-91 days' );
            $d_t = $date_to->format ( 'Y-m-d' );
            $date_from = new DateTime ( date ( "Y-m-d" ) );
            $date_from->modify ( '-180 days' );
            $d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
            break;
        case 6 :
            $date = new DateTime ( date ( "Y-m-d" ) );
            $date->modify ( '-181 days' );
            $d = $date->format ( 'Y-m-d' );
            $payment_date = " payment_date < '$d'";
            break;
        case 7 :
            $date = new DateTime ( date ( "Y-m-d" ) );
            $d = $date->format ( 'Y-m-d' );
            $payment_date = " payment_date >= '$d'";
            break;
        case 8 :
            $payment_date = " 1=1 ";
            $saldo = true;
            $settled = " 1=1 and";
            break;
        case 9:
            $date = new DateTime ( date ( "Y-m-d" ) );
            $d = $date->format ( 'Y-m-d' );
            $payment_date = " payment_date <= '$d'";
            $settled = " 1=1 AND ";
            $saldo = true;
            break;
    }


    //start WINIEN
    $r = $db->fetchByAssoc ( $db->query ( "
            SELECT
            sum(
            t.value
    ) AS sum
            FROM ecmtransactions AS t
            WHERE
            t.parent_id = '$id' AND
            t.deleted='0' AND
            " .$settled. "
				t.type='1' AND
            " . $payment_date . "
    " ) );

    //get part settled transactions
    /*
     if (!$saldo){
     $s = $db->fetchByAssoc($db->query("
     SELECT
     sum(
     CASE WHEN t.currency_id='PLN' THEN t.value
     ELSE t.value*t.currency_value
     END
     ) AS sum
     FROM ecmtransactions AS t
     WHERE
     t.parent_id = '$id' AND
     t.deleted='0' AND
     " .$settled. "
     t.type='0' AND
     t.register_date > '2011-12-31' AND
     " . $payment_date . "

     "));

     }
    */
    if (!$saldo){
        return $r['sum'];
    }
    if (! is_numeric ( $r ['sum'] ))
        $r ['sum'] = 0;

    if (! is_numeric ( $s ['settled'] ))
        $s ['settled'] = 0;

    if (floatval($s['settled']) > 0)
        $r['sum'] = floatval($r['sum']) - floatval($s['settled']);

    $sum = $r['sum'];
    //END WINIEN

    $r['sum'] = 0;
    if ($saldo) {
        $r = $db->fetchByAssoc ( $db->query ( "
                SELECT
                sum(
                t.value
        ) AS sum
                FROM ecmtransactions AS t
                WHERE
                t.parent_id = '$id' AND
                t.deleted='0' AND
                " .$settled. "
                t.type='0' AND
				" . $payment_date . "
                " ) );
}
                $res=$sum - $r ['sum'];
                if($expired==1 && $res>0){
	    return 0;
	}
	//END MA
	return $res;
}

$id=array();
$ids=explode(',',$_REQUEST['idToPdf']);
foreach ($ids as $key){
    if($ids[$key]!=''){
        $id=$ids[$key];
    }
}
$db=$GLOBALS['db'];
$zap=$db->query("
select 
    a.name,
        a.id,
    a.index_dbf,
        a.currency_id as wal,
    (sum(CASE
        WHEN t.type = 1 THEN t.value else 0
    END)-
    sum(CASE
        WHEN t.type = 0 THEN t.value else 0
    END)) as saldo,
   (sum(CASE
        WHEN t.type = 1 and t.settled!=1 THEN t.value else 0
    END)-
    sum(CASE
        WHEN t.type = 0 and t.settled!=1 THEN t.value else 0
    END)) as zaleglosc,t2.name as name2,t2.value,t2.payment_date,t2.type
from
    accounts a

        inner join
    ecmtransactions t ON t.parent_id = a.id
		left join ecmtransactions t2 on t2.parent_id=a.id
where
    a.id in ('".implode("','",$ids)."') and t2.settled!=1 and t2.deleted=0
group by a.id,t2.id order by a.index_dbf");
$wynik=array();
while($dane=$db->fetchByAssoc($zap)){
    $tmp=array();
    $c= new Currency();
    $c->retrieve($dane['wal']);
    $wynik[$dane['index_dbf']]['name']=$dane['name'];
    $wynik[$dane['index_dbf']]['index_dbf']=$dane['index_dbf'];
    $wynik[$dane['index_dbf']]['saldo']=getData($dane['id'],8);
    $wynik[$dane['index_dbf']]['zaleglosc']=getData2($dane['id'],9);
    $wynik[$dane['index_dbf']]['wal']=$c->name;
    $wynik[$dane['index_dbf']]['ksac']=$dane['ks_account'];
   $tmp['name']=$dane['name2'];
   $tmp['value']=$dane['value'];
   $tmp['payment_date']=$dane['payment_date'];
   $tmp['type']=$dane['type'];
    $wynik[$dane['index_dbf']]['poz'][]=$tmp;
}
ob_start(); 
?>
<style>
.boldtable, .boldtable TD, .boldtable TH
{
font-family:sans-serif;
font-size:8pt;
border-collapse: collapse;

}
tr.separated td {
    /* set border style for separated rows */
    border-bottom: 1px solid black;
    border-top: 1px solid black;
} 

</style>
<table>
<tr>
<?php 
$ecmsysinfos = new EcmSysInfo();
$header = $ecmsysinfos->getName();
?>
	
<td><?php echo $header;?><br>
Data wydruku: <?php echo date("d.m.Y");?><br>
<?php echo $_REQUEST['title'];?></td>
</tr>
</table>

<table width="100%" class="boldtable">
<tr class='separated'>
<td>INDEKS</td>
<td>NAZWA</td>
<td style="text-align:right;">SALDO</td>
<td style="text-align:right;">ZALEGŁOŚĆ</td>
<td style="text-align:right;">KONTO KS</td>
</tr>


<?php 
$total=0;
$total=2;
$total3=0;
$total4=0;
foreach ($wynik as $val=>$key){
    echo "<tr>
    <td>".$wynik[$val]['index_dbf']."</td>
    <td>".$wynik[$val]['name']."</td>
    <td style='text-align:right;'>".format_number($wynik[$val]['saldo'])." ".$wynik[$val]['wal']."</td>
    <td style='text-align:right;'>".format_number($wynik[$val]['zaleglosc'])." ".$wynik[$val]['wal']."</td>
    <td style='text-align:right;'>".$wynik[$val]['ksac']."</td>
    </tr>";
    if($wynik[$val]['wal']=='PLN'){
        $total+=$wynik[$val]['saldo'];
        $total2+=$wynik[$val]['zaleglosc'];
    } else {
        $total3+=$wynik[$val]['saldo'];
        $total4+=$wynik[$val]['zaleglosc'];
    }
}
echo '<tr class="separated">
<td></td>
<td>Razem EUR:</td>
<td style="text-align:right;">'.format_number($total3).'</td>
<td style="text-align:right;">'.format_number($total4).'</td>
<td style="text-align:right;"></td>
</tr>';
echo '<tr class="separated">
<td></td>
<td>Razem PLN:</td>
<td style="text-align:right;">'.format_number($total).'</td>
<td style="text-align:right;">'.format_number($total2).'</td>
<td style="text-align:right;"></td>
</tr>';
?>
</table>
<?php 
if($_REQUEST['pdf_type']=='1'){
?>
<br>
<table width="100%" class="boldtable">
<tr class='separated'>
<td>INDEKS</td>
<td>NAZWA</td>
<td style="text-align:right;"></td>
<td style="text-align:right;">SALDO</td>
<td style="text-align:right;">ZALEGŁOŚĆ</td>
<td style="text-align:right;">KONTO KS</td>
</tr>
<?php 
$content=null;
foreach ($wynik as $val=>$key){
    $content.= "<tr class='separated'>
    <td>".$wynik[$val]['index_dbf']."</td>
    <td>".$wynik[$val]['name']."</td><td style='text-align:right;'></td>
    <td style='text-align:right;'>".format_number($wynik[$val]['saldo'])."</td>
    <td style='text-align:right;'>".format_number($wynik[$val]['zaleglosc'])."</td>
    <td style='text-align:right;'>".$wynik[$val]['ksac']."</td>
    </tr>";
   
    if(count($wynik[$val]['poz'])>0){

        foreach ($wynik[$val]['poz'] as $v=>$k){
            if($wynik[$val]['poz'][$v]['type']==0){
                $t="(Wn)";
            } else {
                $t="(Ma)";
            }
            if(date("d.m.Y",strtotime($wynik[$val]['poz'][$v]['payment_date']))=='01.01.1970'){
                $data='';
            } else {
                $data=date("d.m.Y",strtotime($wynik[$val]['poz'][$v]['payment_date']));
            }
            $content.="<tr>
    <td></td>
    <td>".$wynik[$val]['poz'][$v]['name']."</td><td style='text-align:right;'>".$t."</td>
    <td style='text-align:right;'>".format_number($wynik[$val]['poz'][$v]['value'])."</td>
    <td style='text-align:right;'>".$data."</td>
    <td style='text-align:right;'></td>
    </tr>";
        }
    }
}
$content.='</table>';
}

include_once ("include/MPDF57/mpdf.php");

$mPDF = new mPDF ( 'pl', 'A4', 9, 'arial',  10, 10,10, 10, 14, 20);
			$mPDF->setAutoTopMargi = 'stretch';
			$mPDF->setAutoBottomMargin = 'stretch';
			$mPDF->mirrorMargins = 1;
			$mPDF->WriteHTML(ob_get_clean().$content);
                        	$mPDF->Output('saldo_'.date('d_m_Y').'pdf', "I"); 
?>