<?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;
$filtro_nivel = $model->nivel;

//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 cuenta BETWEEN '$filtro_id_cuenta_desde' AND '$filtro_id_cuenta_hasta' AND titulo_mov = 2 OR (titulo_mov = 1 AND cuenta BETWEEN '1' AND '$filtro_id_cuenta_hasta')";
    $where_total_cuenta = " AND cuenta BETWEEN '$filtro_id_cuenta_desde' AND '$filtro_id_cuenta_hasta' ";

    //echo $where_cuenta; die();
    //echo $where_total_cuenta; die();
endif;


if ($filtro_fecha_desde!=NULL && $filtro_fecha_hasta!=NULL ):
//    $where_cuenta = " AND cuenta BETWEEN '$filtro_id_cuenta_desde' AND '$filtro_id_cuenta_hasta' ";
    $where_fecha = " AND fecha_comprobante BETWEEN '$filtro_fecha_desde' AND '$filtro_fecha_hasta' ";
//    $where_total_cuenta = " AND cuenta BETWEEN '$filtro_id_cuenta_desde' AND '$filtro_id_cuenta_hasta' ";
    //echo $where_fecha; die();
endif;

if ($filtro_nivel!=NULL):
    $where_nivel = " AND nivel <= ".$filtro_nivel." ";
endif;

if ($model->excluir_movimiento_cierre) {
    $movimiento_cierre = ' AND id_tipo_comprobante=1';
} else {
    $movimiento_cierre = ' AND (id_tipo_comprobante=1 OR id_tipo_comprobante=3)';
}

//'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.mpdf60.mpdf');

ob_start();
?>
<style type="text/css">

    .cabecera{
        text-align: center;
        font-weight: bold;
        font-size: 10px;
        width: 100%;
    }

    .titulo{
        text-align: center;
        font-weight: bold;
        border: 1px solid black;
    }

    .cuenta_alto_nivel{
        text-transform: uppercase;
        font-weight: bold;
        border-top: 1px solid black;
        border-bottom: 1px solid black;
        padding-top: 10px;
    }

    .listado{
        font-size: 10px;
    }
    .listado td{
        padding-left: 8px;
        padding-right: 8px;
    }

    .total{
        font-size: 10px;
        font-weight: bold;
        background-color: Gainsboro;
    }

    @media print {
        thead { display: table-header-group; }
    }

    table.firmas{

        width: 100%;
        border-spacing: 20px;
    }

    .firmas th{

        text-align: center;
    }

    .firmas tr td.lineas{

        border-bottom: 1px solid #000;
        padding-top: 30px;
    }

    .firmas tr td.info_lineas{

        text-align: center;
        font-size: 12px;
    }

</style>


<table class="listado" style="width: 100%;" border="0" cellpadding="0" cellspacing="0">
    <?php
    $model_plan_cuentas = CuentasConsolidada::model()->findAll(array(
                    'condition'=>" blnborrado = false ".$where_cuenta."".$where_nivel,
                    'order'=>'cuenta ASC',
               ));
    ?>
    <thead>
        <tr>
            <th class="titulo" style="width: 10%;">Código</th>
            <th class="titulo" style="width: 30%;">Cuenta</th>
            <th class="titulo" style="width: 15%;">Saldo Inicial</th>
            <th class="titulo" style="width: 15%;">Debe</th>
            <th class="titulo" style="width: 15%;">Haber</th>
            <th class="titulo" style="width: 15%;">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
        $ejercicio=  EjerciciosContables::model()->find('activo=1');

                if ($filtro_fecha_desde!=null):
                    $fechainicio=date('m',strtotime($filtro_fecha_desde));
                    $anyo= date('Y',strtotime($filtro_fecha_desde));

                    if ($fechainicio==01):
                        $fechareferencia="AND fecha_comprobante BETWEEN '$filtro_fecha_desde' AND '$filtro_fecha_hasta' AND id_tipo_comprobante=2";
                    else:
                        $fechareferencia="AND fecha_comprobante < '$filtro_fecha_desde' ";
                    endif;
                    $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 = FALSE
                                        AND estatus_contab=1
                                        AND activo=1
                                        AND clvejercicio=$ejercicio->id
                                        {$movimiento_cierre}
                                        {$where_total_cuenta}
                                        {$where_fecha}",
                    ));

                   $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 = FALSE
                                        AND estatus_contab=1
                                        AND activo=1
                                        AND clvejercicio=$ejercicio->id
                                        {$where_total_cuenta}
                                        {$fechareferencia}",
                    ));
                else:
                    $fechareferencia="";
                    $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 = FALSE
                                        AND estatus_contab=1
                                        AND activo=1
                                        AND clvejercicio=$ejercicio->id
                                        {$movimiento_cierre}
                                        {$where_total_cuenta}
                                        {$where_fecha}",
                    ));

                   $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 = FALSE
                                        AND estatus_contab=1
                                        AND activo=1
                                        AND clvejercicio=$ejercicio->id
                                        AND id_tipo_comprobante=2
                                        {$where_total_cuenta}
                                        {$fechareferencia}",
                    ));
                endif;
               //Vamos a  buscar el saldo total sumandolo a la apertura
               $saldo_con_apertura = $model_total_anterior->total_saldo + $model_total->total_apertura;

               $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;
//               $monto_saldo; exit;

               /*
               //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;
        // Cuentas sin movimiento (no mostrar = true)
        if ($filtro_sin_ceros && $monto_inicial == '0,00' && $monto_debe == '0,00' && $monto_haber == '0,00' && $monto_saldo == '0,00'):
            $mostrar = false;
        else:
            $mostrar = true;
        endif;

        if ($mostrar):
        ?>
            <tr>
                <td class="<?=$clase_cuenta?>" style="<?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : '' ?>"><?=$cuenta->cuenta?></td>
                <td class="<?=$clase_cuenta?>" style="<?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : '' ?>"><?=$cuenta->descripcion?></td>
                <td style="text-align: right; <?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : '' ?>" class="<?=$clase_cuenta?>"><?=$monto_inicial?></td>
                <td style="text-align: right; <?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : '' ?>" class="<?=$clase_cuenta?>"><?=$monto_debe?></td>
                <td style="text-align: right; <?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : '' ?>" class="<?=$clase_cuenta?>"><?=$monto_haber?></td>
                <td style="text-align: right; <?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : '' ?>" class="<?=$clase_cuenta?>"><?=$monto_saldo?></td>
            </tr>
        <?php
        endif;

    endforeach;
    //die();

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

               if ( (DetalleAnalitico::totalDebe($where_total_cuenta.$where_fecha)-DetalleAnalitico::totalHaber($where_total_cuenta.$where_fecha)) < 0 ):
                    $total_saldo = number_format( ((DetalleAnalitico::totalDebe($where_total_cuenta.$where_fecha)-DetalleAnalitico::totalHaber($where_total_cuenta.$where_fecha) )*-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: 28%; text-align: left;">&nbsp;</td>
        <td class="total"  style="width: 15%; text-align: right; "><?=$total_inicial?></td>
        <td class="total"  style="width: 15%; text-align: right;"><?=$total_debe?></td>
        <td class="total"  style="width: 15%; text-align: right;"><?=$total_haber?></td>
        <td class="total"  style="width: 15%; text-align: right;"><?=$total_saldo?></td>
      </tr>
        <tr>
        <td class="total" style="width: 12%; text-align: left;"><b>&nbsp;</b></td>
        <td class="total"  style="width: 28%; text-align: left;">&nbsp;</td>
        <td class="total"  style="width: 15%; text-align: right;">==========</td>
        <td class="total"  style="width: 15%; text-align: right;">==========</td>
        <td class="total"  style="width: 15%; text-align: right;">==========</td>
        <td class="total"  style="width: 15%; text-align: right;">==========</td>
      </tr>
    </tbody>
</table>
<?php
//die();//CAMB
$contenido = ob_get_clean();

//echo $contenido;

//cabecera pagina
ob_start();
$modelEmpresa = Empresa::model()->find();
$ruta_logo= dirname(Yii::app()->getBasePath())."/images/".$modelEmpresa->logo;
?>
<div class="cabecera">
     (FORMA "C")<br/>
    <?=Empresa::RazonSocial()?>
    <br/>
     <?="RIF: ".Empresa::Rif()?>
    <br/>
    <?="SECTOR: ".Empresa::Sector()."&nbsp;&nbsp;&nbsp; NÚMERO DE REGISTRO: ".Empresa::RegistroSUDECA()?>
    <br/>
    <?='BALANCE DE COMPROBACIÓN AL '.$filtro_fecha_hasta?>
    <br/>
    <?='(EXPRESADO EN Bs.)'?>
<br/><br/>
</div>
<?php
$cabecera = ob_get_clean();

//echo $contenido;
$mpdf=new mPDF('win-1252','LETTER','','',9,9,30,10,5,5);
$arr = array (
                        'L' => array (
                          'content' => (empty($modelEmpresa->logo))?"<img src=".dirname(Yii::app()->getBasePath())."/images/logo.png alt='Logo' width ='40px' heigth='40px'/>":"<img src='".$ruta_logo."' alt='Logo' width ='60px' heigth='60px'/>",
                        ),

                        'C' => array (
                          'content' => $cabecera,
                          'font-style' => 'BI',
                          'font-family' => 'serif',
                          'color'=>'#000000'
                        ),

                        'line' => 0,

                    );
$mpdf->setHeader($arr, 'O');
//$mpdf->SetHTMLHeader($cabecera);
date_default_timezone_set('America/Caracas');
$mpdf->SetFooter("Emitido: ".date('d/m/Y h:i:s a')." - Página {PAGENO} de {nb}");
$mpdf->WriteHTML($contenido);
if (!empty($datos_firma)):
$mpdf->AddPage();
ob_start();

//$a = 5;
//$r = $a % 3;
//echo "<pre>";print_r($datos_firma);exit;
?>
<br/><br/>
    <?php foreach ($datos_firma as $departamento => $funcionario): ?>
        <table class="firmas">
            <thead>
                <tr>
                    <th colspan="3"><?php echo $departamento; ?></th>
                </tr>
            </thead>
            <tbody>
                <?php
                    $breakloop = 0;
                    $indice_fe = 0;
                    $fin_ciclo = 0;

                    $breakloop_1 = 0;
                    $indice_fe_1 = 0;

                    if (count($funcionario) > 0):
                ?>
                    <?php do { ?>
                        <tr>
                            <td>
                                <tr>
                                    <?php foreach ($funcionario as $funci => $dat): //echo "<pre>";var_dump($indice_fe);exit;?>
                                        <?php if ($funci== $indice_fe_1): ?>
                                                <td class="lineas" width="33%"></td>
                                        <?php
                                            $breakloop_1 ++;
                                            $indice_fe_1 ++;

                                            if ($breakloop_1 === 3) {

                                                break;
                                            }

                                            endif
                                        ?>
                                    <?php endforeach ?>
                                </tr>
                                <tr>
                                    <?php foreach ($funcionario as $func => $datos): //echo "<pre>";var_dump($indice_fe);exit;?>
                                        <?php if ($func == $indice_fe): ?>
                                                <td class="info_lineas" width="33%"><?php echo $datos['nombre_apellido']; ?><br/><?php echo $datos['cedula']; ?><br/><?php echo $datos['cargo']; ?></td>
                                        <?php
                                            $breakloop ++;
                                            $indice_fe ++;
                                            $fin_ciclo ++;

                                            if ($breakloop === 3) {

                                                break;
                                            }

                                            endif
                                        ?>
                                    <?php endforeach ?>
                                </tr>
                            </td>
                        </tr>
                    <?php } while ($fin_ciclo < count($funcionario)); ?>
                <?php endif ?>
            </tbody>
        </table>
        <br/><br/>
    <?php endforeach ?>
<br/><br/>

<?php
$firmas = ob_get_clean();
$mpdf->WriteHTML($firmas);
endif;
$mpdf->Output("SAICA_balance_comprobacion.pdf","D");
exit;
?>
