<?php
/* @var $this ReportescontablesController */


//TOMAMOS TODAS LAS VARIABLES QUE VIENEN DE LA PANTALLA
$filtro_id_cuenta_desde = $model->id_cuenta_desde;
$filtro_id_cuenta_hasta = $model->id_cuenta_hasta;
$filtro_fecha_desde = $model->fecha_desde;
$filtro_fecha_hasta = $model->fecha_hasta;
$filtro_nivel = $model->nivel;
$filtro_sin_ceros = $model->sin_ceros;

///echo "<pre>".print_r($model,true)."</pre>"; die();


if ($filtro_id_cuenta_desde!=NULL && $filtro_id_cuenta_hasta!=NULL ):
    //$where_cuenta = " AND id BETWEEN $filtro_id_cuenta_desde AND $filtro_id_cuenta_hasta ";
    $where_cuenta = " AND id BETWEEN $filtro_id_cuenta_desde AND $filtro_id_cuenta_hasta AND titulo_mov = 2 OR (titulo_mov = 1 AND id BETWEEN 1 AND $filtro_id_cuenta_hasta)";
    $where_total_cuenta = " AND id_cuenta BETWEEN $filtro_id_cuenta_desde AND $filtro_id_cuenta_hasta ";
    echo $where_cuenta; die();
endif;








//'nivel'=>'digitos'
$config_contable = array('0'=>0,'1'=>1,'2'=>2,'3'=>3,'4'=>5,'5'=>7,'6'=>9,'7'=>11);


$pdf = Yii::createComponent('application.extensions.MPDF52.mpdf');

ob_start();
?>
<style type="text/css">
    
    .titulo{
        text-align: center; 
        font-weight: bold;
        border: 1px solid black;
    }
    
    .cuenta_alto_nivel{
        text-transform: uppercase;
        font-weight: bold;
        border-bottom: 1px solid black;
        padding-top: 10px;
    }
    
    .listado{
        font-size: 12px;     
    }
    .listado td{
        padding-left: 8px;
        padding-right: 8px;
    }
    
    .total{
        font-size: 14px;
        font-weight: bold;
        background-color: Gainsboro;
    }
    
    @media print {
        thead { display: table-header-group; }
    }
    
    
</style>


<table class="listado" style="width: 100%;" border="0" cellpadding="0" cellspacing="0">
    
    <!--tr>
        <td style="width: 12%;"></td>
        <td style="width: 40%;"></td>
        <td style="width: 12%;"></td>
        <td style="width: 12%;"></td>
        <td style="width: 12%;"></td>
        <td style="width: 12%;"></td>
    </tr-->
    <!--tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr-->
    
    <?php
    //$model_plan_cuentas = CuentasConsolidada2015::model()->findAll(array('order'=>'cuenta ASC')); //Traemos el plan de cuentas contable
    $model_plan_cuentas = CuentasConsolidada2015::model()->findAll(array(
                    //'select'=>'sum(monto_debe) as total_debe , sum(monto_haber) as total_haber, sum(monto_debe)-sum(monto_haber) as total_saldo ',
                    'condition'=>" blnborrado = TRUE ".$where_cuenta."",
                    'order'=>'cuenta ASC',
                    //'params'=>array(':idcuenta'=>$cuenta->id,)
               ));
    ?>
    <thead>
        <tr>
            <th class="titulo" style="width: 12%;">Código</th>
            <th class="titulo" style="width: 40%;">Cuenta</th>
            <th class="titulo" style="width: 12%;">Saldo Inicial</th>
            <th class="titulo" style="width: 12%;">Debe</th>
            <th class="titulo" style="width: 12%;">Haber</th>
            <th class="titulo" style="width: 12%;">Saldo Actual</th>
        </tr>
    </thead>
    <tbody>
   <?php
   
    $acum_inicial = 0;
    $acum_debe = 0;
    $acum_haber = 0;
    $acum_saldo = 0;
   
   foreach($model_plan_cuentas as $cuenta): //Imprimimos cada cuenta
       //Buscamos el detalle de cada cuenta
       
                $model_total_anterior = DetalleAnalitico::model()->find(array(
                    'select'=>'sum(monto_debe) as total_debe , sum(monto_haber) as total_haber, sum(monto_debe)-sum(monto_haber) as total_saldo ',
                    'condition'=>"SUBSTRING('".$cuenta->cuenta."' from 1 for ".$config_contable[$cuenta->nivel]." ) = SUBSTRING(cuenta from 1 for ".$config_contable[$cuenta->nivel]." ) AND blnborrado = TRUE AND mov_apertura = FALSE ".$where_total_cuenta,
                    //'order'=>'id',
                    //'params'=>array(':idcuenta'=>$cuenta->id,)
                ));
   
               $model_total = DetalleAnalitico::model()->find(array(
                    'select'=>'sum(monto_debe)-sum(monto_haber) as total_apertura ',
                    'condition'=>"SUBSTRING('".$cuenta->cuenta."' from 1 for ".$config_contable[$cuenta->nivel]." ) = SUBSTRING(cuenta from 1 for ".$config_contable[$cuenta->nivel]." ) AND blnborrado = TRUE AND mov_apertura = TRUE ".$where_total_cuenta,
                    //'order'=>'id',
                    //'params'=>array(':idcuenta'=>$cuenta->id,)
                ));
               
               //Vamos a  buscar el saldo total sumandolo a la apertura
               $saldo_con_apertura = $model_total_anterior->total_saldo + $model_total->total_apertura;
               //echo $saldo_con_apertura."<br/>"; //CAMB
               
               $monto_inicial = ($model_total->total_apertura) ? $model_total->total_apertura : 0;
               $monto_debe = ($model_total_anterior->total_debe) ? $model_total_anterior->total_debe : 0;
               $monto_haber = ($model_total_anterior->total_haber) ? $model_total_anterior->total_haber : 0;
               $monto_saldo = ($saldo_con_apertura) ? $saldo_con_apertura : 0;
               
               
               /*
               //Verificamos si a la cuenta se le hacen movimientos
               $cta_mov = DetalleComprobante::model()->findByAttributes(array('id_cuenta'=>$cuenta->id));
               
               if($cta_mov!=null): //Si es una cuenta de movimiento si sumo para el total del balance
                    $acum_inicial += $total_inicial;
                    $acum_debe += $model_total->total_debe;
                    $acum_haber += $model_total->total_haber;
                    $acum_saldo += $model_total->total_saldo;
                    
                    echo $cuenta->cuenta . " " . $cuenta->descripcion . " " . $model_total->total_debe . " " . $model_total->total_haber . "<br/>";
                */    
               //formateo de la presentacion
               $monto_inicial =number_format($model_total->total_apertura,2,',','.');
               $monto_debe = number_format($model_total_anterior->total_debe,2,',','.');
               $monto_haber = number_format($model_total_anterior->total_haber,2,',','.');
               $monto_saldo = number_format($saldo_con_apertura,2,',','.');
               

               
               if ($saldo_con_apertura<0): //Si es negativo el saldo
                   $saldo = $saldo_con_apertura*-1;
                   //$acum_saldo += $saldo; //Acumulamos el saldo
                   $monto_saldo = number_format($saldo,2,',','.');
                   $monto_saldo = "(".$monto_saldo.")";
               //else:
                   //$total_saldo = $model_total->total_saldo;
               endif;
               
               if ($model_total->total_apertura<0): //Si es negativo el saldo
                   $inicial = $model_total->total_apertura*-1;
                   //$acum_saldo += $saldo; //Acumulamos el saldo
                   $monto_inicial = number_format($inicial,2,',','.');
                   $monto_inicial = "(".$monto_inicial.")";
               //else:
                   //$total_saldo = $model_total->total_saldo;
               endif;
               
               
               
               
               //Si son los 3 primeros niveles la presentacion debe ser en mayusculas y negrita
               if ( in_array($cuenta->nivel, array(1,2,3)) ):
                   
                   $clase_cuenta = "cuenta_alto_nivel";
                   $cuenta->cuenta = strtoupper($cuenta->cuenta);
               else:
                   $clase_cuenta = "";
               endif;
   ?>
    <tr>
        <td class="<?=$clase_cuenta?>"><?=$cuenta->cuenta?></td>
        <td class="<?=$clase_cuenta?>"><?=$cuenta->descripcion?></td>
        <td style="text-align: right;" class="<?=$clase_cuenta?>"><?=$monto_inicial?></td>
        <td style="text-align: right;" class="<?=$clase_cuenta?>"><?=$monto_debe?></td>
        <td style="text-align: right;" class="<?=$clase_cuenta?>"><?=$monto_haber?></td>
        <td style="text-align: right;" class="<?=$clase_cuenta?>"><?=$monto_saldo?></td>
    </tr>   
    <?php
    endforeach;
                

                 //formateo de la presentacion
               $total_inicial =number_format($monto_inicial,2,',','.');
               $total_debe = number_format(DetalleAnalitico::totalDebe($where_total_cuenta),2,',','.');
               $total_haber = number_format(DetalleAnalitico::totalHaber($where_total_cuenta),2,',','.');
               $total_saldo = number_format( (DetalleAnalitico::totalDebe($where_total_cuenta)-DetalleAnalitico::totalHaber($where_total_cuenta) ),2,',','.');

               if ( (DetalleAnalitico::totalDebe($where_total_cuenta)-DetalleAnalitico::totalHaber($where_total_cuenta)) < 0 ):
                    $total_saldo = number_format( ((DetalleAnalitico::totalDebe($where_total_cuenta)-DetalleAnalitico::totalHaber($where_total_cuenta) )*-1),2,',','.');
                    $total_saldo = "(".$monto_saldo.")";
               endif;
    
    ?>
    <tr>
        <td class="total" style="width: 12%; text-align: left;"><b>TOTALES</b></td>
        <td class="total"  style="width: 40%; text-align: left;">&nbsp;</td>
        <td class="total"  style="width: 12%; text-align: right; "><?=$total_inicial?></td>
        <td class="total"  style="width: 12%; text-align: right;"><?=$total_debe?></td>
        <td class="total"  style="width: 12%; text-align: right;"><?=$total_haber?></td>
        <td class="total"  style="width: 12%; text-align: right;"><?=$total_saldo?></td>
      </tr>
    </tbody>
</table>
<?php
//die();//CAMB
$contenido = ob_get_clean();

//echo $contenido;

//cabecera pagina
ob_start();
?>
<div style="text-align: center; font-weight: bold; width: 100%;">
    <?="NOMBRE DE LA ASOCIACION"?>
    <br/>
    <?="SECTOR: NÚMERO DE REGISTRO"?>
    <br/>
    <?='BALANCE DE COMPROBACIÓN "TRIMESTRAL" AL '?>
    <br/>
    <?='(EXPRESADO EN Bs.)'?>
<br/><br/>   
</div>
<?php
$cabecera = ob_get_clean();


$mpdf=new mPDF('win-1252','LETTER','','',9,9,35,10,5,5);
$mpdf->SetHTMLHeader($cabecera);
$mpdf->SetFooter("Emitido: ".date('d/m/Y h:i:s a')." - Página {PAGENO} de {nb}");
$mpdf->WriteHTML($contenido);
$mpdf->Output("SAICA_balance_comprobacion.pdf","D");
exit;
?>