<?php

class EmpleadoController 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
		);
	}

        public function accessRules()
	{
		return array(
			array('allow',  
				'actions'=>array('excel','index','view','create','update','delete'),
				'expression' => array('EmpleadoController', '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;
            }
        }
        
	public function actionView($id)
	{
                $this->pageTitle = 'EMPLEADO';
            
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	
	public function actionCreate()
	{
		$this->pageTitle = 'REGISTRAR EMPLEADO';
                
                $model=new Empleado;
                $model->scenario= 'create';
                $model->foto='foto.png';

                $this->performAjaxValidation($model);
                
		if(isset($_POST['Empleado']))
		{
			$model->attributes=$_POST['Empleado'];
                        
                        //validar que aya ingresado el numero de dni
                    
                    
                            $rnd = rand(0,9999);
                            if(!empty($_FILES["Empleado"]["name"]['foto'])){
                             if($_FILES["Empleado"]["name"]['foto']) {
                              $filename = $rnd.'-'.$_FILES["Empleado"]["name"]['foto'];
                              $model->foto=$filename;
                              $source = $_FILES["Empleado"]["tmp_name"]['foto'];
                              $directorio = 'upload/';
                              if(!file_exists($directorio)){
                                      mkdir($directorio, 0777) or die("No se puede crear el directorio de extracci&oacute;n");	
                              }
                              $dir=opendir($directorio);
                              $target_path = $directorio.'/'.$filename;
                              if(move_uploaded_file($source, $target_path)) {
                                  $file = explode('.',$filename);
                              }	
                              closedir($dir);   
                              $_POST['Empleado']['foto']=$filename;
                              $model->foto=$_POST['Empleado']['foto'];
                            }
                        }
                        
                       //validar que el empleado no este registrado en el sistema
                        $validar= Empleado::validarEmpleado($_POST['Empleado']['dni']);
                        if(empty($validar)){
                                if($model->validate()){    
                                try
                                {    
                                  $agregar= $model->add();
                                  if ($agregar) {
                                  $model->unsetAttributes();     
                                  Yii::app()->user->setFlash('success', Yii::app()->params['add']);
                                  $this->redirect(array('index'));  
                                  }

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

                                }
                        }else{
                            Yii::app()->user->setFlash('danger', 'DNI YA ESTA REGISTRADO EN EL SISTEMA. ');
                        }  
                        
                        
                      }
		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionUpdate($id)
	{
            
                $this->pageTitle = 'MODIFICAR EMPLEADO';
            
		$model=$this->loadModel($id);
                
                
                
                $model->scenario= 'update';
		$this->performAjaxValidation($model);

		if(isset($_POST['Empleado']))
		{
			$model->attributes=$_POST['Empleado'];
                        
                        
                        $rnd = rand(0,9999);
                       if(!empty($_FILES["Empleado"]["name"]['foto'])){
                       if($_FILES["Empleado"]["name"]['foto']) {
                        $filename = $rnd.'-'.$_FILES["Empleado"]["name"]['foto'];
                        $model->foto=$filename;
                        $source = $_FILES["Empleado"]["tmp_name"]['foto'];
                        $directorio = 'upload/';
                        if(!file_exists($directorio)){
                                mkdir($directorio, 0777) or die("No se puede crear el directorio de extracci&oacute;n");	
                        }
                        $dir=opendir($directorio);
                        $target_path = $directorio.'/'.$filename;
                        
                        if(move_uploaded_file($source, $target_path)) {
                            $file = explode('.',$filename);
                            $_POST['Empleado']['foto']=$filename;
                        }	
                        closedir($dir);            
                        $model->foto=$_POST['Empleado']['foto'];
                        
                      }
                  }  else {
                      $_POST['Empleado']['foto']=$model->foto;
                  }
                        
                        
                        
                        
                        
                        
                       // if($model->validate()){    
                        try
                        {
                          $editar=$model->edit($id);  
                       
                          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 Empleado();
                $model->borrar($id);
                
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

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

		$this->render('index',array(
			'model'=>$model,
		));
	}
        
	public function loadModel($id)
	{
		$model=Empleado::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']==='empleado-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=empleados.xls");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);

            $t1='';
            $t1.='<th>DNI</th>';
            $t1.='<th>NOMBRES</th>';
            $t1.='<th>APELLIDOS</th>';
            $t1.='<th>DIRECCION</th>';
            $t1.='<th>MZ</th>';
            $t1.='<th>LT</th>';
            $t1.='<th>NRO. CELULAR</th>';
    
            $d1 = $_SESSION['empleados'];
            $t2='';
            foreach ($d1->data as $item) {
                $t2.='<tr>';
                $t2.='<td>'.$item->dni.'</td>'; 
                $t2.='<td>'.CHtml::encode($item->nombre).'</td>'; 
                $t2.='<td>'.CHtml::encode($item->apellido).'</td>';
                $t2.='<td>'.CHtml::encode($item->direccion).'</td>';
                $t2.='<td>'.CHtml::encode($item->mz).'</td>';
                $t2.='<td>'.CHtml::encode($item->lt).'</td>';
                $t2.='<td>'.CHtml::encode($item->nro_celular).'</td>';
                
                $t2.='</tr>';
            }
              echo utf8_decode('<html><body> <br><b>EMPLEADOS</b><br> <br>  '
                    . '<table  border="1"  >'
                   .'<thead>
                   <tr style="background-color: #ffff00;">
                   '.$t1.'
                   </tr>
                 </thead>'
                   . '<tbody>'.$t2.'</tbody>'
                   . '</table>'

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

      }
        
        
        
}
