<?php

class ReporteAsociadosController 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 [
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete',
            ['CrugeAccessControlFilter'],
        ];
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     *
     * @return array access control rules
     */
    public function accessRules()
    {
        return [
            [
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => ['index', 'view'],
                'users' => ['@'],
            ],
            [
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => ['create', 'update', 'cargarUnidad'],
                'users' => ['@'],
            ],
            [
                'allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => ['admin', 'delete'],
                'users' => ['admin'],
            ],
            [
                'deny', // deny all users
                'users' => ['*'],
            ],
        ];
    }

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

    public function actionCargarUnidad()
    {
        $data = Unidad::model()->findAllBySql(
            "select * from unidad where idlugartrabajo
        =:keyword and blnborrado='f' order by descripcion asc",
            [':keyword' => $_POST['ReporteAsociados']['oficina']]
        );

        $data = CHtml::listData($data, 'idunidad', 'descripcion');
        echo "<option value=''>Seleccione la Unidad</option>";
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', ['value' => $value], CHtml::encode($name), true);
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new ReporteAsociados();
        $model->unsetAttributes(); // clear any default values
        if (isset($_POST['ReporteAsociados'])) {
            $model->desde = $_POST['ReporteAsociados']['desde'];
            $model->hasta = $_POST['ReporteAsociados']['hasta'];

            if (isset($_POST['yt1'])) {
                $model->attributes = $_POST['ReporteAsociados'];
                if ($model->validate()) {
                    $model->setAttribute('columnas', $_POST['columnas']);

                    $reporte = $model->getAsociados();

                    $total = count($reporte);
                    if ($total > 0) {
                        $this->render('reporteAsociados', ['model' => $model]);
                        echo "<script type=\"text/javascript\">
    					$('#carga').show();
    					$('#formulario').hide();
    					</script>";
                        $this->mensajeCarga(($mensaje = '<b>Generando Resumen:</b> .....'));

                        $filas = [
                            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
                            'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ',
                            'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
                        ];

                        spl_autoload_unregister(['YiiBase', 'autoload']);
                        include Yii::getPathOfAlias('ext.Excel.PHPExcel.Classes').
                            DIRECTORY_SEPARATOR.
                            'PHPExcel.php';
                        include Yii::getPathOfAlias('application.extensions.Excel.PHPExcel.Classes.PHPExcel').
                            DIRECTORY_SEPARATOR.
                            'IOFactory.php';
                        spl_autoload_register(['YiiBase', 'autoload']);

                        $objPHPExcel = new PHPExcel();
                        $objPHPExcel
                            ->getProperties()
                            ->setCreator('RORAIMASOFTWARE')
                            ->setLastModifiedBy('RORAIMASOFTWARE')
                            ->setTitle('RORAIMASOFTWARE')
                            ->setSubject('RORAIMASOFTWARE')
                            ->setDescription('RORAIMASOFTWARE')
                            ->setKeywords('RORAIMASOFTWARE')
                            ->setCategory('RORAIMASOFTWARE');

                        $objPHPExcel->setActiveSheetIndex(0);
                        $this->mensajeCarga(($mensaje = '<b>Creando Cintillo:</b> .....'));
                        $numtemo = 0;

                        $objPHPExcel->getActiveSheet()->freezePaneByColumnAndRow(0, 2);
                        foreach ($reporte[0] as $name => $nombrefila) {
                            $cintillo = $model->configuracionCampo($name);

                            if ($cintillo != 0 && $model->hasColumn($name)) {
                                $objPHPExcel
                                    ->getActiveSheet()
                                    ->setCellValue($filas[$numtemo].'1', $model->getAttributeLabel($name));
                                $objPHPExcel
                                    ->getActiveSheet()
                                    ->getColumnDimension($filas[$numtemo])
                                    ->setAutoSize(true);

                                $objPHPExcel
                                    ->getActiveSheet()
                                    ->getStyle($filas[$numtemo].'1')
                                    ->getFont()
                                    ->setBold(true); //stylo
                                $objPHPExcel
                                    ->getActiveSheet()
                                    ->getStyle($filas[$numtemo].'1')
                                    ->getFill()
                                    ->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                                $objPHPExcel
                                    ->getActiveSheet()
                                    ->getStyle($filas[$numtemo].'1')
                                    ->getFill()
                                    ->getStartColor()
                                    ->setARGB($cintillo['color']);
                                $objPHPExcel
                                    ->getActiveSheet()
                                    ->getStyle($filas[$numtemo].'1')
                                    ->getFont()
                                    ->getColor()
                                    ->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
                                $objPHPExcel
                                    ->getActiveSheet()
                                    ->getStyle($filas[$numtemo].'1')
                                    ->getAlignment()
                                    ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

                                $numtemo = $numtemo + 1;
                            }
                        }
                        //Columna de Suma
                        $numfila = 2;

                        $this->mensajeCarga(($mensaje = '<b>Registrando datos en la celda:</b> .....'));
                        foreach ($reporte as $i => $data) {
                            $this->barraProgreso(($i * 100) / $total);
                            $numtemo = 0;
                            foreach ($data as $name => $datofila) {
                                if ($name == 'vivienda') {
                                    $datofila = $data->viviendas ? $data->viviendas->descripcion : '';
                                }
                                if ($name == 'vehiculo') {
                                    $datofila = $data->vehiculo ? $data->siNo->descripcion : '';
                                }
                                if ($name == 'asegurado') {
                                    $datofila = $data->asegurado ? $data->idAsegurado->descripcion : '';
                                }
                                if ($name == 'actualizado') {
                                    $datofila = $data->actualizado ? $data->actualizados->descripcion : '';
                                }

                                if ($name == 'fechaingreso') {
                                    $datofila = $data->fechaingreso
                                        ? date('d-m-Y', strtotime($data->fechaingreso))
                                        : '';
                                }
                                $camposConfigurado = $model->configuracionCampo($name);

                                if ($camposConfigurado != 0) {
                                    if (array_key_exists('alineacion', $camposConfigurado)) {
                                        $objPHPExcel
                                            ->getActiveSheet()
                                            ->getStyle($filas[$numtemo].$numfila)
                                            ->getAlignment()
                                            ->setHorizontal($camposConfigurado['alineacion']);
                                    }
                                    if (array_key_exists('formato', $camposConfigurado)) {
                                        $objPHPExcel
                                            ->getActiveSheet()
                                            ->getStyle($filas[$numtemo].$numfila)
                                            ->getNumberFormat()
                                            ->setFormatCode($camposConfigurado['formato']);
                                    }

                                    $objPHPExcel
                                        ->getActiveSheet()
                                        ->setCellValue($filas[$numtemo].$numfila, $datofila);
                                    $numtemo = $numtemo + 1;
                                }
                            }
                            $progreso = 0;
                            if ($i != 0) {
                                $progreso = ($i * 100) / ($total - 1);
                            }
                            $numfila = $numfila + 1;
                            $this->barraProgreso($progreso);
                            $this->mensajeCarga(
                                ($mensaje = '<b>'.floor($progreso).'%</b>'),
                                ($contenedorMensajeId = 'barraProgreso')
                            );
                        }
                        $this->barraProgreso(100);
                        $this->mensajeCarga(($mensaje = '<b>Completado</b>'), ($contenedorMensajeId = 'barraProgreso'));
                        $this->mensajeCarga(($mensaje = '<b>Datos guardados</b>'));
                        echo "<script type=\"text/javascript\">
    					$('#resultado').show();
    					$('#barraEstado').show();
    					</script>";
                        $this->barraProgreso(0, ($barraProgresoId = 'barraEstado'));
                        // Rename sheet
                        $objPHPExcel->getActiveSheet()->setTitle('Reporte General de Asociados');
                        $objPHPExcel->setActiveSheetIndex(0);

                        $this->barraProgreso(33, ($barraProgresoId = 'barraEstado'));

                        $this->mensajeCarga(
                            ($mensaje = '<b>Generando Resumen:</b>  Generado.'),
                            ($contenedorMensajeId = 'mensajeResultado')
                        );
                        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                        $objWriter->save('doc/ReporteGeneralAsociados.xlsx');
                        $this->mensajeCarga(
                            ($mensaje = '<b>Guardando Archivo</b> .....'),
                            ($contenedorMensajeId = 'mensajeResultado')
                        );
                        $this->barraProgreso(66, ($barraProgresoId = 'barraEstado'));

                        echo "<script type=\"text/javascript\">
    					$('#archivos').append('<b></b> Descargar Excel <b>".
                            CHtml::link('aquí', 'doc/ReporteGeneralAsociados.xlsx', ['target' => '_blank']).
                            "</b><br>');
    					$('#boton').show();
    					</script>";
                        $this->mensajeCarga(
                            ($mensaje = '<b>Archivo listo</b> .....'),
                            ($contenedorMensajeId = 'mensajeResultado')
                        );

                        $this->barraProgreso(100, ($barraProgresoId = 'barraEstado'));
                        flush();
                        ob_flush();
                        exit();
                    }

                    Yii::app()->user->setFlash('error', '<b>No hay datos para generar el reporte</b>');
                }
            } elseif (isset($_POST['yt0'])) {
                if (file_exists('doc/ReporteGeneralAsociados.xlsx')) {
                    unlink('doc/ReporteGeneralAsociados.xlsx');
                }
            }
        }
        $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param int $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);

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

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

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

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     *
     * @param int $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $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'] : ['admin']);
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

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

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

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

    protected function mensajeCarga($mensaje, $contenedorMensajeId = '')
    {
        if ($contenedorMensajeId == '') {
            $contenedorMensajeId = 'mensajes';
        }

        echo "	<script type=\"text/javascript\">
	$('#".
            $contenedorMensajeId.
            "').html('".
            $mensaje.
            "');
	</script>";
        flush();
        ob_flush();
        flush();
        ob_flush();
    }

    protected function barraProgreso($count, $barraProgresoId = '')
    {
        if ($barraProgresoId == '') {
            $barraProgresoId = 'barraProgreso';
        }

        echo "<script type=\"text/javascript\">
	$('#".
            $barraProgresoId.
            "').css('width','".
            $count.
            "%' );
	</script>";
        flush();
        ob_flush();
    }

    /**
     * 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 int the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Asociados::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }

        return $model;
    }

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