<?php
/*****************************************************************************************************************************************
 * DEV: CONTRALORIA DE ESTADOS
 * PROYECTO: SISTEMA INTEGRAL ADMINISTRATIVO DE CONTRALORIAS DE ESTADOS
 * MODULO: index
 * PROCESO: index del sistema
 * PROGRAMADORES:
 * | # |          NOMBRES Y APELLIDOS              |               CORREO               |          TELEFONO              |
 * | 1 |          Daniel Muñoz                     |d.munoz@contraloriamonagas.gob.ve   |         0412-8358676           |
 * |   |                                           |                                    |                                |
 * |___|___________________________________________|____________________________________|________________________________|
 *
 * VERSION
 *
 * |          PROGRAMADOR                  |          FECHA          |       VERSION      |
 * |               #1                      |        27-08-2015       |         1.0        |
 * |                                       |                         |                    |
 * |_______________________________________|_________________________|____________________|
 *
 *****************************************************************************************************************************************/

require_once LIBRERIA_FPDF;

class pdf extends FPDF
{
    /**
     * [$atFechainicio fecha desde donde se consultaran los requerimientos]
     * @var [date]
     */
    var $atFechainicio;
    
    /**
     * [$atFechaFinal fecha hasta donde se consultaran los requerimientos]
     * @var [type]
     */
    var $atFechaFinal;

    var $titulos = true;

    function setFecha($fechaInicio, $fechaFinal)
    {
        $this->atFechainicio = $fechaInicio;
        $this->atFechaFinal  = $fechaFinal;
    }

    function getFecha(){
        return "DESDE ".$this->atFechainicio." HASTA ".$this->atFechaFinal;
    }

    /**
     * [Header Imprimir el encabezado del reporte]
     */
    function Header()
    {

        $this->Image('publico/imagenes/logos/CES.png', 8, 8, 22);
        $this->SetFont('Arial', 'B', 8);
        $this->SetXY(30,10); $this->Cell(100,5,utf8_decode('REPÚBLICA BOLIVARIANA DE VENEZUELA'),0,1,'L');
        $this->SetXY(30,14); $this->Cell(100,5,utf8_decode('CONTRALORIA DEL ESTADO SUCRE'),0,1,'L');
        $this->SetXY(30,18); $this->Cell(100,5,utf8_decode('DIRECCIÓN DE ADMINISTRACIÓN'),0,1,'L');
        ## 
        $this->SetXY(163,12); $this->Cell(25,5,utf8_decode('Fecha: ' . date('d-m-Y')),0,1,'L');
        $this->SetXY(163,17); $this->Cell(25,5,utf8_decode('Página: ' . $this->PageNo() . ' de {nb}'),0,1,'L');
        $this->SetXY(40, 10); $this->Cell(100, 20, '', 0, 1, 'L');
        $this->SetXY(42, 10); $this->Cell(20, 28, '', 0, 1, 'L');
        $this->Image(ROOT.'publico'.DS.'imagenes'.DS.'logos'.DS."LOGOSNCF.png", 190, 10, 17, 15);
        
        $this->SetXY(5, 25); $this->Cell(195, 8, utf8_decode(strtoupper('Listado de Requerimientos')), 0, 1, 'C');
        $this->Ln(3);

        if($this->titulos)
        {
            $this->SetDrawColor(0, 0, 0);
            $this->SetFillColor(229, 229, 229); //$this->SetFillColor(255, 255, 255);
            $this->SetTextColor(0, 0, 0);
            $this->SetFont('Arial', 'B', 6);
            $this->SetWidths(array(10, 20, 30, 20, 20, 80, 20));
            $this->SetAligns(array('C','C', 'C', 'C', 'C', 'C', 'C'));
            $this->Row(array(
                utf8_decode('N°'),
                utf8_decode('NRO. DOC.'),
                utf8_decode('DEPENDENCIA'),
                utf8_decode('FECHA PREP.'),
                utf8_decode('CLASIFICACIÓN'),
                utf8_decode('COMENTARIOS'),
                utf8_decode('ESTADO')
            ));
            //$this->Ln(1);
        }
    }

    /**
     * [Footer imprimir el pie de pagina]
     */
    function Footer(){
         //Position at 1.5 c   m from bottom
        $this->SetXY(227,24.5);
        //Helvetica italic 8

        $this->SetFont('Arial', 'B', 8);
        //Page number
        $anio_actual=date("Y");
        $anio_fundadoCES=1966;
        $aniversarios=$anio_actual-$anio_fundadoCES;

        if(strcmp($this->orientacion,'L')==0) {//horizontalheader
            $this->SetFont('Arial', 'B', 7.5);
            $this->SetXY(40, 185); $this->MultiCell(200, 3, utf8_decode('Dirección: Avenida Arismendi, Edificio Palacio Legislativo, Cumaná, estado Sucre, Teléfonos: (0293) 4320708, 4323658. Directo: Tele Fax 4323447. Correo Electrónico: despacho@cgesucre.gob.ve, Zona Postal: 6101,  Rif. G20001224-2. Sitio web: www.cgesucre.gob.ve'),0, 'C');
            $this->SetFont('Arial', 'B', 7.5);
            $this->SetXY(115, 175); $this->Cell(50, 45, utf8_decode('"Todos los Sucrenses Somos Contralores, '.$aniversarios.' Aniversario '.$anio_fundadoCES.'-'.$anio_actual.'"'), 0, 1, 'C', 0);
            $this->Image(ROOT.'publico'.DS.'imagenes'.DS.'logos'.DS."60Aniv.jpg", 10, 185, 18, 16);
            $this->Image(ROOT.'publico'.DS.'imagenes'.DS.'logos'.DS."SNCF_GRIS.jpg", 250, 183, 17, 18);
            //Page number
            $this->SetFont('Arial', 'B', 8);
            $this->SetXY(205,10);
            $this->Cell(0,5,' '.$this->PageNo().'/{nb}',0,0,'C');
        }else{//vertical
            $this->SetFont('Arial', 'B', 7.5);
            //Page number
            $this->SetXY(38, 258); $this->MultiCell(140, 3, utf8_decode('Dirección: Avenida Arismendi, Edificio Palacio Legislativo, Cumaná, estado Sucre, Teléfonos: (0293) 4320708, 4323658. Directo: Tele Fax 4323447. Correo Electrónico: despacho@cgesucre.gob.ve, Zona Postal: 6101,  Rif. G20001224-2. Sitio web: www.cgesucre.gob.ve'),0, 'C');
            $this->SetFont('Arial', 'B', 7.5);
            $this->SetXY(85, 217); $this->Cell(50, 110, utf8_decode('"Todos los Sucrenses Somos Contralores, '.$aniversarios.' Aniversario '.$anio_fundadoCES.'-'.$anio_actual.'"'), 0, 1, 'C', 0);
            $this->Image(ROOT.'publico'.DS.'imagenes'.DS.'logos'.DS."60Aniv.jpg", 17, 256, 18, 16);
            $this->Image(ROOT.'publico'.DS.'imagenes'.DS.'logos'.DS."SNCF_GRIS.jpg", 177, 254, 17, 18);

            $this->Cell(0,10,' '.$this->PageNo().'/{nb}',0,0,'C');
        }


    }

    /**
     * funciones para la grafica
     */
    /**
     * [PieChart permite generar gráficos circulares Utiliza el script 
     * Sector . : ancho máximo del diagrama. : altura máxima del diagrama. : matriz asociativa 
     * que contiene las etiquetas y los datos correspondientes. : formato utilizado para 
     * mostrar las leyendas. Es una cadena que puede contener los siguientes valores 
     * especiales:% l (etiqueta),% v (valor) y% p (porcentaje). : matriz que contiene los 
     * colores. Si no se proporciona, se usará una escala de grises. : ancho del diagrama. : 
     * altura del diagrama. : matriz asociativa que contiene las etiquetas y los datos 
     * correspondientes. : formato utilizado para mostrar las leyendas. Es una cadena que 
     * puede contener los siguientes valores especiales:% l (etiqueta),% v (valor) y% p (
     * porcentaje).]
     * @param [int] $w      [ancho máximo del diagrama.]
     * @param [int] $h      [altura máxima del diagrama.]
     * @param [array] $data   [matriz asociativa que contiene las etiquetas y los datos correspondientes.]
     * @param [string] $format [formato utilizado para mostrar las leyendas. Es una cadena que puede contener los siguientes valores especiales: %l (etiqueta), %v (valor) y %p (porcentaje).]
     * @param [array] $colors [matriz que contiene los colores. Si no se proporciona, se usará una escala de grises.]
     */
    function PieChart($w, $h, $data, $format, $colors=null)
    {
        $this->SetFont('Courier', '', 10);
        $this->SetLegends($data,$format);
        /**
         * POSICION DE LA GRAFICA $XPage, $YPage
         */
        $XPage = $this->GetX();
        $YPage = $this->GetY()+15;
        $margin = 2;
        $hLegend = 5;
        $radius = min($w - $margin * 4 - $hLegend - $this->wLegend, $h - $margin * 2);
        $radius = floor($radius / 2);
        $XDiag = $XPage + $margin + $radius;
        $YDiag = $YPage + $margin + $radius;
        if($colors == null) {
            for($i = 0; $i < $this->NbVal; $i++) {
                $gray = $i * intval(255 / $this->NbVal);
                $colors[$i] = array($gray,$gray,$gray);
            }
        }

        //Sectors
        $this->SetLineWidth(0.2);
        $angleStart = 0;
        $angleEnd = 0;
        $i = 0;
        foreach($data as $val) {
            $angle = ($val * 360) / doubleval($this->sum);
            if ($angle != 0) {
                $angleEnd = $angleStart + $angle;
                $this->SetFillColor($colors[$i][0],$colors[$i][1],$colors[$i][2]);
                $this->Sector($XDiag, $YDiag, $radius, $angleStart, $angleEnd);
                $angleStart += $angle;
            }
            $i++;
        }

        //Legends
        $this->SetFont('Courier', '', 10);
        $x1 = $XPage + 2 * $radius + 4 * $margin;
        $x2 = $x1 + $hLegend + $margin;
        $y1 = $YDiag - $radius + (2 * $radius - $this->NbVal*($hLegend + $margin)) / 2;
        for($i=0; $i<$this->NbVal; $i++) {
            $this->SetFillColor($colors[$i][0],$colors[$i][1],$colors[$i][2]);
            $this->Rect($x1, $y1, $hLegend, $hLegend, 'DF');
            $this->SetXY($x2,$y1);
            $this->Cell(0,$hLegend,$this->legends[$i]);
            $y1+=$hLegend + $margin;
        }
    }

    function BarDiagram($w, $h, $data, $format, $color=null, $maxVal=0, $nbDiv=4)
    {
        $this->SetFont('Courier', '', 10);
        $this->SetLegends($data,$format);

        $XPage = $this->GetX();
        $YPage = $this->GetY();
        $margin = 2;
        $YDiag = $YPage + $margin;
        $hDiag = floor($h - $margin * 2);
        $XDiag = $XPage + $margin * 2 + $this->wLegend;
        $lDiag = floor($w - $margin * 3 - $this->wLegend);
        if($color == null)
            $color=array(155,155,155);
        if ($maxVal == 0) {
            $maxVal = max($data);
        }
        $valIndRepere = ceil($maxVal / $nbDiv);
        $maxVal = $valIndRepere * $nbDiv;
        $lRepere = floor($lDiag / $nbDiv);
        $lDiag = $lRepere * $nbDiv;
        $unit = $lDiag / $maxVal;
        $hBar = floor($hDiag / ($this->NbVal + 1));
        $hDiag = $hBar * ($this->NbVal + 1);
        $eBaton = floor($hBar * 80 / 100);

        $this->SetLineWidth(0.2);
        $this->Rect($XDiag, $YDiag, $lDiag, $hDiag);

        $this->SetFont('Courier', '', 10);
        $this->SetFillColor($color[0],$color[1],$color[2]);
        $i=0;
        foreach($data as $val) {
            //Bar
            $xval = $XDiag;
            $lval = (int)($val * $unit);
            $yval = $YDiag + ($i + 1) * $hBar - $eBaton / 2;
            $hval = $eBaton;
            $this->Rect($xval, $yval, $lval, $hval, 'DF');
            //Legend
            $this->SetXY(0, $yval);
            $this->Cell($xval - $margin, $hval, $this->legends[$i],0,0,'R');
            $i++;
        }

        //Scales
        for ($i = 0; $i <= $nbDiv; $i++) {
            $xpos = $XDiag + $lRepere * $i;
            $this->Line($xpos, $YDiag, $xpos, $YDiag + $hDiag);
            $val = $i * $valIndRepere;
            $xpos = $XDiag + $lRepere * $i - $this->GetStringWidth($val) / 2;
            $ypos = $YDiag + $hDiag - $margin;
            $this->Text($xpos, $ypos, $val);
        }
    }

    function SetLegends($data, $format)
    {
        $this->legends=array();
        $this->wLegend=0;
        $this->sum=array_sum($data);
        $this->NbVal=count($data);
        foreach($data as $l=>$val)
        {
            $p=sprintf('%.2f',$val/$this->sum*100).'%';
            $legend=str_replace(array('%l','%v','%p'),array($l,$val,$p),$format);
            $this->legends[]=$legend;
            $this->wLegend=max($this->GetStringWidth($legend),$this->wLegend);
        }
    }


}
