<?php
//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;

if ($filtro_fecha_desde != null && $filtro_fecha_hasta != null):
    //$where_cuenta = " AND id 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_fecha_desde != null):
    //$where_cuenta = " AND id BETWEEN $filtro_id_cuenta_desde AND $filtro_id_cuenta_hasta ";
    $where_fecha_ant = " AND fecha_comprobante <= '$filtro_fecha_desde' ";
    //$where_total_cuenta = " AND cuenta BETWEEN '$filtro_id_cuenta_desde' AND '$filtro_id_cuenta_hasta' ";
    //echo $where_fecha; die();
endif;

$fecha_ant = $where_fecha_ant;

if ($filtro_nivel != null):
    $where_nivel = ' AND nivel <= '.$filtro_nivel.' ';
endif;

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

$config_contable = ['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
    Yii::import('application.modules.configuracion.models.*');
    $conf_contable = ConfContable::model()->find('id=4');
    $utili = CuentasConsolidada::model()->findAll(['select' => 'id', 'condition' => "codigo_cuenta ILIKE '%341.%' AND blnborrado=false and titulo_mov=1"]);

$utilid = [];
    foreach ($utili as $uti) {
        $utilid[] = $uti->id;
    }
    $ctas = $utilid;
    $model_plan_cuentas = CuentasConsolidada::model()->findAll([
        'condition' => " blnborrado = FALSE AND SUBSTRING(cuenta from 1 for 1) IN ('1','2','3')  ".$where_cuenta.''.$where_nivel,
        'order' => 'cuenta ASC',
    ]);
    ?>
    <thead>
        <tr>
            <th class="titulo" style="width: 14%;">Código</th>
            <th class="titulo" style="width: 26%;">Cuenta</th>
            <th class="titulo" style="width: 20%;">Anterior a <?=date('d-m-Y', strtotime($filtro_fecha_desde)); ?></th>
            <th class="titulo" style="width: 20%;"><?=date('d-m-Y', strtotime($filtro_fecha_desde)); ?> <br/><?=date('d-m-Y', strtotime($filtro_fecha_hasta)); ?></th>
            <th class="titulo" style="width: 20%;">Variación</th>
        </tr>
    </thead>
    <tbody>
   <?php

    $acum_total_anterior = 0;
    $acum_total_actual = 0;
    $acum_variacion = 0;

    foreach ($model_plan_cuentas as $cuenta): //Imprimimos cada cuenta
        if (($cuenta->cuenta[0] == 1 or $cuenta->cuenta[0] == 2 or $cuenta->cuenta[0] == 3) && $cuenta->nivel <= $filtro_nivel) {
           //Buscamos el detalle de cada cuenta
            $ejercicio = EjerciciosContables::model()->find('activo=1');
            $ingresoactual = DetalleAnalitico::model()->find([
                'select' => 'COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual',
                'condition' => "SUBSTRING('400000000' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                AND estatus_contab=1
                                AND activo=1
                                AND clvejercicio={$ejercicio->id}
                                AND blnborrado = FALSE
                                {$movimiento_cierre}
                                {$where_fecha}",
            ]);
            $ingresoanterior = DetalleAnalitico::model()->find([
                'select' => 'COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_anterior',
                'condition' => "SUBSTRING('400000000' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                AND estatus_contab=1
                                AND activo=1
                                AND clvejercicio={$ejercicio->id}
                                AND blnborrado = FALSE
                                {$movimiento_cierre}
                                {$fecha_ant}",
            ]);

            // condicion para las cuentas de excedente y patrimonio
            $condicion = in_array($cuenta->id, array_merge($ctas, [
                'patrimonio' => 477,
                'excedente' => 498,
                'utilidad_retenida_ejercicio' => $conf_contable->atributo
            ]));

            // El detalle del trimestre anterior
            if ($condicion && $ingresoanterior->total_monto_anterior != null) {
                $model_total_anterior = DetalleAnalitico::model()->find([
                    'select' => 'COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric)
                                + (select sum ((SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                   FROM "contable"."vsw_detalle_analitico" "t"
                                   WHERE SUBSTRING(\'400000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                        AND estatus_contab=1
                                        AND activo=1
                                        AND clvejercicio='.$ejercicio->id.'
                                        AND blnborrado = FALSE
                                        '.$movimiento_cierre.'
                                        '.$fecha_ant.'
                                   LIMIT 1)
                                +(SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                  FROM "contable"."vsw_detalle_analitico" "t"
                                  WHERE SUBSTRING(\'500000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1)
                                        AND estatus_contab=1
                                        AND activo=1
                                        AND clvejercicio='.$ejercicio->id.'
                                        AND blnborrado = FALSE
                                        '.$movimiento_cierre.'
                                        '.$fecha_ant.'
                                  LIMIT 1 ))) as total_monto_anterior ',
                    'condition' => "SUBSTRING('{$cuenta->cuenta}' from 1 for {$config_contable[$cuenta->nivel]})=SUBSTRING(cuenta from 1 for {$config_contable[$cuenta->nivel]})
                                    AND estatus_contab=1
                                    AND activo=1
                                    AND clvejercicio={$ejercicio->id}
                                    AND blnborrado = FALSE
                                    {$movimiento_cierre}
                                    {$where_total_cuenta}
                                    {$fecha_ant}",
                ]);
                if (($cuenta->id == (int) $conf_contable->atributo)):
                    $model_total_anterior = DetalleAnalitico::model()->find([
                        'select' => '(select sum ((SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                      FROM "contable"."vsw_detalle_analitico" "t"
                                      WHERE SUBSTRING(\'400000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                            AND estatus_contab=1
                                            AND activo=1
                                            AND clvejercicio='.$ejercicio->id.'
                                            AND blnborrado = FALSE
                                            '.$movimiento_cierre.'
                                            '.$fecha_ant.'
                                      LIMIT 1)
                                      +(SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                      FROM "contable"."vsw_detalle_analitico" "t"
                                      WHERE SUBSTRING(\'500000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                            AND estatus_contab=1
                                            AND activo=1
                                            AND clvejercicio='.$ejercicio->id.'
                                            AND blnborrado = FALSE
                                            '.$movimiento_cierre.'
                                            '.$fecha_ant.'
                                      LIMIT 1 ))) as total_monto_anterior ',
                        'condition' => "SUBSTRING('341010000' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 ) ",
                    ]);
                endif;
            } else {
                $model_total_anterior = DetalleAnalitico::model()->find([
                    'select' => 'COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_anterior ',
                    'condition' => "SUBSTRING('{$cuenta->cuenta}' from 1 for {$config_contable[$cuenta->nivel]})=SUBSTRING(cuenta from 1 for {$config_contable[$cuenta->nivel]})
                                    AND estatus_contab=1
                                    AND activo=1
                                    AND clvejercicio={$ejercicio->id}
                                    AND blnborrado = FALSE
                                    {$movimiento_cierre}
                                    {$where_total_cuenta}
                                    {$fecha_ant}",
                ]);
            }

            //El detalle del trimestre actual
            if ($condicion && $ingresoanterior->total_monto_anterior != null) {
                $model_total = DetalleAnalitico::model()->find([
                    'select' => '(select COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric)
                                  FROM "contable"."vsw_detalle_analitico" "t"
                                  where SUBSTRING(\''.$cuenta->cuenta.'\' from 1 for \''.$config_contable[$cuenta->nivel].'\' ) = SUBSTRING(cuenta from 1 for \''.$config_contable[$cuenta->nivel].'\' )
                                        AND estatus_contab=1
                                        AND activo=1
                                        AND clvejercicio='.$ejercicio->id.'
                                        AND blnborrado = FALSE
                                        '.$movimiento_cierre.'
                                        '.$where_total_cuenta.$fecha_ant.'
                                  LIMIT 1 )
                                    + COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric)
                                    + (select sum ((SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                                    FROM "contable"."vsw_detalle_analitico" "t"
                                                    WHERE SUBSTRING(\'400000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1)
                                                        AND estatus_contab=1
                                                        AND activo=1
                                                        AND clvejercicio='.$ejercicio->id.'
                                                        AND blnborrado = FALSE
                                                        '.$movimiento_cierre.'
                                                        '.$where_fecha.'
                                                    LIMIT 1 )
                                    +(SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                      FROM "contable"."vsw_detalle_analitico" "t"
                                      WHERE SUBSTRING(\'500000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1)
                                            AND estatus_contab=1
                                            AND activo=1
                                            AND clvejercicio='.$ejercicio->id.'
                                            AND blnborrado = FALSE
                                            '.$movimiento_cierre.'
                                            '.$where_fecha.'
                                      LIMIT 1)
                                    ))
                                    +(select sum ((SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                      FROM "contable"."vsw_detalle_analitico" "t"
                                      WHERE SUBSTRING(\'400000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                          AND estatus_contab=1
                                          AND activo=1
                                          AND clvejercicio='.$ejercicio->id.'
                                          AND blnborrado = FALSE
                                          '.$movimiento_cierre.'
                                          '.$fecha_ant.'
                                      LIMIT 1 )
                                    +(SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                      FROM "contable"."vsw_detalle_analitico" "t"
                                      WHERE SUBSTRING(\'500000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                            AND estatus_contab=1
                                            AND activo=1
                                            AND clvejercicio='.$ejercicio->id.'
                                            AND blnborrado = FALSE
                                            '.$movimiento_cierre.'
                                            '.$fecha_ant.'
                                      LIMIT 1 ))) as total_monto_actual ',
                    'condition' => "SUBSTRING('{$cuenta->cuenta}' from 1 for {$config_contable[$cuenta->nivel]})=SUBSTRING(cuenta from 1 for {$config_contable[$cuenta->nivel]})
                                AND estatus_contab=1
                                AND activo=1
                                AND clvejercicio={$ejercicio->id}
                                AND blnborrado = FALSE
                                {$movimiento_cierre}
                                {$where_total_cuenta}
                                {$where_fecha}",
                ]);

                if ($cuenta->id == $conf_contable->atributo && $ingresoactual->total_monto_actual != null) {
                    $model_total = DetalleAnalitico::model()->find([
                        'select' => '(select sum ((SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                      FROM "contable"."vsw_detalle_analitico" "t"
                                      WHERE SUBSTRING(\'400000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                            AND estatus_contab=1
                                            AND activo=1
                                            AND clvejercicio='.$ejercicio->id.'
                                            AND blnborrado = FALSE
                                            '.$movimiento_cierre.'
                                            '.$where_fecha.'
                                      LIMIT 1)
                                        + (SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                          FROM "contable"."vsw_detalle_analitico" "t"
                                          WHERE SUBSTRING(\'500000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                                AND estatus_contab=1
                                                AND activo=1
                                                AND clvejercicio='.$ejercicio->id.'
                                                AND blnborrado = FALSE
                                                '.$movimiento_cierre.'
                                                '.$where_fecha.'
                                          LIMIT 1 )))
                                        + (select sum ((SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                           FROM "contable"."vsw_detalle_analitico" "t"
                                           WHERE SUBSTRING(\'400000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 )
                                                AND estatus_contab=1
                                                AND activo=1
                                                AND clvejercicio='.$ejercicio->id.'
                                                AND blnborrado = FALSE
                                                '.$movimiento_cierre.'
                                                '.$fecha_ant.'
                                           LIMIT 1)
                                        + (SELECT COALESCE(sum(monto_debe), 0::numeric) -COALESCE(sum(monto_haber), 0::numeric) as total_monto_actual
                                           FROM "contable"."vsw_detalle_analitico" "t"
                                           WHERE SUBSTRING(\'500000000\' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1)
                                                AND estatus_contab=1
                                                AND activo=1
                                                AND clvejercicio='.$ejercicio->id.'
                                                AND blnborrado = FALSE
                                                '.$movimiento_cierre.'
                                                '.$fecha_ant.'
                                           LIMIT 1)))   as total_monto_actual',
                        'condition' => "SUBSTRING('341010000' from 1 for 1 ) = SUBSTRING(cuenta from 1 for 1 ) ",
                    ]);
                }
            } else {
                $model_total = DetalleAnalitico::model()->find([
                    'select' => "(COALESCE(sum(monto_debe), 0::numeric) - COALESCE(sum(monto_haber), 0::numeric)) as total_monto_actual",
                    'condition' => "SUBSTRING('{$cuenta->cuenta}' from 1 for {$config_contable[$cuenta->nivel]})=SUBSTRING(cuenta from 1 for {$config_contable[$cuenta->nivel]})
                                    AND estatus_contab=1
                                    AND activo=1
                                    AND clvejercicio={$ejercicio->id}
                                    AND blnborrado = FALSE
                                    {$movimiento_cierre}
                                    {$where_total_cuenta}
                                    {$where_fecha}",
                ]);
            }

            // ESTO NECESITA UNA MEJORA URGENTE 23-05-2018 11:32:26 AM
            $monto_anterior = ($model_total_anterior->total_monto_anterior) ? $model_total_anterior->total_monto_anterior : 0;
            $monto_actual = ($model_total->total_monto_actual) ? $model_total->total_monto_actual : 0;

            // ESTO NECESITA UNA MEJORA URGENTE 23-05-2018 11:32:26 AM
            // Se aplica para las cuentas de patrimonio y excendente tambien para cuando se consulta
            // el primer periodo. (el calculo del trimestre esta basado en el las
            // fechas desde y hasta)
            if (($condicion && $ingresoactual->total_monto_actual != null) || (new Periodo($filtro_fecha_desde, $filtro_fecha_hasta))->getTrimestre() == 1) {
                // formula: (debe - haber)
                $monto_actual = $monto_actual;
            } else {
                // formula: (debe - haber) + saldo_anterior
                $monto_actual = $monto_actual + $monto_anterior;
            }

            $monto_variacion = $monto_actual - $monto_anterior;

               //Verificamos si a la cuenta se le hacen movimientos
               $cta_mov = DetalleComprobante::model()->findByAttributes(['id_cuenta' => $cuenta->id]);

               if ($cta_mov != null): //Si es una cuenta de movimiento si sumo para el total del balance
                    $acum_total_anterior += $monto_anterior;
                    $acum_total_actual += $monto_actual;
                    $acum_variacion += $monto_variacion;
               endif;

               //total de los activos
                    if (trim($cuenta->cuenta[0]) == '1' && $cuenta->nivel == 1):
                        $acum_activos_anterior += $monto_anterior;
                        $acum_activos_actual += $monto_actual;
                        $acum_activos_variacion += $monto_variacion;
                    endif;

                    //total de los pasivos
                    if (trim($cuenta->cuenta[0]) == '2' && $cuenta->nivel == 1):
                        $acum_pasivos_anterior += $monto_anterior;
                        $acum_pasivos_actual += $monto_actual;
                        $acum_pasivos_variacion += $monto_variacion;
                    endif;
                    //total de patrimonio
                    if (trim($cuenta->cuenta[0]) == '3' && $cuenta->nivel == 1):
                        $acum_patrimonio_anterior += $monto_anterior;
                        $acum_patrimonio_actual += $monto_actual;
                        $acum_patrimonio_variacion += $monto_variacion;
                    endif;
               //formateo de la presentacion
               if ($model_total_anterior->total_monto_anterior < 0):
                    $monto_anterior_f = number_format(($model_total_anterior->total_monto_anterior) * -1, 2, ',', '.');
                    $monto_anterior_f = '('.$monto_anterior_f.')';
               else:
                    $monto_anterior_f = number_format($model_total_anterior->total_monto_anterior, 2, ',', '.');
               endif;
               if ($monto_actual < 0):
                    $monto_actual_f = number_format(($monto_actual) * -1, 2, ',', '.');
                    $monto_actual_f = '('.$monto_actual_f.')';
                else:
                    $monto_actual_f = number_format($monto_actual, 2, ',', '.');
               endif;
               if ($monto_variacion < 0):
                    $monto_variacion_f = number_format(($monto_variacion) * -1, 2, ',', '.');
                    $monto_variacion_f = '('.$monto_variacion_f.')';
                else:
                    $monto_variacion_f = number_format($monto_variacion, 2, ',', '.');
               endif;

               //Si son los 3 primeros niveles la presentacion debe ser en mayusculas y negrita
               if (in_array($cuenta->nivel, [1, 2, 3])):
                   $clase_cuenta = 'cuenta_alto_nivel';
                   $cuenta->cuenta = strtoupper($cuenta->cuenta);
               else:
                   $clase_cuenta = '';
               endif;

        if ($filtro_sin_ceros): //Cuentas sin movimiento (no mostrar = true)
            if ($monto_actual == 0 && $monto_anterior == 0 && $monto_variacion == 0):
                $mostrar = false;
            else:
                $mostrar = true;
            endif;
        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_anterior_f; ?></td>
                <td style="text-align: right; <?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : ''; ?>" class="<?=$clase_cuenta; ?>"><?=$monto_actual_f; ?></td>
                <td style="text-align: right; <?= $cuenta->titulo_mov == 1 ? 'font-weight: bold;' : ''; ?>" class="<?=$clase_cuenta; ?>"><?=$monto_variacion_f; ?></td>
            </tr>   
        <?php
        endif;
      }
    endforeach;

                 //formateo de la presentacion
               $total_anterior = number_format($acum_total_anterior, 2, ',', '.');
               $total_actual = number_format($acum_total_actual, 2, ',', '.');
               $total_variacion = number_format($acum_variacion, 2, ',', '.');

               //Obtenemos el patrimonio:
                $total_patrimonio_anterior = (-$acum_activos_anterior - $acum_pasivos_anterior);
                $total_patrimonio_actual = (-$acum_activos_actual - $acum_pasivos_actual);
                $total_patrimonio_variacion = ($total_patrimonio_actual - $total_patrimonio_anterior);

               //$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="totalx" style="width: 12%; text-align: left;"><b>&nbsp;</b></td>
        <td class="totalx"  style="width: 36%; text-align: left;">&nbsp;</td>
        <td class="totalx"  style="width: 12%; text-align: right; ">&nbsp;</td>
        <td class="totalx"  style="width: 12%; text-align: right;">&nbsp;</td>
        <td class="totalx"  style="width: 12%; text-align: right;">&nbsp;</td>
      </tr>
      
         <?php
         // formateo activo
           if ($acum_activos_anterior < 0):
                    $acum_activos_anterior_f = '('.number_format($acum_activos_anterior * -1, 2, ',', '.').')';
                else:
                    $acum_activos_anterior_f = number_format($acum_activos_anterior, 2, ',', '.');
               endif;
               if ($acum_activos_actual < 0):
                    $acum_activos_actual_f = '('.number_format($acum_activos_actual * -1, 2, ',', '.').')';
                else:
                    $acum_activos_actual_f = number_format($acum_activos_actual, 2, ',', '.');
               endif;
               if ($acum_activos_variacion < 0):
                    $acum_activos_variacion_f = '('.number_format($acum_activos_variacion * -1, 2, ',', '.').')';
                else:
                    $acum_activos_variacion_f = number_format($acum_activos_variacion, 2, ',', '.');
               endif;
         // formateo pasivos
               if ($acum_pasivos_anterior < 0):
                    $acum_pasivos_anterior_f = '('.number_format($acum_pasivos_anterior * -1, 2, ',', '.').')';
                else:
                    $acum_pasivos_anterior_f = number_format($acum_pasivos_anterior * -1, 2, ',', '.');
               endif;
               if ($acum_pasivos_actual < 0):
                    $acum_pasivos_actual_f = '('.number_format($acum_pasivos_actual * -1, 2, ',', '.').')';
                else:
                    $acum_pasivos_actual_f = number_format($acum_pasivos_actual, 2, ',', '.');
               endif;
               if ($acum_pasivos_variacion < 0):
                    $acum_pasivos_variacion_f = '('.number_format($acum_pasivos_variacion * -1, 2, ',', '.').')';
                else:
                    $acum_pasivos_variacion_f = number_format($acum_pasivos_variacion, 2, ',', '.');
               endif;
           // formateo patrimonio
           if ($total_patrimonio_anterior < 0):
                    $total_patrimonio_anterior_f = '('.number_format($total_patrimonio_anterior * -1, 2, ',', '.').')';
                else:
                    $total_patrimonio_anterior_f = number_format($total_patrimonio_anterior, 2, ',', '.');
               endif;
               if ($total_patrimonio_actual < 0):
                    $total_patrimonio_actual_f = '('.number_format($total_patrimonio_actual * -1, 2, ',', '.').')';
                else:
                    $total_patrimonio_actual_f = number_format($total_patrimonio_actual, 2, ',', '.');
               endif;
               if ($total_patrimonio_variacion < 0):
                    $total_patrimonio_variacion_f = '('.number_format($total_patrimonio_variacion * -1, 2, ',', '.').')';
                else:
                    $total_patrimonio_variacion_f = number_format($total_patrimonio_variacion, 2, ',', '.');
               endif;
           // formateo totales
           if (($total_patrimonio_anterior + $acum_pasivos_anterior) < 0):
                    $totalactivo = '('.number_format(($total_patrimonio_anterior + $acum_pasivos_anterior) * -1, 2, ',', '.').')';
                else:
                    $totalactivo = number_format(($total_patrimonio_anterior + $acum_pasivos_anterior), 2, ',', '.');
               endif;

           if (($total_patrimonio_actual + $acum_pasivos_actual) < 0):
                    $totalactivoactual = '('.number_format(($total_patrimonio_actual + $acum_pasivos_actual) * -1, 2, ',', '.').')';
                else:
                    $totalactivoactual = number_format(($total_patrimonio_actual + $acum_pasivos_actual), 2, ',', '.');
               endif;

           if (($total_patrimonio_variacion + $acum_pasivos_variacion) < 0):
                    $totalactivoavariacion = '('.number_format(($total_patrimonio_variacion + $acum_pasivos_variacion) * -1, 2, ',', '.').')';
                else:
                    $totalactivoavariacion = number_format(($total_patrimonio_variacion + $acum_pasivos_variacion), 2, ',', '.');
               endif;

      ?>
     <tr>
        <td class="total" colspan="2" style="width: 12%; text-align: left;"><b>TOTAL ACTIVO</b></td>
        <!--td class="total"  style="width: 36%; text-align: left;">&nbsp;</td-->
        <td class="total"  style="width: 16%; text-align: right; "><?=$acum_activos_anterior_f; ?></td>
        <td class="total"  style="width: 16%; text-align: right;"><?=$acum_activos_actual_f; ?></td>
        <td class="total"  style="width: 16%; text-align: right;"><?=$acum_activos_variacion_f; ?></td>
      </tr>
      <tr>
        <td class="total" style="width: 16%; text-align: left;"><b>&nbsp;</b></td>
        <td class="total"  style="width: 36%; text-align: left;">&nbsp;</td>
        <td class="total"  style="width: 16%; text-align: right;">==========</td>
        <td class="total"  style="width: 16%; text-align: right;">==========</td>
        <td class="total"  style="width: 16%; text-align: right;">==========</td>
      </tr>
      <tr>
        <td class="totalx" colspan="2" style="width: 16%; text-align: left;"><b>TOTAL PASIVO</b></td>
        <!--<td class="totalx"  style="width: 36%; text-align: left;">&nbsp;</td>-->
        <td class="totalx"  style="width: 16%; text-align: right; "><?=$acum_pasivos_anterior_f; ?></td>
        <td class="totalx"  style="width: 16%; text-align: right;"><?=$acum_pasivos_actual_f; ?></td>
        <td class="totalx"  style="width: 16%; text-align: right;"><?=$acum_pasivos_variacion_f; ?></td>
      </tr>
      <tr>
        <td class="totalx" colspan="2" style="width: 16%; text-align: left;"><b>TOTAL PATRIMONIO</b></td>
        <!--td class="totalx"  style="width: 36%; text-align: left;">&nbsp;</td-->
        <td class="totalx"  style="width: 16%; text-align: right; "><?=$total_patrimonio_anterior_f; ?></td>
        <td class="totalx"  style="width: 16%; text-align: right;"><?=$total_patrimonio_actual_f; ?></td>
        <td class="totalx"  style="width: 16%; text-align: right;"><?=$total_patrimonio_variacion_f; ?></td>
      </tr>
      <tr>
        <td class="total" colspan="2" style="width: 16%; text-align: left;"><b>TOTAL PASIVO + PATRIMONIO</b></td>
        <!--td class="total"  style="width: 36%; text-align: left;">&nbsp;</td-->
        <td class="total"  style="width: 16%; text-align: right; "><?=$totalactivo; ?></td>
        <td class="total"  style="width: 16%; text-align: right;"><?=$totalactivoactual; ?></td>
        <td class="total"  style="width: 16%; text-align: right;"><?=$totalactivoavariacion; ?></td>
      </tr> 
      <tr>
        <td class="total" style="width: 16%; text-align: left;"><b>&nbsp;</b></td>
        <td class="total"  style="width: 36%; text-align: left;">&nbsp;</td>
        <td class="total"  style="width: 16%; text-align: right;">==========</td>
        <td class="total"  style="width: 16%; text-align: right;">==========</td>
        <td class="total"  style="width: 16%; text-align: right;">==========</td>
      </tr>
     
    </tbody>
</table>
<?php
$contenido = ob_get_clean();
//cabecera pagina
ob_start();
$modelEmpresa = Empresa::model()->find();
$ruta_logo = dirname(Yii::app()->getBasePath()).'/images/'.$modelEmpresa->logo;
?>
<div class="cabecera">
    (FORMA "A")<br/>
    <?=Empresa::RazonSocial(); ?>
    <br/>
    <?='RIF: '.Empresa::Rif(); ?>
    <br/>
    <?='SECTOR: '.Empresa::Sector().'&nbsp;&nbsp;&nbsp; NÚMERO DE REGISTRO: '.Empresa::RegistroSUDECA(); ?>
    <br/>
    <?='ESTADO DE SITUACIÓN FINANCIERA DESDE  '.date('d-m-Y', strtotime($filtro_fecha_desde)).' HASTA '.date('d-m-Y', strtotime($filtro_fecha_hasta)); ?>
    <br/>
    <?='(EXPRESADO EN Bs.)'; ?>
<br/><br/>   
</div>
<?php
$cabecera = ob_get_clean();

$mpdf = new mPDF('win-1252', 'LETTER', '', '', 9, 9, 30, 10, 5, 5);
$arr = [
                        'L' => [
                          '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' => [
                          '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();
?>
<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_situacion_financiera.pdf', 'D');
exit;
?>
