<?php

class SituacionFinancieraFechaPdf
{
    protected $query;

    public function __construct($query)
    {
        $this->query = $query;
    }

    private function toUpper($string)
    {
        return strtoupper($string);
    }

    private function format($number)
    {
        return Yii::app()->format->number($number);
    }

    protected function applyFormat($number)
    {
        if ($number < 0) {
            return "({$this->format(abs($number))})";
        }

        return $this->format($number);
    }

    public function create()
    {
        Yii::createComponent('application.extensions.mpdf60.mpdf');

        $empresa = Empresa::model()->find();

        $cabecera = "
            <div class='cabecera'>
                (FORMA \"A\")
                <br/>
                {$this->toUpper($empresa->razon_social)}
                <br/>
                RIF: {$this->toUpper($empresa->rif_emp)}
                <br/>
                SECTOR: {$empresa->getSector()} NÚMERO DE REGISTRO: {$empresa->getRegistroSudeca()}
                <br/>
                ESTADO DE SITUACIÓN FINANCIERA DESDE {$this->query['attributes']['fecha_desde']} HASTA {$this->query['attributes']['fecha_hasta']}
                <br/>
                (EXPRESADO EN Bs.)
                <br/>
                <br/>
            </div>
        ";

        $html = "
        <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'>
            <thead>
                <tr>
                    <th class='titulo' style='width: 10%;'>Código</th>
                    <th class='titulo' style='width: 45%;'>Cuenta</th>
                    <th class='titulo' style='width: 15%;'>Anterior a {$this->query['attributes']['fecha_desde']}</th>
                    <th class='titulo' style='width: 15%;'>{$this->query['attributes']['fecha_desde']} {$this->query['attributes']['fecha_hasta']}</th>
                    <th class='titulo' style='width: 15%;'>Variación</th>
                </tr>
            </thead>
            <tbody>";

        foreach ($this->query['detalle'] as $cuenta) {
            $style = $cuenta['cuenta_titulo'] ? 'font-weight: bold;' : '';
            $html .= "
                <tr>
                    <td class='{$cuenta['clase']}' style='{$style}'>
                        {$cuenta['cuenta']}
                    </td>
                    <td class='{$cuenta['clase']}' style='{$style}'>
                        {$cuenta['descripcion']}
                    </td>
                    <td style='text-align: right;' class='{$cuenta['clase']}'>
                        {$this->applyFormat($cuenta['anterior'])}
                    </td>
                    <td style='text-align: right;' class='{$cuenta['clase']}'>
                        {$this->applyFormat($cuenta['actual'])}
                    </td>
                    <td style='text-align: right;' class='{$cuenta['clase']}'>
                        {$this->applyFormat($cuenta['variacion'])}
                    </td>
                </tr>
            ";
        }

        $totales = new Warp($this->query['totales']);

        $html .= "
        <tr>
            <td class='total' colspan='2' style='width: 12%; text-align: left;'><b>TOTAL ACTIVO</b></td>
            <td class='total' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('activo.anterior'))}</td>
            <td class='total' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('activo.actual'))}</td>
            <td class='total' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('activo.variacion'))}</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>
        </tr>
        <tr>
            <td class='totalx' colspan='2' style='width: 16%; text-align: left;'><b>TOTAL PASIVO</b></td>
            <td class='totalx' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('pasivo.anterior'))}</td>
            <td class='totalx' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('pasivo.actual'))}</td>
            <td class='totalx' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('pasivo.variacion'))}</td>
        </tr>
        <tr>
            <td class='totalx' colspan='2' style='width: 16%; text-align: left;'><b>TOTAL PATRIMONIO</b></td>
            <td class='totalx' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('patrimonio.anterior'))}</td>
            <td class='totalx' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('patrimonio.actual'))}</td>
            <td class='totalx' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('patrimonio.variacion'))}</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: 16%; text-align: right;'>{$this->applyFormat($totales->get('pasivo_patrimonio.anterior'))}</td>
            <td class='total' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('pasivo_patrimonio.actual'))}</td>
            <td class='total' style='width: 16%; text-align: right;'>{$this->applyFormat($totales->get('pasivo_patrimonio.variacion'))}</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>
        </tr>
        ";

        $html .= '</tbody></table>';

        $mpdf = new mPDF('win-1252', 'LETTER', '', '', 9, 9, 30, 10, 5, 5);
        $mpdf->setTitle("Estado de situación financiera al {$this->query['attributes']['fecha_hasta']}");
        $ruta_logo = dirname(Yii::app()->getBasePath()).'/images/'.$empresa->logo;
        $mpdf->setHeader([
            'L' => [
                'content' => empty($empresa->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,
        ], 'O');
        $mpdf->SetFooter('Emitido: '.date('d/m/Y h:i:s a').' - Página {PAGENO} de {nb}');
        $mpdf->WriteHTML($html);

        if ((new Warp($this->query))->get('attributes.firmas')) {
            $mpdf->AddPage();
            $firmas = '';
            foreach ((new Warp($this->query))->get('attributes.firmas') as $departamento => $funcionario) {
                $breakloop = 0;
                $indice_fe = 0;
                $fin_ciclo = 0;

                $breakloop_1 = 0;
                $indice_fe_1 = 0;

                $firmas .= "
                <br/>
                <br/>
                <table class='firmas'>
                    <thead>
                        <tr>
                            <th colspan='3'>{$departamento}</th>
                        </tr>
                    </thead>
                    <tbody>
                ";

                if (count($funcionario) > 0) {
                    do {
                        $firmas .= '<tr><td><tr>';
                        foreach ($funcionario as $funci => $_) {
                            if ($funci == $indice_fe_1) {
                                $firmas .= '<td class="lineas" width="33%"></td>';
                                $breakloop_1++;
                                $indice_fe_1++;

                                if ($breakloop_1 === 3) {
                                    break;
                                }
                            }
                        }
                        $firmas .= '</tr><tr>';
                        foreach ($funcionario as $func => $datos) {
                            if ($func == $indice_fe) {
                                $firmas .= "
                                <td class='info_lineas' width='33%'>
                                    {$datos['nombre_apellido']}
                                    <br/>
                                    {$datos['cedula']}
                                    <br/>
                                    {$datos['cargo']}
                                </td>";
                                $breakloop++;
                                $indice_fe++;
                                $fin_ciclo++;

                                if ($breakloop === 3) {
                                    break;
                                }
                            }
                        }
                        $firmas .= '</tr></td></tr>';
                    } while (fin_ciclo < count($funcionario));
                }
                $firmas .= '</tbody></table><br/><br/>';
            }
            $mpdf->WriteHTML($firmas);
        }

        $mpdf->Output("Estado de situación financiera al {$this->query['attributes']['fecha_hasta']}.pdf", 'I');
        exit;
    }
}
