<?php

class PreinscripcionController 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
			array('CrugeAccessControlFilter')
		);
	}

	/**
	 * 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',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('create'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('update','view','aprobar', 'reporteExcel'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * 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),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Preinscripcion;

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

		if(isset($_POST['Preinscripcion']))
		{
			$model->attributes=$_POST['Preinscripcion'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$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);
		$model->scenario = 'Update';
		$model->fechanacimiento = date(('d-m-Y'), strtotime($model->fechanacimiento));
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Preinscripcion']))
		{
			$model->attributes=$_POST['Preinscripcion'];
			if($model->save()) {
				$this->redirect(array('view','id'=>$model->id));
            }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	public function actionAprobar($id)
	{
		$model=$this->loadModel($id);
		$model->scenario = 'Update';
		$model->fechanacimiento = date(('d-m-Y'),strtotime($model->fechanacimiento));
		$modelSeguimiento =new PreinscripcionSeguimiento('Aprobar');
		$modelSeguimiento->fecha_registro_inscripcion = date(('d-m-Y'));
		$modelSeguimiento->idpreinscripcion = $id;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['PreinscripcionSeguimiento']))
		{
			$valido = false;
			$modelSeguimiento->attributes=$_POST['PreinscripcionSeguimiento'];
			if (isset($_POST['yt0'])) {
				$modelSeguimiento->scenario ='Aprobar';
				$modelSeguimiento->id_estatus_preinscripcion = 2;
				$valido = true;
			}
			elseif (isset($_POST['yt1'])) {
				$modelSeguimiento->scenario ='Denegar';
				$modelSeguimiento->id_estatus_preinscripcion = 3;
				$valido = true;
				# code...
			}
			if($valido){
				if($modelSeguimiento->validate()){
					$transaction = Yii::app()->db->beginTransaction();
                    try {
                    	$registrado = true;
						if($modelSeguimiento->id_estatus_preinscripcion == 2){

							$modelSeguimiento->fecha_registro = NULL;
							$modelAsociado = new Asociado;
							$modelAsociado->attributes = $model->attributes;
							$modelAsociado->fechaingreso = $modelSeguimiento->fecha_registro_inscripcion;
							$modelAsociado->actualizado = 0;
							$modelAsociado->id_estatus = 1;
							if($modelAsociado->save()){
								$modelAsociadoSeguimiento = new AsociadoEstatus();
								$modelAsociadoSeguimiento->id_estatus_asociado= 1;
								$modelAsociadoSeguimiento->idasociado= $modelAsociado->idasociado;
								$modelAsociadoSeguimiento->save();
								$newPwd = CrugeUtil::passwordGenerator();

								if(Yii::app()->user->um->loadUser($model->cedula) == null)
								{
									// asi se crea un usuario (una nueva instancia en memoria volatil)
									$modelUsuario = Yii::app()->user->um->createBlankUser();
									$modelUsuario->username = $model->cedula;
									$modelUsuario->email = ($model->correoelectronico!='')?$model->correoelectronico:'ejemplo@ejemplo.com';
									$modelUsuario->cedula = $model->cedula;
									$modelUsuario->nombres = $model->nombre;
									$modelUsuario->apellidos = $model->apellidos;
									$modelUsuario->username = $model->cedula;

									// la establece como "Activada"
									Yii::app()->user->um->activateAccount($modelUsuario);
									// ahora a ponerle una clave
									Yii::app()->user->um->changePassword($modelUsuario,$newPwd);


									// guarda usando el API, la cual hace pasar al usuario por el sistema de filtros.
									if(Yii::app()->user->um->save($modelUsuario)){
											 Yii::app()->user->rbac->assign("usuario_asociado", $modelUsuario->primaryKey);
									}
								}
								else{
									CrugeUserI::model()->updateAll(['state'=>1,'password'=>$newPwd],'username=:username',[':username'=>$model->cedula]);
								}
							}
							else{
								$registrado = false;
							}
						}
						if($registrado){
							PreinscripcionSeguimiento::model()->updateAll(['actual'=>false],'idpreinscripcion=:idpreinscripcion',[':idpreinscripcion'=>$id]);
							$modelSeguimiento->save();
							$transaction->commit();
	                        Yii::app()->user->setFlash('success', 'La solicitud fue guardado de forma exitosa');
	                        if($modelSeguimiento->id_estatus_preinscripcion == 2){
							CorreoElectronico::enviarCorreo(array('nombre'=>$model->nombre.' '.$model->apellidos,
	                                                                                'correo'=>$model->correoelectronico,
	                                                                                'asunto'=>'Aprobación de la solicitud',
	                                                                                'mensaje'=>$this->renderPartial('correoAprobacionPreinscripcion',array(
	                                                                                        'model'=>$model,
	                                                                                        'contrasenia'=>$newPwd,
	                                                                                        'empresa' =>  Empresa::model()->find(),
	                                                                                ), true)
	                                                                        ));
							}
							else{
								CorreoElectronico::enviarCorreo(array('nombre'=>$model->nombre.' '.$model->apellidos,
	                                                                                'correo'=>$model->correoelectronico,
	                                                                                'asunto'=>'Solicitud de afiliación',
	                                                                                'mensaje'=>$this->renderPartial('correoDenegacionPreinscripcion',array(
	                                                                                        'model'=>$model,
	                                                                                        'observacion'=>$modelSeguimiento->observacion,
	                                                                                        'empresa' =>  Empresa::model()->find(),
	                                                                                ), true)
	                                                                        ));
							}
						}
                        $this->redirect(array('view', 'id' => $model->id));
                    } catch (Exception $ex) {
                        $transaction->rollback();
                        Yii::app()->user->setFlash('error', 'Error al tratar de guardar la solicitud');
                        $this->redirect(array('view', 'id' => $model->id));
                    }


				}
			}
		}

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

	public function actionReporteExcel(){
  		$dataProvider = $_SESSION['datos_filtrados']->getData();
  		$model = new Preinscripcion;
  		//echo "<pre>";print_r($dataProvider);exit;
  		$phpExcelPath = Yii::getPathOfAlias('ext.Excel.PHPExcel.Classes');
        $phpExcelPath2 = Yii::getPathOfAlias('application.extensions.Excel.PHPExcel.Classes.PHPExcel');
        spl_autoload_unregister(array('YiiBase','autoload'));
        include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
        include $phpExcelPath.DIRECTORY_SEPARATOR.'PHPExcel'.DIRECTORY_SEPARATOR.'Reader'.DIRECTORY_SEPARATOR.'Excel2007.php';
        include($phpExcelPath2 . DIRECTORY_SEPARATOR . 'IOFactory.php');
        spl_autoload_register(array('YiiBase','autoload'));

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->getProperties()->setCreator("RORAIMASOFTWARE")
                                    ->setLastModifiedBy("RORAIMASOFTWARE")
                                    ->setTitle("RORAIMASOFTWARE")
                                    ->setSubject("RORAIMASOFTWARE")
                                    ->setDescription("RORAIMASOFTWARE")
                                    ->setKeywords("RORAIMASOFTWARE")
                                    ->setCategory("RORAIMASOFTWARE");

        $objPHPExcel->setActiveSheetIndex(0);

        $numtemo =0;
        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getFont()->setBold(true);                    //stylo
        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        foreach(range('A','Z') as $columnID) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
        }

        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:V1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1','LISTADO DE PREINSCRIPCIÓN ');
        // $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);         //stylo
        // $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        // $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB('1C336E');
        // $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
        // $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        $objPHPExcel->getActiveSheet()->getStyle('A2:V2')->getFont()->setBold(true);         //stylo
        $objPHPExcel->getActiveSheet()->getStyle('A2:V2')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A2:V2')->getFill()->getStartColor()->setARGB('1C336E');
        $objPHPExcel->getActiveSheet()->getStyle('A2:V2')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
        $objPHPExcel->getActiveSheet()->getStyle('A2:V2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);



        $objPHPExcel->setActiveSheetIndex(0);
        $dataArray[] =[
        		$model->getAttributeLabel('nacionalidad'),
        		$model->getAttributeLabel('cedula'),
        		$model->getAttributeLabel('nombre'),
        		$model->getAttributeLabel('apellidos'),
        		$model->getAttributeLabel('dirhabitacion'),
        		$model->getAttributeLabel('lugarnacimiento'),
        		$model->getAttributeLabel('fechanacimiento'),
        		$model->getAttributeLabel('correoelectronico'),
        		$model->getAttributeLabel('tlfhabitacion'),
        		$model->getAttributeLabel('lugartrabajo'),
        		$model->getAttributeLabel('estado'),
        		$model->getAttributeLabel('ciudad'),
        		$model->getAttributeLabel('cargo'),
        		$model->getAttributeLabel('tlfoficina'),
        		$model->getAttributeLabel('oficina'),
        		$model->getAttributeLabel('idunidad'),
        		$model->getAttributeLabel('idtipotrabajador'),
        		$model->getAttributeLabel('porcentaje'),
        		$model->getAttributeLabel('idcategoria'),
        		$model->getAttributeLabel('id_estatus'),
        		$model->getAttributeLabel('fecha_registro'),
        		$model->getAttributeLabel('fecha_estatus'),

            // [estado] => 13
            // [ciudad] => SDDSJANDJANSKJDN
            // [cargo] => SDBJABSJKDB
            // [tlfoficina] => (8888)-888-88-88
            // [oficina] => 39
            // [idunidad] => 41
            // [idtipotrabajador] => 2
            // [blnborrado] =>
            // [porcentaje] => 1
            // [idcategoria] => 1

        ];
        foreach ($dataProvider as $key => $value) {
        	$dato =[
        		$value['nacionalidad'],
        		$value['cedula'],
        		$value['nombre'],
        		$value['apellidos'],
        		$value['dirhabitacion'],
        		$value['lugarnacimiento'],
        		date('d-m-Y',strtotime($value['fechanacimiento'])),
        		$value['correoelectronico'],
        		$value['tlfhabitacion'],
        		$value['lugartrabajo'],
        		(($value['estado'])?TEstado::model()->findByPk($value['estado'])->DescripcionEstado:""),
        		$value['ciudad'],
        		$value['cargo'],
        		$value['tlfoficina'],
        		(($value['oficina'])?LugarTrabajo::model()->findByPk($value['oficina'])->descripcion:""),
        		(($value['idunidad'])?Unidad::model()->findByPk($value['idunidad'])->descripcion:""),
        		(($value['idtipotrabajador'])?TipoTrabajador::model()->findByPk($value['idtipotrabajador'])->descripcion:""),
        		(($value['porcentaje'])?Porcentaje::model()->findByPk($value['porcentaje'])->descripcion.'%':""),
        		(($value['idcategoria'])?CategoriaAsociado::model()->findByPk($value['idcategoria'])->descripcion:""),
        		$value['nombre_estatus'],
        		date('d-m-Y',strtotime($value['fecha_registro'])),
        		date('d-m-Y',strtotime($value['fecha_estatus'])),
        ];
        		$dataArray[]=  $dato;
        }
        // echo "<pre>";print_r($dataArray);exit;
        $objPHPExcel->getActiveSheet()->fromArray($dataArray, null, 'A2');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Listado de preinscripcion.xls"');
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter->setOffice2003Compatibility(true);
        $objWriter->save('php://output');

        exit;

	}

	/**
	 * 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)
	{
		$this->loadModel($id)->delete();

		// 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'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Preinscripcion');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Preinscripcion('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Preinscripcion']))
			$model->attributes=$_GET['Preinscripcion'];

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

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Preinscripcion the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Preinscripcion::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Preinscripcion $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='preinscripcion-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
