<?php

class PrestamoController extends Controller
{
	
	public $layout='//layouts/column2';

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}



        
             public function accessRules()
	{
		return array(
			array('allow',  
				'actions'=>array('excelnuevo','nuevo','Carteraexcelr','renovar','comision','clientec','Carteraexcelc','Carterapdfc','carteracancelados','ajax','Carteraexcel','Carterapdf','cartera','CarteraStambay','actualizar','index','view',
                                    'cronograma','excel','create','update','delete','actualizarpendiente','actualizaratrasos','actualizaradelantado',
                    'actualizarmoras','actualizarcancelado','actualizarvencidos', 'actualizaraldia','pendientes'),
				'expression' => array('PrestamoController', 'validaracceso'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}

   
        
	public static function validaracceso() {
            if (!Yii::app()->user->isGuest) {
                   return true;
            } else {
                Yii::app()->user->setFlash('error', Yii::app()->params['sesion']);
                return false;
            }
        }
        
        
        public function actionPendientes()
	{
		$this->pageTitle = 'PRESTAMOS';
                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
		$model=new Prestamo('searchPendientes');
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('index',array(
			'model'=>$model
		));
	}    
    
        
         public function actionClientec()
	{
                $this->pageTitle = 'CONSULTAS CLIENTE';
                set_time_limit(0);


                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
                $prestamo=  Prestamo::lista();
		$model=new Prestamo('search');
                
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('clientec',array(
			'model'=>$model,'prestamo'=>$prestamo 
		));

	}
        

	public function actionView($id)
	{
                $model=$this->loadModel($id);
                $cliente= Cliente::model()->findByPk($model->id_cliente);
                $model->dni=$cliente->dni;
                $model->nombre=$cliente->nombre;
                $model->apellido=$cliente->apellido;
                $this->pageTitle = 'VER PRESTAMO N° '.$id;
                $model->id_usuario_creador = !empty($model->id_usuario_creador)?Usuario::descripcion($model->id_usuario_creador):null;
                $model->id_usuario_modificador = !empty($model->id_usuario_modificador)?Usuario::descripcion($model->id_usuario_modificador):null;
                $model->fecha_creacion = !empty($model->fecha_creacion)?Utility::fecha($model->fecha_creacion):null;
                $model->fecha_modificacion = !empty($model->fecha_modificacion)?Utility::fecha_hora($model->fecha_modificacion):null;	
                $model->id_gestor=$model->id_gestor!=null?Gestor::descripcion($model->id_gestor):'';
                $model->fecha_final= Utility::fecha(Pagos::fechaFinal($id));
                $model->fecha_inicio= Utility::fecha($model->fecha_inicio);
                $model->id_modalidad=$model->id_modalidad!=null?  Modalidad::descripcion($model->id_modalidad):'';
                $model->id_monto= number_format($model->id_monto, 2, ',', '.');
                $model->cuota= number_format($model->cuota, 2, ',', '.');
                $model->estatus= Pagos::estatusPrestamo($id);
                $model->atrasos=Pagos::atrazos($id);
                $model->cuotas_pagadas= Pagos::cuotasCanceladas($id);
                $model->hora_creacion=Utility::hora($model->hora_creacion);   
		$this->render('view',array(
			'model'=>$model,
		));
	}

	public function actionCreate()
	{
		$model=new Prestamo;
                $this->pageTitle = 'AGREGAR 1ER. PRESTAMO ';
                $model->scenario = 'create'; 
                
		if(isset($_POST['Prestamo']))
		{
			$model->attributes=$_POST['Prestamo'];
              
                  try
                  {    
               
                    $validar=Prestamo::model()->find('id_cliente=? and borrado=0',array($_POST['Prestamo']['id_cliente']));
                    if(!empty($validar)){
                          Yii::app()->user->setFlash('danger', 'EL CLIENTE YA TIENE UN CREDITO REGISTRADO EN EL SISTEMA.'); 
                          $this->redirect(array('index'));  
                    }else{
                     
                    $cliente=Cliente::model()->find('id_cliente=? and borrado=0',array($_POST['Prestamo']['id_cliente']));
                    if($cliente['recibir_prestamo']==2){
                        Yii::app()->user->setFlash('danger', 'EL CLIENTE ESTA BLOQUEADO PARA RECIBIR PRESTAMOS.'); 
                        $this->redirect(array('index')); 
                    }else{

                          $_POST['Prestamo']['num']=0;
                        
                          $cliente= Cliente::model()->find(array('condition'=>'id_cliente='.$_POST['Prestamo']['id_cliente'].' ' )  );   
     
                          $_POST['Prestamo']['id_gestor']  = $cliente['id_gestor'];
                        
                            
                            
                            if($_POST['Prestamo']['manual']==1){
                                $_POST['Prestamo']['id_monto']=$_POST['Prestamo']['id_monto2'];
                                $_POST['Prestamo']['id_duracion']=$_POST['Prestamo']['id_duracion2'];
                            }else{
                                $_POST['Prestamo']['tasa']=0;
                                $_POST['Prestamo']['interes']=0;
                            }
                            
            
                          
                          
                          
                          
                          
                        $agregar=  Prestamo::agregar();  
                        
                        if($agregar){   
                            
                            $resul=Prestamo::model()->find(array('condition'=>'id_cliente='.htmlspecialchars(addslashes(stripslashes(strip_tags(trim($_POST['Prestamo']['id_cliente']))))).' and borrado!=1','order'=>'id_prestamo desc'));
                            if(!empty($resul)){
                                Prestamo::estatusActualizar($resul['id_prestamo']);
                            }
                            Yii::app()->user->setFlash('success', Yii::app()->params['add']);
                            $this->redirect(array('index'));  
                        }
                        $model->unsetAttributes();     
                     }          
                    }
                   
                    }catch(Exception $e)
                    {
                     Yii::app()->user->setFlash('danger', Yii::app()->params['error']); 
                    }  
                        
                        
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}


	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
                $model->scenario = 'update'; 
                $this->pageTitle = 'MODIFICAR PRESTAMO';
                $model->fecha_inicio=  Utility::fecha($model->fecha_inicio);
                $cliente = Cliente::model()->find('id_cliente=?',array($model->id_cliente));
                $model->dni=$cliente['dni'];  
                $model->nombre=$cliente['nombre']; 
                $model->apellido=$cliente['apellido']; 
                $model->id_monto2= $model->id_monto;
                $model->id_duracion2=$model->id_duracion;
                
		if(isset($_POST['Prestamo']))
		{
			$model->attributes=$_POST['Prestamo'];
			try
                        {
                            if($_POST['Prestamo']['manual']==1){
                                $_POST['Prestamo']['id_monto']=$_POST['Prestamo']['id_monto2'];
                                $_POST['Prestamo']['id_duracion']=$_POST['Prestamo']['id_duracion2'];
                            }else{
                                $_POST['Prestamo']['tasa']=0;
                                $_POST['Prestamo']['interes']=0;
                            }     
                            
                      $editar= Prestamo::editar($id);
                      if ($editar) {
                        Prestamo::estatusActualizar($id);
                        $model->unsetAttributes();     
                        Yii::app()->user->setFlash('success', Yii::app()->params['edit']);
                        $this->redirect(array('index'));  
                      }
                    }catch(Exception $e)
                    {
                     Yii::app()->user->setFlash('danger', Yii::app()->params['error']); 
                    }
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}
        
	public function actionDelete($id)
	{
		$model= new Prestamo();
                $eliminar=$model->borrar($id);
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

	
	public function actionIndex()
	{
		$this->pageTitle = 'PRESTAMOS';
                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
		$model=new Prestamo('search');
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('index',array(
			'model'=>$model
		));
	}
        
        
         public function actionNuevo()
	{
		$this->pageTitle = 'NUEVOS';
                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
		$model=new Prestamo('search');
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('nuevo',array(
			'model'=>$model
		));
	}

        public function actionComision()
	{
		$this->pageTitle = 'COMISION POR VENTAS Y RENOCACIONES';
                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
		$model=new Prestamo('search');
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('comision',array(
			'model'=>$model
		));
	}
        
        
        
	public function loadModel($id)
	{
		$model=Prestamo::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='prestamo-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionCronograma($id)
	{   
             $this->layout='pdf';
            if(!empty($id)){
                
		$prestamo= Prestamo::model()->findByPk($id);
                $cliente= Cliente::model()->findByPk($prestamo->id_cliente);
                $gestor=  Gestor::model()->findByPk($prestamo->id_gestor);
                $fechas= Pagos::forFechas($prestamo->fecha_inicio, $prestamo->id_duracion, 1,$prestamo->domingo);
      
		if($prestamo===null){
			throw new CHttpException(404,'NUMERO DE PRESTAMO NO EXISTE.');
                }else{
                    set_time_limit(0);
                    Yii::import("application.vendors.cronograma", true);
                    $pdf = new PDF();
                    $pdf->AliasNbPages();
                    $pdf->title='CRONOGRAMA DE PAGOS ';
                    $pdf->SetMargins(15, 1, 2);
                    $pdf->AddPage('P','Letter');
                    $pdf->cronograma($prestamo,$cliente,$gestor,$fechas);
                    $pdf->SetDisplayMode('real','continuous');
                    $pdf->Output("cronograma.pdf",'I');
                }
		return $model;
            }
	}






 
        public function actionExcel()
	{ 
          $session=new CHttpSession;
          $session->open();
          Yii::import('ext.phpexcel.XPHPExcel');    
	  $objPHPExcel= XPHPExcel::createPHPExcel();
          $sheet = $objPHPExcel->getActiveSheet();
	  $objPHPExcel->getProperties()->setCreator("EXPORTAR A EXCEL")
							 ->setLastModifiedBy("EXPORTAR A EXCEL")
							 ->setTitle("EXPORTAR A EXCEL")
							 ->setSubject("EXPORTAR A EXCEL")
							 ->setDescription("EXPORTAR A EXCEL")
							 ->setKeywords("EXPORTAR A EXCEL")
							 ->setCategory("EXPORTAR A EXCEL");

          
            $objPHPExcel->getActiveSheet()->mergeCells('A2:W2');
            $objPHPExcel->getActiveSheet()->getStyle("A2:W2")->getFont()->setSize(14)->setBold( TRUE )->getColor()->setRGB('000000');
            $objPHPExcel->getActiveSheet()->getStyle("A5:W5")->getFont()->setSize(14)->setBold( TRUE )->getColor()->setRGB('000000');

            $sheet->getStyle('A5:W5')->getAlignment()->applyFromArray(
                  array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
            );
            
            $sheet->setCellValue('A2', CHtml::encode('PRESTAMOS'));
          
            /*$objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A5', CHtml::encode('ID'))
                        ->setCellValue('B5', CHtml::encode('PRESTAMO NUMERO'))
                        ->setCellValue('C5', CHtml::encode('DNI'))
                        ->setCellValue('D5', CHtml::encode('NOMBRES'))
                        ->setCellValue('E5', CHtml::encode('APELLIDOS'))
                        ->setCellValue('F5', CHtml::encode('FECHA INICIO'))
                        ->setCellValue('G5', CHtml::encode('FECHA FINAL'))
                        ->setCellValue('H5', CHtml::encode('DIA'))
                        ->setCellValue('I5', CHtml::encode('MODALIDAD'))
                        ->setCellValue('J5', CHtml::encode('DURACION'))
                        ->setCellValue('K5', CHtml::encode('MONTO CREDITO'))
                        ->setCellValue('L5', CHtml::encode('MONTO CUOTA'))
                        ->setCellValue('M5', CHtml::encode('CELULAR'))
                        ->setCellValue('N5', CHtml::encode('DIRECCION'))
                        ->setCellValue('O5', CHtml::encode('MZ'))
                        ->setCellValue('P5', CHtml::encode('LT'))
                        ->setCellValue('Q5', CHtml::encode('ZONA'))
                        ->setCellValue('R5', CHtml::encode('DISTRITO'))
                        ->setCellValue('S5', CHtml::encode('GESTOR'))
                        ->setCellValue('T5', CHtml::encode('OBSERVACION'))
                        ->setCellValue('U5', CHtml::encode('FECHA REGISTRO'))
                        ->setCellValue('V5', CHtml::encode('HORA DE ENTREGA'))
                    ;*/
            
                    
            $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A5', CHtml::encode('ID'))
                        ->setCellValue('B5', CHtml::encode('PRESTAMO NUMERO'))
                        ->setCellValue('C5', CHtml::encode('DNI'))
                        ->setCellValue('D5', CHtml::encode('NOMBRES'))
                        ->setCellValue('E5', CHtml::encode('APELLIDOS'))
                        ->setCellValue('F5', CHtml::encode('FECHA INICIO'))
                        ->setCellValue('G5', CHtml::encode('FECHA FINAL'))
                        ->setCellValue('H5', CHtml::encode('MONTO CREDITO'))
                        ->setCellValue('I5', CHtml::encode('MONTO CUOTA'))
                        ->setCellValue('J5', CHtml::encode('DESCUENTO SEGURO'))
                        ->setCellValue('K5', CHtml::encode('DESCUENTO 1RA CUOTA'))
                        ->setCellValue('L5', CHtml::encode('MONTO ENTREGA'))
                        ->setCellValue('M5', CHtml::encode('ESTATUS'))
                        ->setCellValue('N5', CHtml::encode('GESTOR'))
                        ->setCellValue('O5', CHtml::encode('FECHA REGISTRO'))
                        ->setCellValue('P5', CHtml::encode('HORA DE ENTREGA'))
                    ;        
            
            
            
            $d = $session['prestamo'];
            $n=5;
            $contenido=array();

            foreach ($d->data as $item) {
                
                $cliente= Cliente::model()->findByPk($item->id_cliente);
                $id_zona=$cliente->id_zona!=null?Zona::descripcion($cliente->id_zona):'';
                $id_distrito=$cliente->id_distrito!=null?Distrito::descripcion($cliente->id_distrito):'';
            
                
                $n=$n+1;
                $contenido[]=array(
                $item->id_prestamo,
                $item->num, 
                $item->dni, 
                CHtml::encode($item->nombre),
                CHtml::encode($item->apellido),
                Utility::fecha($item->fecha_inicio),
                Utility::fecha(Pagos::fechaFinal($item->id_prestamo)),
                $item->id_monto, 
                $item->cuota,
                $item->descuento_seguro,
                $item->descuento_primera_cuota,
                $item->monto_entrega,
                $item->estatus,
                CHtml::encode($item->gestor),
                Utility::fecha($item->fecha_creacion),
                CHtml::encode($item->hora_entrega),    
            );  
            
           }
            $objPHPExcel->getActiveSheet()->fromArray($contenido,NULL,'A6');
            for($col = 'A'; $col !== 'Q'; $col++) {
               $objPHPExcel->getActiveSheet()
                   ->getColumnDimension($col)
                   ->setAutoSize(true);
            }
            $sheet->getStyle("A5:P$n")->applyFromArray(
            array(
            'borders' => array(
               'allborders' => array(
                 'style' => PHPExcel_Style_Border::BORDER_THIN
               )
             ),
         ));
            $objPHPExcel->getActiveSheet()->setTitle('Simple');
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="prestamo.xls"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
            header ('Cache-Control: cache, must-revalidate');
            header ('Pragma: public');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
                  Yii::app()->end();
        }
 
        
        
        public function actionExcelnuevo()
	{ 
          $session=new CHttpSession;
          $session->open();
          Yii::import('ext.phpexcel.XPHPExcel');    
	  $objPHPExcel= XPHPExcel::createPHPExcel();
          $sheet = $objPHPExcel->getActiveSheet();
	  $objPHPExcel->getProperties()->setCreator("EXPORTAR A EXCEL")
							 ->setLastModifiedBy("EXPORTAR A EXCEL")
							 ->setTitle("EXPORTAR A EXCEL")
							 ->setSubject("EXPORTAR A EXCEL")
							 ->setDescription("EXPORTAR A EXCEL")
							 ->setKeywords("EXPORTAR A EXCEL")
							 ->setCategory("EXPORTAR A EXCEL");

          
            $objPHPExcel->getActiveSheet()->mergeCells('A2:F2');
            $objPHPExcel->getActiveSheet()->getStyle("A2:F2")->getFont()->setSize(14)->setBold( TRUE )->getColor()->setRGB('000000');
            $objPHPExcel->getActiveSheet()->getStyle("A5:F5")->getFont()->setSize(14)->setBold( TRUE )->getColor()->setRGB('000000');

            $sheet->getStyle('A5:F5')->getAlignment()->applyFromArray(
                  array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
            );
            
            $sheet->setCellValue('A2', CHtml::encode('PRESTAMOS NUEVOS'));
          
            $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A5', CHtml::encode('ID'))
                        ->setCellValue('B5', CHtml::encode('FECHA INICIO'))
                        ->setCellValue('C5', CHtml::encode('DNI'))
                        ->setCellValue('D5', CHtml::encode('NOMBRES'))
                        ->setCellValue('E5', CHtml::encode('APELLIDOS'))
    
                        ->setCellValue('F5', CHtml::encode('GESTOR'))
     
                    ;
            
            
            $d = $session['prestamo'];
            $n=5;
            $contenido=array();

            foreach ($d->data as $item) {
                
                $cliente= Cliente::model()->findByPk($item->id_cliente);
            
                $n=$n+1;
                $contenido[]=array(
                $item->id_prestamo,
                Utility::fecha($item->fecha_inicio),    
                $item->dni, 
                CHtml::encode($item->nombre),
                CHtml::encode($item->apellido),
                CHtml::encode($item->gestor),
              
                    
            );  
           }
            $objPHPExcel->getActiveSheet()->fromArray($contenido,NULL,'A6');
            for($col = 'A'; $col !== 'G'; $col++) {
               $objPHPExcel->getActiveSheet()
                   ->getColumnDimension($col)
                   ->setAutoSize(true);
            }
            $sheet->getStyle("A5:F$n")->applyFromArray(
            array(
            'borders' => array(
               'allborders' => array(
                 'style' => PHPExcel_Style_Border::BORDER_THIN
               )
             ),
         ));
            $objPHPExcel->getActiveSheet()->setTitle('Simple');
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="prestamo nuevos.xls"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
            header ('Cache-Control: cache, must-revalidate');
            header ('Pragma: public');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            Yii::app()->end();
        }
 
        public function actionActualizar()
	{
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTULIZAR';
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
		 
		    
                   Prestamo::estatusPagos();
                  
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}
            $this->render('actualizar',array(
                    'model'=>$model
            ));
	}           
 
        
           public function actionActualizarpendiente()
	{
            
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTUALIZAR PENDIENTE';
                     
            
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
                Prestamo::estatusPagosPendiente($_POST['date_desde'],$_POST['date_hasta']);
        
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}
                    
             
         
            
            $this->render('actualizarpendiente',array(
                    'model'=>$model
            ));
	} 
        
        
        public function actionActualizaradelantado()
	{
            
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTUALIZAR ADELANTADO';
                     
            
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
        
        Prestamo::estatusPagosAdelantado($_POST['date_desde'],$_POST['date_hasta']);
        
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}
                    
             
         
            
            $this->render('actualizarpendiente',array(
                    'model'=>$model
            ));
	}
    
        
    
    
          
             public function actionActualizaraldia()
	{
            
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTUALIZAR AL DIA';
                     
            
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
                  Prestamo::estatusPagosAldia($_POST['date_desde'],$_POST['date_hasta']);
        
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}
                    
             
         
            
            $this->render('actualizaraldia',array(
                    'model'=>$model
            ));
	} 
        
        
                    public function actionActualizaratrasos()
	{
            
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTUALIZAR  ATRASOS';
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
                  Prestamo::estatusPagosAtrasos();
        
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}

            $this->render('actualizartrasos',array(
                    'model'=>$model
            ));
	} 
        
             
        public function actionActualizarmoras()
	{
            
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTUALIZAR  MORAS';
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
		    
		      if($_POST['date_desde'] == "" || $_POST['date_hasta'] == ""){ 
		             echo '<script language="javascript">alert("DEBE DE COLOCAR RANGO DE FECHAS."); </script>';
		      }else{
                  Prestamo::estatusPagosMoras($_POST['date_desde'],$_POST['date_hasta']);
		      }
        
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}

            $this->render('actualizarmoras',array(
                    'model'=>$model
            ));
	} 
        
         public function actionActualizarcancelado()
	{
            
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTUALIZAR  CANCELADOS';
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
                    
                    try
                    {
                        
                        if($_POST['date_desde'] == "" || $_POST['date_hasta'] == ""){ 
                        echo '<script language="javascript">alert("DEBE DE COLOCAR RANGO DE FECHAS."); </script>';
                        
                        }else{
                        
                        Prestamo::estatusPagosCancelados($_POST['date_desde'],$_POST['date_hasta']);
                        
                        }
                        
                        
                    }catch(Exception $e)
                    {
                      echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    }   
                    
                  
        
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}

            $this->render('actualizarcancelado',array(
                    'model'=>$model
            ));
	} 
        
               public function actionActualizarvencidos()
	{
            
                $model=  Prestamo::model();
                $this->pageTitle = 'ACTUALIZAR VENCIDOS';
                set_time_limit(0);
		$this->performAjaxValidation($model);
		if(isset($_POST['Prestamo']))
		{
                  Prestamo::estatusPagosVencido();
        
                   echo '<script language="javascript">alert("ACTUALIZACION FINALIZO CON EXITO!!!"); </script>';
                    
		}

            $this->render('actualizarvencidos',array(
                    'model'=>$model
            ));
	} 
        
        
        
        
        
        
        
        
        
                public function actionCartera()
	{
                $this->pageTitle = 'CARTERA CLIENTES';
                set_time_limit(0);


                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
                $prestamo=  Prestamo::lista();
		$model=new Prestamo('search');
                $consular= new ConsultarForm();
                if(isset($_POST['ConsultarForm']))
		{
                    $model->attributes=$_POST['ConsultarForm'];
		}     
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('cartera',array(
			'model'=>$model,'prestamo'=>$prestamo,'consular'=> $consular
		));

	}
	
	
	public function actionCarteraStambay(){
	   $this->pageTitle = 'CARTERA CLIENTES';
       set_time_limit(0);


                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
        
        $prestamo=  Prestamo::lista();
		$model=new Prestamo('search');
                $consular= new ConsultarForm();
                if(isset($_POST['ConsultarForm']))
		{
                    $model->attributes=$_POST['ConsultarForm'];
		}     
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('carteraShelby',array(
			'model'=>$model,'prestamo'=>$prestamo,'consular'=> $consular
		));  
	    
	    
	    
	    
	}
 
        
        
        
                public function actionRenovar()
	{
                $this->pageTitle = 'POR RENOVAR';
                set_time_limit(0);


                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
                $prestamo=  Prestamo::lista();
		$model=new Prestamo('search');
                $consular= new ConsultarForm();
                if(isset($_POST['ConsultarForm']))
		{
                    $model->attributes=$_POST['ConsultarForm'];
		}     
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('renovar',array(
			'model'=>$model,'prestamo'=>$prestamo,'consular'=> $consular
		));

	}
 
        
        
        
        
        public function actionCarterapdf()
	{   
            $this->layout='pdf';
            $session=new CHttpSession;
            $session->open();

            if(!empty($session['cartera'])){
                    set_time_limit(0);
                    Yii::import("application.vendors.cartera", true);
                    $pdf = new PDF($orentation='P',$unit='mm',array(1100,1100));
                    $pdf->AliasNbPages();
                    $pdf->title='CARTERA DE GESTORES ';
                    $pdf->SetMargins(10, 12, 20);
                    $pdf->AddPage();
                    $dataProvider = $session['cartera']->getData();
                    $pdf->cartera($dataProvider);
                    $pdf->SetDisplayMode('real','continuous');
                    $pdf->Output("cartera.pdf",'I');
               
            }  else {
                throw new CHttpException(404,'NO EXISTEN REGISTROS EN CARTERA.');
            }
	}
         public function actionCarteraexcelr(){
           set_time_limit(0);

           $session=new CHttpSession;
           $session->open();

           if (isset($session['cartera'])) {

            Yii::import('ext.phpexcel.XPHPExcel');
            $objPHPExcel = XPHPExcel::createPHPExcel();
            $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
            $objPHPExcel->getActiveSheet()
              ->getPageSetup()
              ->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER);
            $objPHPExcel->getActiveSheet()->getPageSetup()->setScale(70);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setTop(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(0);
            $sheet = $objPHPExcel->getActiveSheet();
            $objDrawingPType = new PHPExcel_Worksheet_Drawing();
            $objPHPExcel->getProperties()->setCreator('NO RENOVADOS')
                               ->setLastModifiedBy('USUARIO: ')
                          ;
            for($col = 'A'; $col !== 'F'; $col++) {
               $objPHPExcel->getActiveSheet()
                   ->getColumnDimension($col)
                   ->setAutoSize(true);
             }
  
            $sheet->setCellValue('C2', 'CARTERA DE GESTORES');
            $objPHPExcel->getActiveSheet()->getStyle("C2")->getFont()->setSize(8)->setBold( false )->getColor()->setRGB('004DAE');

            $sheet->setCellValue('A4', 'FECHA:  '.date('d-m-Y'));
            $objPHPExcel->getActiveSheet()->getStyle('A6:F6')->getFont()->setSize(8)->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle("A6:F6")->getBorders()
                        ->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $objPHPExcel->getActiveSheet()->getStyle("A5:F5")->getBorders()
                        ->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);            
$objPHPExcel->getActiveSheet()->getStyle('A6:F6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('FFFF66 ');
$style = array( 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, ) ); 

$sheet->getStyle('A6:F6')->applyFromArray($style); 



//combinar celdas
$objPHPExcel->getActiveSheet()->mergeCells('C2:M2');

  
    $d = $session['cartera'];
    
    $data = array();
     $i=6;
    foreach ($d->data as $item) {
            $data[] = $item->attributes;
            $i=$i+1;
    }
    

    $header=array(
                'GESTOR',
               /* 'DIA',
                'ZONA',
                'ESTATUS',*/
                'NOMBRES',
                'APELLIDOS',
               /* 'CELULAR',
                'DURACION',
                'MODALIDAD',*/
        
                CHtml::encode('Nº PAGOS'),
               /* 'SOLES',*/
                CHtml::encode('Nº ATRAZOS'),
                'TOTAL',
               /* 'CUOTA',
                'PAGAR',
                'DEBE',
                'F.PAGO',
                'SALDO', 
                'DIRECCION',
                'MZ',
                'LT',
                'NUM.RENOVACION'*/
        
        );
    
 
    $contenido[]=$header;
    foreach($d->data as $item)
    {

    $contenido[]=array(
    CHtml::encode($item->gestor),    
    /*CHtml::encode($item->dia_prestamo), 
     CHtml::encode($item->zona),     
    CHtml::encode($item->estatus),*/        
    CHtml::encode($item->nombre),
    CHtml::encode($item->apellido),
        /*
    CHtml::encode($item->celular),
    CHtml::encode($item->id_duracion),  
   
    CHtml::encode(Modalidad::descripcion($item->id_modalidad)),    
*/
    CHtml::encode($item->cuotas_pagadas),    
   /* CHtml::encode($item->total), */      
    CHtml::encode($item->atrasos),      
    CHtml::encode($item->renovar),
        /*
    CHtml::encode($item->cuota),    
    CHtml::encode($item->pagar), 
    CHtml::encode($item->debe), 
    $item->cuotas_pagadas=="0"?null:Utility::fecha($item->fecha_ultimo_pago),    
    CHtml::encode($item->monto_ultimo_pago),   
    CHtml::encode($item->direccion),
    CHtml::encode($item->mz),
    CHtml::encode($item->lt),  
    CHtml::encode($item->num), */ 
    );  
  }
  
  
  
//DIA  
$sheet->getStyle("C7:C$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_amarillo'])
        )
    )
);
//zona
$sheet->getStyle("D7:D$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' =>Yii::app()->params['excel_verde'])
        )
    )
);





$sheet->getStyle("F7:F$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' =>Yii::app()->params['excel_mostaza'])
        )
    )
); 
        
  
     


    $sheet->getStyle("A6:F$i")->applyFromArray(
    array(

         'borders' => array(
    'allborders' => array(
      'style' => PHPExcel_Style_Border::BORDER_THIN
    )
  ),
  
  'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ),
  
  'font'=>array(
        'bold'  => true,
        'size'  => 8,
    ),
  
 )
  
);





$BStyle = array(
  'borders' => array(
    'allborders' => array(
      'style' => PHPExcel_Style_Border::BORDER_THIN
    )
  )
);


  $objPHPExcel->getActiveSheet()->getStyle('A8:L8')->applyFromArray($BStyle);
  $objPHPExcel->getActiveSheet()->fromArray($contenido,NULL,'A6');
  $objPHPExcel->getActiveSheet()->setTitle('REPORTE CARTERA');
  $objPHPExcel->setActiveSheetIndex(0);
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="NO RENOVADOS.xls"');
  header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); 
  header ('Cache-Control: cache, must-revalidate'); 
  header ('Pragma: public'); 
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  $objWriter->save('php://output');
 
  exit;
 
}else {
    $this->redirect('cartera');
}

 }       
        
        
           public function actionCarteraexcel(){
           set_time_limit(0);

           $session=new CHttpSession;
           $session->open();

           if (isset($session['cartera'])) {

            Yii::import('ext.phpexcel.XPHPExcel');
            $objPHPExcel = XPHPExcel::createPHPExcel();
            $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
            $objPHPExcel->getActiveSheet()
              ->getPageSetup()
              ->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER);
            $objPHPExcel->getActiveSheet()->getPageSetup()->setScale(70);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setTop(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(0);
            $sheet = $objPHPExcel->getActiveSheet();
            $objDrawingPType = new PHPExcel_Worksheet_Drawing();
            $objPHPExcel->getProperties()->setCreator('CARTERA DE GESTORES')
                               ->setLastModifiedBy('USUARIO: ')
                          ;
            for($col = 'A'; $col !== 'Z'; $col++) {
               $objPHPExcel->getActiveSheet()
                   ->getColumnDimension($col)
                   ->setAutoSize(true);
             }
  
            $sheet->setCellValue('C2', 'CARTERA DE GESTORES');
            $objPHPExcel->getActiveSheet()->getStyle("C2")->getFont()->setSize(8)->setBold( false )->getColor()->setRGB('004DAE');

            $sheet->setCellValue('A4', 'FECHA:  '.date('d-m-Y'));
            $objPHPExcel->getActiveSheet()->getStyle('A6:X6')->getFont()->setSize(8)->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle("A6:X6")->getBorders()
                        ->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $objPHPExcel->getActiveSheet()->getStyle("A5:X5")->getBorders()
                        ->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);            
$objPHPExcel->getActiveSheet()->getStyle('A6:X6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('FFFF66 ');
$style = array( 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, ) ); 

$sheet->getStyle('A6:W6')->applyFromArray($style); 



//combinar celdas
$objPHPExcel->getActiveSheet()->mergeCells('C2:M2');

  
    $d = $session['cartera'];
    
    $data = array();
     $i=6;
    foreach ($d->data as $item) {
            $data[] = $item->attributes;
            $i=$i+1;
    }
    

    $header=array(
                'GESTOR',
                'FECHA INICIO',
                'FECHA FIN',
                'DIA',
                'ZONA',
                'ESTATUS',
                'NOMBRES',
                'APELLIDOS',
                'CELULAR',
                'DURACION',
                'MODALIDAD',
        
                CHtml::encode('Nº PAGOS'),
                'SOLES',
                CHtml::encode('Nº ATRAZOS'),
                'CREDITO',
                'CUOTA',
                'PAGAR',
                'DEBE',
                'F.PAGO',
                'SALDO', 
                'DIRECCION',
                'MZ',
                'LT',
                'NUM.RENOVACION'
        
        );
    
 
    $contenido[]=$header;
    foreach($d->data as $item)
    {

    $contenido[]=array(
    CHtml::encode($item->gestor),   
    CHtml::encode($item->fecha_inicio),
    CHtml::encode(Pagos::fecha_ultima($item->fecha_inicio, $item->id_duracion, 1)),
    CHtml::encode($item->dia_prestamo), 
     CHtml::encode($item->zona),     
    CHtml::encode($item->estatus),        
    CHtml::encode($item->nombre),
    CHtml::encode($item->apellido),
    CHtml::encode($item->celular),
    CHtml::encode($item->id_duracion),  
   
    CHtml::encode(Modalidad::descripcion($item->id_modalidad)),    

    CHtml::encode($item->cuotas_pagadas),    
    CHtml::encode($item->total),        
    CHtml::encode($item->atrasos),      
    CHtml::encode($item->id_monto),
    CHtml::encode($item->cuota),    
    CHtml::encode($item->pagar), 
    CHtml::encode($item->debe), 
    $item->cuotas_pagadas=="0"?null:Utility::fecha($item->fecha_ultimo_pago),    
    CHtml::encode($item->monto_ultimo_pago),   
    CHtml::encode($item->direccion),
    CHtml::encode($item->mz),
    CHtml::encode($item->lt),  
    CHtml::encode($item->num),  
    );  
  }
  
  
  
//DIA  
$sheet->getStyle("E7:E$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_amarillo'])
        )
    )
);
//zona
$sheet->getStyle("F7:F$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' =>Yii::app()->params['excel_rosado'])
        )
    )
);


$sheet->getStyle("G7:G$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' =>Yii::app()->params['excel_mostaza'])
        )
    )
); 


$sheet->getStyle("H7:H$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' =>Yii::app()->params['excel_mostaza'])
        )
    )
); 
        
                $sheet->getStyle("I7:I$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' =>Yii::app()->params['excel_rosado'])
        )
    )
);  


        $sheet->getStyle("J7:J$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_verde_claro'])
        )
    )
);
  
        $sheet->getStyle("K7:K$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_rosado'])
        )
    )
);

        


    $sheet->getStyle("L7:L$i")->applyFromArray(
        array(
            'fill' => array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb' => Yii::app()->params['excel_verde_claro'])
            )
        )
    );







      $sheet->getStyle("M7:M$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_azul_oscuro'])
        )
    )
);

      
      
      
      
    $sheet->getStyle("N7:N$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            
            
            'color' => array('rgb' => Yii::app()->params['excel_rosado'])
            
        )
    )
);
   
    
    $sheet->getStyle("O7:O$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_amarillo'])
        )
    )
);
    
            $sheet->getStyle("P7:P$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_azul_oscuro'])
        )
    )
);


     $sheet->getStyle("Q7:Q$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_verde_claro'])
        )
    )
);
  
       $sheet->getStyle("Q7:Q$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_amarillo_oscuro'])
        )
    )
);
    
    
      $sheet->getStyle("V7:V$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_azul_claro'])
        )
    )
);

$sheet->getStyle("W7:W$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_amarillo'])
        )
    )
);
  
        $sheet->getStyle("X7:X$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => Yii::app()->params['excel_rosado'])
        )
    )
);


 


    $sheet->getStyle("A6:X$i")->applyFromArray(
    array(

         'borders' => array(
    'allborders' => array(
      'style' => PHPExcel_Style_Border::BORDER_THIN
    )
  ),
  
  'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ),
  
  'font'=>array(
        'bold'  => true,
        'size'  => 8,
    ),
  
 )
  
);





$BStyle = array(
  'borders' => array(
    'allborders' => array(
      'style' => PHPExcel_Style_Border::BORDER_THIN
    )
  )
);


  $objPHPExcel->getActiveSheet()->getStyle('A8:L8')->applyFromArray($BStyle);
  $objPHPExcel->getActiveSheet()->fromArray($contenido,NULL,'A6');
  $objPHPExcel->getActiveSheet()->setTitle('REPORTE CARTERA');
  $objPHPExcel->setActiveSheetIndex(0);
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="CARTERA GESTORES.xls"');
  header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); 
  header ('Cache-Control: cache, must-revalidate'); 
  header ('Pragma: public'); 
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  $objWriter->save('php://output');
 
  exit;
 
}else {
    $this->redirect('cartera');
}

 }       
        
      public function actionAjax()
	{
            
                        $gestor=$_POST['gestor'];
                        $zona=$_POST['zona'];
                        $estatus=$_POST['estatus'];
                        $cant=$_POST['cant'];
                        $credito=$_POST['credito'];
                        $id_modalidad=$_POST['id_modalidad'];
                        
                        
                        
                        $datos = ConsultarForm::datos($gestor,$zona,$estatus,$cant,$credito,$id_modalidad);
                        
                        if(!empty($datos)){
                    
                        $res=array(
                            'clientes'=>$datos['clientes']==NULL?'0':$datos['clientes'],
                            'soles'=>$datos['soles']==NULL?'0':number_format($datos['soles'], 0, '', '.'),
                            'capitalinteres'=>$datos['capitalinteres']==NULL?'0':number_format($datos['capitalinteres'], 0, '', '.'),
                            'ingreso'=>$datos['ingreso']==NULL?'0':number_format($datos['ingreso'], 0, '', '.'),
                            'porcobrar'=>$datos['porcobrar']==NULL?'0':number_format($datos['porcobrar'], 0, '', '.'),
                        );
                        }else {
                            $res=array( 
                            'clientes'=>'0',    
                            'soles'=>'0',
                            'capitalinteres'=>'0',
                            'ingreso'=>'0',
                            'porcobrar'=>'0',
                        );
                        }
                        echo json_encode($res);
               
               
               
	}
        
        
           
       
        
        
                public function actionCarteracancelados()
	{
                $this->pageTitle = 'CARTERA CLIENTES CANCELADOS';
                set_time_limit(0);


                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
                $prestamo=  Prestamo::lista();
		$model=new Prestamo('search');
                $consular= new ConsultarForm();
                if(isset($_POST['ConsultarForm']))
		{
                    $model->attributes=$_POST['ConsultarForm'];
		}     
		$model->unsetAttributes();  
		if(isset($_GET['Prestamo']))
			$model->attributes=$_GET['Prestamo'];
                
		$this->render('carteracancelados',array(
			'model'=>$model,'prestamo'=>$prestamo,'consular'=> $consular
		));

	}
 
        public function actionCarterapdfc()
	{   
            $this->layout='pdf';
            $session=new CHttpSession;
            $session->open();

            if(!empty($session['cancelados'])){
                    set_time_limit(0);
                    Yii::import("application.vendors.carteracancelados", true);
                    $pdf = new PDF($orentation='P',$unit='mm',array(1100,1100));
                    $pdf->AliasNbPages();
                    $pdf->title='CARTERA DE GESTORES CANCELADOS ';
                    $pdf->SetMargins(10, 12, 20);
                    $pdf->AddPage();
                    $dataProvider = $session['cancelados']->getData();
                    $pdf->cartera($dataProvider);
                    $pdf->SetDisplayMode('real','continuous');
                    $pdf->Output("carteracancelados.pdf",'I');
               
            }  else {
                throw new CHttpException(404,'NO EXISTEN REGISTROS EN CARTERA.');
            }
	}
        
        
           public function actionCarteraexcelc(){
           set_time_limit(0);

           $session=new CHttpSession;
           $session->open();

           if (isset($session['cancelados'])) {

            Yii::import('ext.phpexcel.XPHPExcel');
            $objPHPExcel = XPHPExcel::createPHPExcel();
            $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
            $objPHPExcel->getActiveSheet()
              ->getPageSetup()
              ->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER);
            $objPHPExcel->getActiveSheet()->getPageSetup()->setScale(70);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setTop(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0);
            $objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(0);
            $sheet = $objPHPExcel->getActiveSheet();
            $objDrawingPType = new PHPExcel_Worksheet_Drawing();
            $objPHPExcel->getProperties()->setCreator('CARTERA DE GESTORES')
                               ->setLastModifiedBy('USUARIO: ')
                          ;
            for($col = 'A'; $col !== 'Z'; $col++) {
               $objPHPExcel->getActiveSheet()
                   ->getColumnDimension($col)
                   ->setAutoSize(true);
             }
  
            $sheet->setCellValue('C2', 'CARTERA DE GESTORES CANCELADOS');
            $objPHPExcel->getActiveSheet()->getStyle("C2")->getFont()->setSize(8)->setBold( false )->getColor()->setRGB('004DAE');

            $sheet->setCellValue('A4', 'FECHA:  '.date('d-m-Y'));
            $objPHPExcel->getActiveSheet()->getStyle('A6:U6')->getFont()->setSize(8)->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle("A6:U6")->getBorders()
                        ->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $objPHPExcel->getActiveSheet()->getStyle("A5:U5")->getBorders()
                        ->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);            
$objPHPExcel->getActiveSheet()->getStyle('A6:U6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('FFFF66 ');
$style = array( 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, ) ); 

$sheet->getStyle('A6:U6')->applyFromArray($style); 



//combinar celdas
$objPHPExcel->getActiveSheet()->mergeCells('C2:M2');

  
    $d = $session['cancelados'];
    
    $data = array();
     $i=6;
    foreach ($d->data as $item) {
            $data[] = $item->attributes;
            $i=$i+1;
    }
    

    $header=array(
                'GESTOR',
                'DIA',
                'ZONA',
                'ESTATUS',
                'NOMBRES',
                'APELLIDOS',
                'CELULAR',
                'DURACION',
        
        
                CHtml::encode('Nº PAGOS'),
                'SOLES',
                CHtml::encode('Nº ATRAZOS'),
                'CREDITO',
                'CUOTA',
                'PAGAR',
                'DEBE',
                'F.PAGO',
                'SALDO', 
                'DIRECCION',
                'MZ',
                'LT',
                'NUM.RENOVACION'
        
        );
    
 
    $contenido[]=$header;
    foreach($d->data as $item)
    {

    $contenido[]=array(
    CHtml::encode($item->gestor),    
    CHtml::encode($item->dia_prestamo), 
     CHtml::encode($item->zona),     
    CHtml::encode($item->estatus),        
    CHtml::encode($item->nombre),
    CHtml::encode($item->apellido),
    CHtml::encode($item->celular),
    CHtml::encode($item->id_duracion),    
    CHtml::encode($item->cuotas_pagadas),    
    CHtml::encode($item->total),        
    CHtml::encode($item->atrasos),      
    CHtml::encode($item->id_monto),
    CHtml::encode($item->cuota),    
    CHtml::encode($item->pagar), 
    CHtml::encode($item->debe), 
    $item->cuotas_pagadas=="0"?null:Utility::fecha($item->fecha_ultimo_pago),    
    CHtml::encode($item->monto_ultimo_pago),   
    CHtml::encode($item->direccion),
    CHtml::encode($item->mz),
    CHtml::encode($item->lt),  
    CHtml::encode($item->num),  
    );  
  }
  
  
  

  
$sheet->getStyle("B7:B$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FFD933')
        )
    )
);

$sheet->getStyle("C7:C$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '54C867')
        )
    )
);
$sheet->getStyle("E7:E$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FFA07A')
        )
    )
); 
     

$sheet->getStyle("F7:F$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FFA07A')
        )
    )
); 
        
$sheet->getStyle("H7:H$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'EF3CBD')
        )
    )
);  
       $sheet->getStyle("G7:G$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '54C867')
        )
    )
);

        $sheet->getStyle("I7:I$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '54C867')
        )
    )
);
  
        $sheet->getStyle("J7:J$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '54C867')
        )
    )
);

        


       $sheet->getStyle("K7:K$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'EF3CBD')
        )
    )
);




   
    
    $sheet->getStyle("L7:L$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FFD933')
        )
    )
);
    
            $sheet->getStyle("M7:M$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '54AACC')
        )
    )
);
     $sheet->getStyle("N7:N$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '54C867')
        )
    )
);
  
       $sheet->getStyle("O7:O$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FFD933')
        )
    )
);
    
    
      $sheet->getStyle("R7:R$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '54AACC')
        )
    )
);

$sheet->getStyle("S7:S$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FFD933')
        )
    )
);
  

 


    $sheet->getStyle("A6:U$i")->applyFromArray(
    array(

         'borders' => array(
    'allborders' => array(
      'style' => PHPExcel_Style_Border::BORDER_THIN
    )
  ),
  
  'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ),
  
  'font'=>array(
        'bold'  => true,
        'size'  => 8,
    ),
  
 )
  
);



$sheet->getStyle("T7:T$i")->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'EF3CBD')
        )
    )
);  


$BStyle = array(
  'borders' => array(
    'allborders' => array(
      'style' => PHPExcel_Style_Border::BORDER_THIN
    )
  )
);


  $objPHPExcel->getActiveSheet()->getStyle('A8:L8')->applyFromArray($BStyle);
  $objPHPExcel->getActiveSheet()->fromArray($contenido,NULL,'A6');
  $objPHPExcel->getActiveSheet()->setTitle('REPORTE CARTERA');
  $objPHPExcel->setActiveSheetIndex(0);
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="CARTERA GESTORES CANCELADOS.xls"');
  header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); 
  header ('Cache-Control: cache, must-revalidate'); 
  header ('Pragma: public'); 
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  $objWriter->save('php://output');
 
  exit;
 
}else {
    $this->redirect('cartera');
}

 }       
        
        
        
        
}
