<?php

Yii::import("application.vendors.fpdf.*", true);

if (function_exists('mcrypt_encrypt')) {

    function RC4($key, $data) {
        return mcrypt_encrypt(MCRYPT_ARCFOUR, $key, $data, MCRYPT_MODE_STREAM, '');
    }

} else {

    function RC4($key, $data) {
        static $last_key, $last_state;

        if ($key != $last_key) {
            $k = str_repeat($key, 256 / strlen($key) + 1);
            $state = range(0, 255);
            $j = 0;
            for ($i = 0; $i < 256; $i++) {
                $t = $state[$i];
                $j = ($j + $t + ord($k[$i])) % 256;
                $state[$i] = $state[$j];
                $state[$j] = $t;
            }
            $last_key = $key;
            $last_state = $state;
        } else
            $state = $last_state;

        $len = strlen($data);
        $a = 0;
        $b = 0;
        $out = '';
        for ($i = 0; $i < $len; $i++) {
            $a = ($a + 1) % 256;
            $t = $state[$a];
            $b = ($b + $t) % 256;
            $state[$a] = $state[$b];
            $state[$b] = $t;
            $k = $state[($state[$a] + $state[$b]) % 256];
            $out .= chr(ord($data[$i]) ^ $k);
        }
        return $out;
    }

}

class PDF extends FPDF {

    var $encrypted = false;  //whether document is protected
    var $Uvalue;             //U entry in pdf document
    var $Ovalue;             //O entry in pdf document
    var $Pvalue;             //P entry in pdf document
    var $enc_obj_id;         //encryption object id
    var $widths;
    var $aligns;

    function SetWidths($w) {
        //Set the array of column widths
        $this->widths = $w;
    }

    function SetAligns($a) {
        //Set the array of column alignments
        $this->aligns = $a;
    }

    function Row($data) {
        //Calculate the height of the row
        $nb = 0;
        for ($i = 0; $i < count($data); $i++)
            $nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
        $h = 8 * $nb;
        //Issue a page break first if needed
        $this->CheckPageBreak($h);
        //Draw the cells of the row
        for ($i = 0; $i < count($data); $i++) {
            $w = $this->widths[$i];
            $a = isset($this->aligns[$i]) ? $this->aligns[$i] : 'J';
            //Save the current position
            $x = $this->GetX();
            $y = $this->GetY();
            //Draw the border

            $this->Rect($x, $y, $w, $h);
            //Print the text


            $this->MultiCell($w, 5, $data[$i], 0, $a);
            //Put the position to the right of the cell
            $this->SetXY($x + $w, $y);
        }
        //Go to the next line
        $this->Ln($h);
    }

    function RowS($data) {
        //Calculate the height of the row
        $nb = 0;
        for ($i = 0; $i < count($data); $i++)
            $nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
        $h = 6 * $nb;
        //Issue a page break first if needed
        $this->CheckPageBreak($h);
        //Draw the cells of the row
        for ($i = 0; $i < count($data); $i++) {
            $w = $this->widths[$i];
            $a = isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
            //Save the current position
            $x = $this->GetX();
            $y = $this->GetY();
            //Draw the border
            $this->Rect($x,$y,$w,$h);
            //Print the text


            $this->MultiCell($w, 5, $data[$i], 0, $a);
            //Put the position to the right of the cell
            $this->SetXY($x + $w, $y);
        }
        //Go to the next line
        $this->Ln($h);
    }

    function CheckPageBreak($h) {
        //If the height h would cause an overflow, add a new page immediately
        if ($this->GetY() + $h > $this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }

    function NbLines($w, $txt) {
        //Computes the number of lines a MultiCell of width w will take
        $cw = &$this->CurrentFont['cw'];
        if ($w == null)
            $w = $this->w - $this->rMargin - $this->x;
        $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize;
        $s = str_replace("\r", '', $txt);
        $nb = strlen($s);
        if ($nb > 0 and $s[$nb - 1] == "\n")
            $nb--;
        $sep = -1;
        $i = 0;
        $j = 0;
        $l = 0;
        $nl = 1;
        while ($i < $nb) {
            $c = $s[$i];
            if ($c == "\n") {
                $i++;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
                continue;
            }
            if ($c == ' ')
                $sep = $i;
            $l += $cw[$c];
            if ($l > $wmax) {
                if ($sep == -1) {
                    if ($i == $j)
                        $i++;
                } else
                    $i = $sep + 1;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
            } else
                $i++;
        }
        return $nl;
    }

    function SetProtection($permissions = array(), $user_pass = '', $owner_pass = null) {
        $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32);
        $protection = 192;
        foreach ($permissions as $permission) {
            if (!isset($options[$permission]))
                $this->Error('Incorrect permission: ' . $permission);
            $protection += $options[$permission];
        }
        if ($owner_pass === null)
            $owner_pass = uniqid(rand());
        $this->encrypted = true;
        $this->padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08" .
                "\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
        $this->_generateencryptionkey($user_pass, $owner_pass, $protection);
    }

  
    function _putstream($s) {
        if ($this->encrypted) {
            $s = RC4($this->_objectkey($this->n), $s);
        }
        parent::_putstream($s);
    }

    function _textstring($s) {
        if ($this->encrypted) {
            $s = RC4($this->_objectkey($this->n), $s);
        }
        return parent::_textstring($s);
    }

    /**
     * Compute key depending on object number where the encrypted data is stored
     */
    function _objectkey($n) {
        return substr($this->_md5_16($this->encryption_key . pack('VXxx', $n)), 0, 10);
    }

    function _putresources() {
        parent::_putresources();
        if ($this->encrypted) {
            $this->_newobj();
            $this->enc_obj_id = $this->n;
            $this->_out('<<');
            $this->_putencryption();
            $this->_out('>>');
            $this->_out('endobj');
        }
    }

    function _putencryption() {
        $this->_out('/Filter /Standard');
        $this->_out('/V 1');
        $this->_out('/R 2');
        $this->_out('/O (' . $this->_escape($this->Ovalue) . ')');
        $this->_out('/U (' . $this->_escape($this->Uvalue) . ')');
        $this->_out('/P ' . $this->Pvalue);
    }

    function _puttrailer() {
        parent::_puttrailer();
        if ($this->encrypted) {
            $this->_out('/Encrypt ' . $this->enc_obj_id . ' 0 R');
            $this->_out('/ID [()()]');
        }
    }

    /**
     * Get MD5 as binary string
     */
    function _md5_16($string) {
        return pack('H*', md5($string));
    }

    /**
     * Compute O value
     */
    function _Ovalue($user_pass, $owner_pass) {
        $tmp = $this->_md5_16($owner_pass);
        $owner_RC4_key = substr($tmp, 0, 5);
        return RC4($owner_RC4_key, $user_pass);
    }

    /**
     * Compute U value
     */
    function _Uvalue() {
        return RC4($this->encryption_key, $this->padding);
    }

    /**
     * Compute encryption key
     */
    function _generateencryptionkey($user_pass, $owner_pass, $protection) {
        // Pad passwords
        $user_pass = substr($user_pass . $this->padding, 0, 32);
        $owner_pass = substr($owner_pass . $this->padding, 0, 32);
        // Compute O value
        $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass);
        // Compute encyption key
        $tmp = $this->_md5_16($user_pass . $this->Ovalue . chr($protection) . "\xFF\xFF\xFF");
        $this->encryption_key = substr($tmp, 0, 5);
        // Compute U value
        $this->Uvalue = $this->_Uvalue();
        // Compute P value
        $this->Pvalue = -(($protection ^ 255) + 1);
    }

    /*     * funcion para parrafo de las constancias* */

    var $flowingBlockAttr;

    function saveFont() {

        $saved = array();

        $saved['family'] = $this->FontFamily;
        $saved['style'] = $this->FontStyle;
        $saved['sizePt'] = $this->FontSizePt;
        $saved['size'] = $this->FontSize;
        $saved['curr'] = & $this->CurrentFont;

        return $saved;
    }

    function restoreFont($saved) {

        $this->FontFamily = $saved['family'];
        $this->FontStyle = $saved['style'];
        $this->FontSizePt = $saved['sizePt'];
        $this->FontSize = $saved['size'];
        $this->CurrentFont = & $saved['curr'];

        if ($this->page > 0)
            $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
    }

    function newFlowingBlock($w, $h, $b = 0, $a = 'J', $f = 0) {
        $this->flowingBlockAttr['width'] = $w * $this->k;
        $this->flowingBlockAttr['height'] = $h;
        $this->flowingBlockAttr['lineCount'] = 0;
        $this->flowingBlockAttr['border'] = $b;
        $this->flowingBlockAttr['align'] = $a;
        $this->flowingBlockAttr['fill'] = $f;
        $this->flowingBlockAttr['font'] = array();
        $this->flowingBlockAttr['content'] = array();
        $this->flowingBlockAttr['contentWidth'] = 1;
    }

    function finishFlowingBlock() {

        $maxWidth = & $this->flowingBlockAttr['width'];

        $lineHeight = & $this->flowingBlockAttr['height'];
        $border = & $this->flowingBlockAttr['border'];
        $align = & $this->flowingBlockAttr['align'];
        $fill = & $this->flowingBlockAttr['fill'];

        $content = & $this->flowingBlockAttr['content'];
        $font = & $this->flowingBlockAttr['font'];


        $this->_out(sprintf('%.3f Tw', 0));


        $usedWidth = 0;

        foreach ($content as $k => $chunk) {

            $b = '';

            if (is_int(strpos($border, 'B')))
                $b .= 'B';

            if ($k == 0 && is_int(strpos($border, 'L')))
                $b .= 'L';

            if ($k == count($content) - 1 && is_int(strpos($border, 'R')))
                $b .= 'R';

            $this->restoreFont($font[$k]);


            if ($k == count($content) - 1)
                $this->Cell(( $maxWidth / $this->k ) - $usedWidth + 2 * $this->cMargin, $lineHeight, $chunk, $b, 1, $align, $fill);
            else
                $this->Cell($this->GetStringWidth($chunk), $lineHeight, $chunk, $b, 0, $align, $fill);

            $usedWidth += $this->GetStringWidth($chunk);
        }
    }

    function WriteFlowingBlock($s) {

        $contentWidth = & $this->flowingBlockAttr['contentWidth'];
        $maxWidth = & $this->flowingBlockAttr['width'];
        $lineCount = & $this->flowingBlockAttr['lineCount'];

        $lineHeight = & $this->flowingBlockAttr['height'];
        $border = & $this->flowingBlockAttr['border'];
        $align = & $this->flowingBlockAttr['align'];
        $fill = & $this->flowingBlockAttr['fill'];
        $content = & $this->flowingBlockAttr['content'];
        $font = & $this->flowingBlockAttr['font'];
        $font[] = $this->saveFont();
        $content[] = '';
        $currContent = & $content[count($content) - 1];
        $cutoffWidth = $contentWidth;


        for ($i = 0; $i < strlen($s); $i++) {


            $c = $s{ $i };


            $cw = $this->CurrentFont['cw'][$c] * ( $this->FontSizePt / 1000 );

            if ($c == ' ') {

                $currContent .= ' ';
                $cutoffWidth = $contentWidth;

                $contentWidth += $cw;

                continue;
            }


            if ($contentWidth + $cw > $maxWidth) {


                $lineCount++;


                $savedContent = '';
                $savedFont = array();


                $words = explode(' ', $currContent);


                if (count($words) == 1) {


                    $savedContent = array_pop($content);
                    $savedFont = array_pop($font);

                    // trim any trailing spaces off the last bit of content
                    $currContent = & $content[count($content) - 1];

                    $currContent = rtrim($currContent);
                } else {

                    $lastContent = '';

                    for ($w = 0; $w < count($words) - 1; $w++)
                        $lastContent .= "{$words[$w]} ";

                    $savedContent = $words[count($words) - 1];
                    $savedFont = $this->saveFont();

                    $currContent = rtrim($lastContent);
                }

                $contentWidth = 0;

                foreach ($content as $k => $chunk) {

                    $this->restoreFont($font[$k]);

                    $contentWidth += $this->GetStringWidth($chunk) * $this->k;
                }

                $cutoffWidth = $contentWidth;


                if ($align == 'J') {


                    $numSpaces = 0;

                    foreach ($content as $chunk)
                        $numSpaces += substr_count($chunk, ' ');


                    if ($numSpaces > 0)
                        $this->ws = ( $maxWidth - $cutoffWidth ) / $numSpaces;
                    else
                        $this->ws = 0;

                    $this->_out(sprintf('%.3f Tw', $this->ws));
                } else
                    $this->_out(sprintf('%.3f Tw', 0));


                $usedWidth = 0;

                foreach ($content as $k => $chunk) {

                    $this->restoreFont($font[$k]);

                    $stringWidth = $this->GetStringWidth($chunk) + ( $this->ws * substr_count($chunk, ' ') / $this->k );


                    $b = '';

                    if ($lineCount == 1 && is_int(strpos($border, 'T')))
                        $b .= 'T';

                    if ($k == 0 && is_int(strpos($border, 'L')))
                        $b .= 'L';

                    if ($k == count($content) - 1 && is_int(strpos($border, 'R')))
                        $b .= 'R';


                    if ($k == count($content) - 1)
                        $this->Cell(( $maxWidth / $this->k ) - $usedWidth + 2 * $this->cMargin, $lineHeight, $chunk, $b, 1, $align, $fill);
                    else {

                        $this->Cell($stringWidth + 2 * $this->cMargin, $lineHeight, $chunk, $b, 0, $align, $fill);
                        $this->x -= 2 * $this->cMargin;
                    }

                    $usedWidth += $stringWidth;
                }


                $this->restoreFont($savedFont);

                $font = array($savedFont);
                $content = array($savedContent . $s{ $i });

                $currContent = & $content[0];

                $contentWidth = $this->GetStringWidth($currContent) * $this->k;
                $cutoffWidth = $contentWidth;
            } else {

                $contentWidth += $cw;
                $currContent .= $s{ $i };
            }
        }
    }


     function Header() {
               $this->Ln(20);
               $this->SetTextColor(0, 77,174);
               $this->SetFont( 'Arial', '', 20 );
               $this->Cell(15,8,'',0,0,'C');
               $this->Cell(160,8,utf8_decode('INV. SILVER DAILY'),0,0,'C');
               $this->Ln(10);
               $this->SetTextColor(0, 0,0);
     }

    
     function cliente($model){
                $this->Ln(10);
          
                
               $this->SetFillColor(223,223,223);
               $this->SetFont( 'Arial', 'B', 12 );
               $this->Cell(180,8,utf8_decode( 'INFORMACION DEL CLIENTE '),0,0,'L', TRUE);
    
               $this->Ln(10);
               
               $this->SetTextColor(0, 77,174);
               $this->SetFont( 'Arial', '', 10 );
  
               $this->Cell(180,8,utf8_decode('DATOS PERSONALES'),0,0,'J');
               $this->SetTextColor(0, 0,0);
               $this->SetFont( 'Arial', '', 8 );
               $this->Ln(7);
               $this->SetWidths(array(40, 70, 70));
               $this->SetAligns(array('J', 'J', 'J'));
               $this->Row(array(utf8_decode('DNI: '.$model['dni']), utf8_decode('NOMBRE(S): '.$model['nombre']), utf8_decode('APELLIDO(S): '.$model['apellido'])
               ));
            
               $this->SetWidths(array(80,100));
               $this->SetAligns(array('J', 'J'));
               $this->Row(array(utf8_decode('CELULAR: '.$model['celular']), 
                   utf8_decode('EMPLEO: '.$model['empleo']),
                 
                   )
               );
        
               $this->SetWidths(array(80, 50,50));
               $this->SetAligns(array('J', 'J','J'));
               $this->Row(array(utf8_decode('DIRECCION: '.$model['direccion']), 
                   utf8_decode('LT: '.$model['lt']),
                   utf8_decode('MZ: '.$model['mz'])
                   )
               );
               
               $this->SetWidths(array(40, 140));
               $this->SetAligns(array('J', 'J'));
               $this->Row(
               array(utf8_decode('ZONA: '.$model['zona']), 
                   utf8_decode('DISTRITO: '.$model['distrito'])
                   )
               );
               $this->Ln(2);
               $this->SetTextColor(0, 77,174);
               $this->SetFont( 'Arial', '', 10 );
               $this->Cell(180,8,utf8_decode('INFORMACION DEL PRESTAMO '),0,0,'J');
               $this->SetTextColor(0, 0,0);
               $this->SetFont( 'Arial', '', 8 );
               $this->Ln(7);
               
               $prestamo=Prestamo::buscar($model['id_cliente']);
               
               if(!empty($prestamo)){
               $this->SetWidths(array(60,60,60));
               $this->SetAligns(array('J','J'));
               $this->Row(array(utf8_decode('FECHA INICIO DEL CREDITO: '.  Utility::fecha($prestamo['fecha_inicio_credito'])),
                   utf8_decode('FECHA FINAL DEL CREDITO: '.  Utility::fecha(Cobro::fechaFinal($prestamo['id']))),
                   utf8_decode('MONTO CREDITO: '.  $prestamo['monto_credito']),
                   ));
               $this->SetWidths(array(60,60,60));
               $this->SetAligns(array('J','J'));
               $this->Row(array(utf8_decode('ESTATUS: '. Cobro::estatusPrestamo($prestamo['id'])),
                   utf8_decode('CUOTAS CANCELADAS: '. Cobro::cuotasCanceladas($prestamo['id'])),
                   utf8_decode('ATRAZOS: '. Cobro::atrazos($prestamo['id'])),
               ));
               }else{

               $this->SetWidths(array(180));
               $this->SetAligns(array('J'));
               $this->Row(array(utf8_decode('SIN CREDITO ASIGNADO')));
               }
               $this->Ln(2);
               $this->SetTextColor(0, 77,174);
               $this->SetFont( 'Arial', '', 10 );
               $this->Cell(180,8,utf8_decode('GESTOR'),0,0,'J');
               $this->SetTextColor(0, 0,0);
               $this->SetFont( 'Arial', '', 8 );
               $this->Ln(6);
            
               $this->SetWidths(array(180));
               $this->SetAligns(array('J'));
               $this->Row(array(utf8_decode('GESTOR: '.$model['gestor'])));
               $this->Ln(2);
                
               $this->SetTextColor(0, 77,174);
               $this->SetFont( 'Arial', '', 10 );
               $this->Cell(180,8,utf8_decode('OBSERVACION'),0,0,'J');
               $this->SetTextColor(0, 0,0);
               $this->SetFont( 'Arial', '', 8 );
               $this->Ln(6);
               
               $this->SetWidths(array(180));
               $this->SetAligns(array('J'));
               $this->Row(array(utf8_decode('OBSERVACION DEL CLIENTE: '.$model['observacion'])));

    } 
    

 
    function Footer() {
        $this->SetY(-25);
        $this->Ln();
        $this->SetX(10);
        $this->SetFont('Arial', '', 6);
        $this->Cell(180, 10, utf8_decode('GENERADO A TRAVES DEL SISTEMA  INV. SILVER DAILY EN FECHA ' . date('d/m/Y') . ' POR EL USUARIO: ' . rtrim(Yii::app()->user->name)), 0, 0, 'L');
        $this->Cell(20, 10, utf8_decode('Página ' . $this->PageNo() . '/{nb}'), 0, 0, 'R');
        
    }

function cronograma($model,$fechas) {
        
        $this->Ln(20);
        $this->SetFillColor(223,223,223);
        $this->SetFont( 'Arial', 'B', 12 );
        $this->Cell(180,8,utf8_decode( 'CRONOGRAMA DE PAGO '),0,0,'L', TRUE);
        $this->Ln(20);
        $this->Cell(90, 6, '', '', 0, 'C');
        $this->SetFont( 'Arial', 'B', 10 );
        $this->Cell(40, 6,'FECHA DE INICIO', 'RLBT', 0, 'C');
        $this->Cell(50, 6,Utility::fecha($model->fecha_inicio_credito), 'RLTB', 0, 'C');
        
        $this->Ln(6);
        $this->Cell(40, 6, 'GESTOR ', 'RLTB', 0, 'J');
        $this->Cell(40, 6, Gestor::descripcion($model->id_gestor_credito), 'RLTB', 0, 'J');
        $this->Cell(10, 6, '', '', 0, 'J');
         
        $this->SetFont( 'Arial', 'B', 10 );
        $this->Cell(40, 6,'DIA DE PAGO', 'RLB', 0, 'C');
        $this->Cell(50, 6, utf8_decode($model->dia_semana_credito), 'RLB', 0, 'C');
        
        
        
         $this->Ln(6);
        $this->Cell(40, 6, 'DNI CLIENTE', 'RLTB', 0, 'J');
        $this->Cell(40, 6, $model->dni, 'RLTB', 0, 'J');
        $this->Cell(10, 6, '', '', 0, 'J');
         
        $this->SetFont( 'Arial', 'B', 10 );
        $this->Cell(40, 6,'CREDITO', 'RLB', 0, 'C');
          $this->SetFont( 'Arial', '', 10 );
        $this->Cell(50, 6, 's/ '.number_format($model->monto_credito, 2, ',', '.'), 'RLB', 0, 'C');
        
        
        
        $this->Ln(6);
        $this->SetFont( 'Arial', 'B', 10 );
        $this->Cell(40, 6, 'NOMBRE', 'RLTB', 0, 'J');
        $this->SetFont( 'Arial', '', 10 );
        $this->Cell(40, 6, $model->nombre, 'RLTB', 0, 'J');
        $this->Cell(10, 6, '', '', 0, 'J');
         
        $this->SetFont( 'Arial', 'B', 10 );
        $this->Cell(40, 6,'CUOTAS', 'RLB', 0, 'C');
          $this->SetFont( 'Arial', '', 10 );
        $this->Cell(50, 6,$model->id_duracion, 'RLB', 0, 'C');
        
        
        $this->Ln(6);
        $this->SetFont( 'Arial', 'B', 10 );
        $this->Cell(40, 6, 'APELLIDO', 'RLTB', 0, 'J');
        $this->SetFont( 'Arial', '', 10 );
        $this->Cell(40, 6, $model->apellido, 'RLTB', 0, 'J');
        $this->Cell(10, 6, '', '', 0, 'J');
         
        $this->SetFont( 'Arial', 'B', 10 );
        $this->Cell(40, 6,'DEUDA', 'RLB', 0, 'C');
        $this->SetFont( 'Arial', '', 10 );
        $this->Cell(50, 6,number_format($model->cuota_credito*$model->id_duracion, 2, ',', '.'), 'RLB', 0, 'C');
        
        $this->SetFillColor(216, 216, 216);
        $this->Ln(20);
        $this->Cell(40, 8, 'CUOTA', 'RLT', 0, 'C',TRUE);
        $this->Cell(100, 8, 'FECHA CRON.', 'RT', 0, 'C',TRUE);
        $this->Cell(40, 8, 'CUOTAS CRONO.', 'LRT', 0, 'C',TRUE);
        
        $this->Ln(8);
        
        
        for ($i = 0; $i < count($fechas)-1; $i++) {
            $this->Cell(40, 8, $i+1, 'RLT', 0, 'C');
            $this->Cell(100, 8, Utility::fecha($fechas[$i]["fecha"]), 'RT', 0, 'C');
            $this->Cell(40, 8, 's/ '.$model->cuota_credito, 'RT', 0, 'C'); 
            $this->Ln(8);

        }

         $this->Cell(180, 8, '', 'T', 0, 'C');

    }
    
}

?>