<?php

class TransferenciaController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

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

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  
				'actions'=>array('pdf','excel','index','view','create','update','delete'),
				'expression' => array('TransferenciaController', 'iniciarseccion'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}

        public static function iniciarseccion() {
            if (!Yii::app()->user->isGuest) {
                return true;
            } else {
                Yii::app()->user->setFlash('danger', Yii::app()->params['sesion']);
                return false;
            }
        }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionCreate()
	{       $this->pageTitle = 'REGISTRAR RENDICION';
		$model=new Transferencia;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Transferencia']))
		{
                       
                 
                        if($_POST['Transferencia']['transferencia']==null){
                            $_POST['Transferencia']['transferencia']='0';
                        }
                    
                        if($_POST['Transferencia']['cobranza']==null){
                            $_POST['Transferencia']['cobranza']='0';
                        }
                        if($_POST['Transferencia']['total']==null){
                            $_POST['Transferencia']['total']='0';
                        }
                        if($_POST['Transferencia']['credito_nuevo']==null){
                            $_POST['Transferencia']['credito_nuevo']='0';
                        }
                        if($_POST['Transferencia']['renovacion']==null){
                            $_POST['Transferencia']['renovacion']='0';
                        }
                        if($_POST['Transferencia']['desc_banco']==null){
                            $_POST['Transferencia']['desc_banco']='0';
                        }
                        if($_POST['Transferencia']['otro_gasto']==null){
                            $_POST['Transferencia']['otro_gasto']='0';
                        }
                        if($_POST['Transferencia']['debe_depositar']==null){
                            $_POST['Transferencia']['debe_depositar']='0';
                        }

                        try
                        {
                        $agregar= Transferencia::add();   
                        if ($agregar){
                            
                        
                            Yii::app()->user->setFlash('success', '¡La rendición se ha guardado exitosamente!');
                            $this->redirect(array('index'));  
                            }  else {
                               Yii::app()->user->setFlash('info', 'Error al agregar la rendición.');
                            }
                        }catch(Exception $e)
                        {
                         Yii::app()->user->setFlash('danger', Yii::app()->params['error']); 
                        } 
                         
		}

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

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
                $this->pageTitle = 'MODIFICAR RENDICION';
                $model->fecha= Utility::fecha($model->fecha);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Transferencia']))
		{
                     
                        if($_POST['Transferencia']['transferencia']==null){
                            $_POST['Transferencia']['transferencia']='0';
                        }
                        if($_POST['Transferencia']['cobranza']==null){
                            $_POST['Transferencia']['cobranza']='0';
                        }
                        if($_POST['Transferencia']['total']==null){
                            $_POST['Transferencia']['total']='0';
                        }
                        if($_POST['Transferencia']['credito_nuevo']==null){
                            $_POST['Transferencia']['credito_nuevo']='0';
                        }
                        if($_POST['Transferencia']['renovacion']==null){
                            $_POST['Transferencia']['renovacion']='0';
                        }
                        if($_POST['Transferencia']['desc_banco']==null){
                            $_POST['Transferencia']['desc_banco']='0';
                        }
                        if($_POST['Transferencia']['otro_gasto']==null){
                            $_POST['Transferencia']['otro_gasto']='0';
                        }
                        if($_POST['Transferencia']['debe_depositar']==null){
                            $_POST['Transferencia']['debe_depositar']='0';
                        }

                     try
                        {
                       
                            $editar= Transferencia::edit($id);  
                         
                            
                            Yii::app()->user->setFlash('success', 'La rendición fue actualizada con éxito.');   
                            $this->redirect(Yii::app()->request->baseUrl."/transferencia");

                        }catch(Exception $e)
                        {
                         Yii::app()->user->setFlash('danger', Yii::app()->params['error']); 
                        } 
			
		}

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

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model= new Transferencia();
                $model->borrar($id);
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	public function actionIndex()
	{       $this->pageTitle = 'RENDICION GESTOR';
            
                if (isset($_GET['pageSize'])) {
                    Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
                    unset($_GET['pageSize']);
                }
		$model=new Transferencia('search');
		$model->unsetAttributes();
		if(isset($_GET['Transferencia']))
			$model->attributes=$_GET['Transferencia'];

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

	
	public function loadModel($id)
	{
		$model=Transferencia::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Transferencia $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='transferencia-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        
         public function actionExcel(){
            $this->layout = 'pdf'; 
            set_time_limit(0);
            header("Content-Type: application/vnd.ms-excel; charset=utf-8");
            header("Content-Disposition: attachment; filename=rendicion.xls");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);

            $t1='';
            $t1.='<th>FECHA</th>';
            $t1.='<th>RESPONSABLE</th>';
            $t1.='<th>TRANSFERENCIA</th>';
            $t1.='<th>'.CHtml::encode('COBRANZA').'</th>';
            $t1.='<th>TOTAL</th>';
            $t1.='<th>CREDITOS NUEVOS</th>';
            $t1.='<th>RENOVACIONES</th>';
            $t1.='<th>DESC. BANCO</th>'; 
            $t1.='<th>OTROS GASTOS</th>';
            $t1.='<th>DEBE DEPOSITAR</th>';
            $t1.='<th>OBSERVACION</th>';
            
            
            $session=new CHttpSession;
	    $session->open();
            $d1 = $session['transferencia'];

            $t2='';
            foreach ($d1->data as $item) {
                $t2.='<tr>';
                $t2.='<td>'. Utility::fecha($item->fecha).'</td>';
                $t2.='<td>'.CHtml::encode($item->responsable).'</td>';
                $t2.='<td>'.$item->transferencia.'</td>';
                $t2.='<td>'.$item->cobranza.'</td>';
                $t2.='<td>'.$item->total.'</td>';
                $t2.='<td>'.$item->credito_nuevo.'</td>';
                $t2.='<td>'.$item->renovacion.'</td>';
                $t2.='<td>'.$item->desc_banco.'</td>';
                $t2.='<td>'.$item->otro_gasto.'</td>';
                $t2.='<td>'.$item->debe_depositar.'</td>';
                $t2.='<td>'.$item->observacion.'</td>';
                $t2.='</tr>';
            }
            
            echo utf8_decode('<html><body> <br><b>RENDICION</b><br> <br>  '
                   . '<table  border="1"  >'
                   .'<thead>
                   <tr style="background-color: #ffff00;">
                   '.$t1.'
                   </tr>
                 </thead>'
                   . '<tbody>'.$t2.'</tbody>'
                   . '</table>'

                    . '</body></html>');

      }
        
        
        
        
        
        
}
