<?php

/**
 * This is the model class for table "reporte_asociados".
 *
 * The followings are the available columns in table 'reporte_asociados':
 *
 * @property int    $idasociado
 * @property int    $cedula
 * @property string $nombre
 * @property string $apellidos
 * @property string $dirhabitacion
 * @property string $lugarnacimiento
 * @property string $fechanacimiento
 * @property string $fecha_nacimiento
 * @property string $correoelectronico
 * @property string $tlfhabitacion
 * @property string $celular
 * @property int    $estadocivil
 * @property int    $cargafamiliar
 * @property int    $vivienda
 * @property int    $tipovivienda
 * @property int    $vehiculo
 * @property int    $asegurado
 * @property int    $aniocarro
 * @property string $lugartrabajo
 * @property string $empresa
 * @property int    $estado
 * @property string $descripcion_estado
 * @property string $ciudad
 * @property string $cargo
 * @property string $tlfoficina
 * @property string $fechaingreso
 * @property string $fecha_ingreso
 * @property int    $oficina
 * @property int    $idunidad
 * @property string $unidad
 * @property float  $sueldo
 * @property int    $tipoinscripcion
 * @property int    $porcentaje
 * @property string $porcentaje_descuento
 * @property bool   $blnborrado
 * @property string $fecha_registro
 * @property bool   $activo_aportes
 * @property string $sexo
 */
class ReporteAsociados extends CActiveRecord
{
    public $desde;
    public $hasta;
    public $columnas;

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'reporte_asociados';
    }

    public function primaryKey()
    {
        return 'idasociado';
    }

    /**
     * @return array validation rules for model attributes
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return [
            [
                'idasociado, cedula, estadocivil, cargafamiliar, vivienda, vehiculo, asegurado, estado, oficina, tipoinscripcion, tipovivienda, porcentaje, aniocarro, idunidad,actualizado',
                'numerical',
                'integerOnly' => true,
            ],
            ['sueldo', 'numerical'],
            ['nombre, apellidos, lugarnacimiento, descripcion_estado,cuenta_bancaria', 'length', 'max' => 100],
            ['correoelectronico', 'length', 'max' => 60],
            [
                'fecha_nacimiento, dirhabitacion, tlfhabitacion, celular, lugartrabajo, ciudad, cargo, tlfoficina, empresa,
                fechaingreso, fecha_ingreso, id_estatus,idtipotrabajador,blnborrado, porcentaje_descuento, fecha_registro,
                activo_aportes, unidad,actualizado,cuenta_bancaria,nombre_estatus,tipo_trabajador, sexo, id_sexo',
                'safe',
            ],
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            [
                'idasociado, cedula, nombre, apellidos, lugarnacimiento, fecha_nacimiento, estadocivil, cargafamiliar,
                vivienda,id_estatus,nombre_estatus,idtipotrabajador,tipo_trabajador, vehiculo, asegurado, dirhabitacion,
                correoelectronico, tlfhabitacion, celular, lugartrabajo, estado, descripcion_estado, ciudad, cargo, tlfoficina,
                oficina, empresa, fechaingreso, fecha_ingreso, sueldo, tipoinscripcion, tipovivienda, blnborrado, porcentaje,
                porcentaje_descuento, aniocarro, fecha_registro, activo_aportes, idunidad, unidad,desde, hasta,actualizado,
                cuenta_bancaria, sexo, id_sexo',
                'safe',
                'on' => 'search',
            ],
        ];
    }

    /**
     * @return array relational rules
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return [
            'idOficina' => [self::BELONGS_TO, 'LugarTrabajo', 'oficina'],
            'idUnidad' => [self::BELONGS_TO, 'Unidad', 'idunidad'],
            'estadoCivil' => [self::BELONGS_TO, 'EstadoCivil', 'estadocivil'],
            'tipoVivienda' => [self::BELONGS_TO, 'TipoVivienda', 'tipovivienda'],
            'viviendas' => [self::BELONGS_TO, 'Sino', 'vivienda'],
            'siNo' => [self::BELONGS_TO, 'Sino', 'vehiculo'],
            'actualizados' => [self::BELONGS_TO, 'Sino', 'actualizado'],
            'idEstado' => [self::BELONGS_TO, 'TEstado', 'estado'],
            'idPorcentaje' => [self::BELONGS_TO, 'Porcentaje', 'porcentaje'],
            'tipoInscripcion' => [self::BELONGS_TO, 'TipoInscripcion', 'tipoinscripcion'],
            'idAsegurado' => [self::BELONGS_TO, 'Sino', 'asegurado'],
            'idtipotrabajador' => [self::BELONGS_TO, 'TipoTrabajador', 'idtipotrabajador'],
            'idestatus' => [self::BELONGS_TO, 'EstatusAsociaso', 'id'],
            'idAsegurado' => [self::BELONGS_TO, 'Sino', 'asegurado'],
        ];
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return [
            'idasociado' => 'Idasociado',
            'cedula' => 'Cédula',
            'nombre' => 'Nombres',
            'apellidos' => 'Apellidos',
            'id_sexo' => 'Sexo',
            'sexo' => 'Sexo',
            'lugarnacimiento' => 'Lugar de Nacimiento',
            'fecha_nacimiento' => 'Fecha de Nacimiento',
            'estadocivil' => 'Estado Civil',
            'cargafamiliar' => 'Carga Familiar',
            'vivienda' => '¿Posee Vivienda?',
            'vehiculo' => '¿Posee Vehículo?',
            'asegurado' => '¿Está Asegurado?',
            'dirhabitacion' => 'Direccion de Habitacion',
            'correoelectronico' => 'Correo Electrónico',
            'tlfhabitacion' => 'Teléfono de Habitacion',
            'celular' => 'Celular',
            'lugartrabajo' => 'Dependencia Administrativa',
            'estado' => 'Estado',
            'descripcion_estado' => 'Estado',
            'ciudad' => 'Ciudad',
            'cargo' => 'Cargo',
            'tipo_trabajador' => 'Tipo trabajador',
            'idtipotrabajador' => 'Tipo trabajador',
            'tlfoficina' => 'Teléfono de Oficina',
            'oficina' => 'Oficina',
            'descripcion_oficina' => 'Oficina',
            'empresa' => 'Empresa',
            'fechaingreso' => 'Fecha de Inscripción',
            'fecha_ingreso' => 'Fecha de Ingreso',
            'sueldo' => 'Sueldo',
            'tipoinscripcion' => 'Tipo de Inscripción',
            'descripcion_inscripcion' => 'Tipo de Inscripción',
            'tipovivienda' => 'Tenencia de Vivienda',
            'descripcion_vivienda' => 'Tenencia de Vivienda',
            'blnborrado' => 'Blnborrado',
            'porcentaje' => 'Porcentaje Descuento',
            'porcentaje_descuento' => 'Porcentaje Descuento',
            'aniocarro' => 'Año de Vehículo',
            'fecha_registro' => 'Fecha de Registro',
            'activo_aportes' => 'Activo Aportes',
            'idunidad' => 'Unidad',
            'unidad' => 'Unidad',
            'cuenta_bancaria' => 'Cuenta Bancaria',
            'actualizado' => '¿Usuario Actualizado?',
            'nombre_estatus' => 'Estatus asociado',
            'id_estatus' => 'Estatus asociado',
        ];
    }

    public function getColumns()
    {
        return [
            'nacionalidad' => [
                'label' => 'Nacionalidad',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'cedula' => [
                'label' => 'Cédula',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'nombre' => [
                'label' => 'Nombre',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'apellidos' => [
                'label' => 'Apellidos',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'sexo' => [
                'label' => 'Sexo',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'lugarnacimiento' => [
                'label' => 'Lugar nacimiento',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'fecha_nacimiento' => [
                'label' => 'Fecha nacimiento',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'estado_civil' => [
                'label' => 'Estado civil',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'cargafamiliar' => [
                'label' => 'Carga familiar',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'correoelectronico' => [
                'label' => 'Correo electronico',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'dirhabitacion' => [
                'label' => 'Dirección habitación',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'tlfhabitacion' => [
                'label' => 'Teléfono habitación',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'celular' => [
                'label' => 'Celular',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'fechaingreso' => [
                'label' => 'Fecha ingreso',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'vivienda' => [
                'label' => 'Vivienda',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'descripcion_vivienda' => [
                'label' => 'Descripción vivienda',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'vehiculo' => [
                'label' => 'Vehículo',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'marca_vehiculo' => [
                'label' => 'Marca vehículo',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'modelo_vehiculo' => [
                'label' => 'Modelo vehículo',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'descripcion_oficina' => [
                'label' => 'Descripción oficina',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'unidad' => [
                'label' => 'Unidad',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'sueldo' => [
                'label' => 'Sueldo',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT',
                'formato' => '#,##0.00',
            ],
            'lugartrabajo' => [
                'label' => 'Lugar trabajo',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'descripcion_estado' => [
                'label' => 'Descripción estado',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'ciudad' => [
                'label' => 'Ciudad',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'cargo' => [
                'label' => 'Cargo',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'tipo_trabajador' => [
                'label' => 'Tipo trabajador',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'tlfoficina' => [
                'label' => 'Teléfono oficina',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'descripcion_inscripcion' => [
                'label' => 'Descripción inscripción',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'porcentaje_descuento' => [
                'label' => 'Porcentaje descuento',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'asegurado' => [
                'label' => 'Asegurado',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'aniocarro' => [
                'label' => 'Año carro',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'cuenta_bancaria' => [
                'label' => 'Cuenta bancaria',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
                'formato' => '####################',
            ],
            'nombre_estatus' => [
                'label' => 'Nombre estatus',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
            'actualizado' => [
                'label' => 'Actualizado',
                'color' => 'C00000',
                'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT',
            ],
        ];
    }

    public function hasColumn($column)
    {
        return array_key_exists($column, $this->getColumnsKeys());
    }

    private function getColumnsKeys()
    {
        return (new Warp($this->columnas))->flatMap(function ($columna) {
            return $columna;
        });
    }

    private function getColumnsSelected()
    {
        return array_keys($this->getColumnsKeys());
    }

    public function configuracionCampo($campo)
    {
        $campos = $this->getColumns();

        return array_key_exists($campo, $campos) ? $campos[$campo] : false;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     *                             based on the search/filter conditions
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria();

        $criteria->compare('idasociado', $this->idasociado);
        $criteria->compare('cedula', $this->cedula);
        $criteria->compare('nombre', $this->nombre, true);
        $criteria->compare('apellidos', $this->apellidos, true);
        $criteria->compare('lugarnacimiento', $this->lugarnacimiento, true);
        $criteria->compare('fecha_nacimiento', $this->fecha_nacimiento, true);
        $criteria->compare('estadocivil', $this->estadocivil);
        $criteria->compare('cargafamiliar', $this->cargafamiliar);
        $criteria->compare('vivienda', $this->vivienda);
        $criteria->compare('vehiculo', $this->vehiculo);
        $criteria->compare('asegurado', $this->asegurado);
        $criteria->compare('dirhabitacion', $this->dirhabitacion, true);
        $criteria->compare('correoelectronico', $this->correoelectronico, true);
        $criteria->compare('tlfhabitacion', $this->tlfhabitacion, true);
        $criteria->compare('celular', $this->celular, true);
        $criteria->compare('lugartrabajo', $this->lugartrabajo, true);
        $criteria->compare('estado', $this->estado);
        $criteria->compare('descripcion_estado', $this->descripcion_estado, true);
        $criteria->compare('ciudad', $this->ciudad, true);
        $criteria->compare('cargo', $this->cargo, true);
        $criteria->compare('tlfoficina', $this->tlfoficina, true);
        $criteria->compare('oficina', $this->oficina);
        $criteria->compare('empresa', $this->empresa, true);
        $criteria->compare('tipo_trabajador', $this->tipo_trabajador, true);
        $criteria->compare('fechaingreso', $this->fechaingreso, true);
        $criteria->compare('fecha_ingreso', $this->fecha_ingreso, true);
        $criteria->compare('sueldo', $this->sueldo);
        $criteria->compare('tipoinscripcion', $this->tipoinscripcion);
        $criteria->compare('tipovivienda', $this->tipovivienda);
        $criteria->compare('blnborrado', $this->blnborrado);
        $criteria->compare('porcentaje', $this->porcentaje);
        $criteria->compare('porcentaje_descuento', $this->porcentaje_descuento, true);
        $criteria->compare('aniocarro', $this->aniocarro);
        $criteria->compare('fecha_registro', $this->fecha_registro, true);
        $criteria->compare('activo_aportes', $this->activo_aportes);
        $criteria->compare('idunidad', $this->idunidad);
        $criteria->compare('unidad', $this->unidad, true);
        $criteria->compare('id_estatus', $this->id_estatus);
        $criteria->compare('idtipotrabajador', $this->idtipotrabajador);
        $criteria->compare('nombre_estatus', $this->nombre_estatus, true);
        $criteria->compare('actualizado', $this->actualizado);
        $criteria->compare('cuenta_bancaria', $this->cuenta_bancaria, true);

        return new CActiveDataProvider($this, [
            'criteria' => $criteria,
        ]);
    }

    public function getAsociados()
    {
        $criteria = new CDbCriteria();
        $criteria->select = $this->getColumnsSelected();
        $criteria->order = 'cedula,fechaingreso';

        $criteria->compare('idasociado', $this->idasociado);
        $criteria->compare('cedula', $this->cedula);
        $criteria->compare('LOWER(nombre)', strtolower($this->nombre), true);
        $criteria->compare('LOWER(apellidos)', strtolower($this->apellidos), true);
        $criteria->compare('lugarnacimiento', $this->lugarnacimiento, true);
        $criteria->compare('fecha_nacimiento', $this->fecha_nacimiento, true);
        $criteria->compare('cargafamiliar', $this->cargafamiliar);
        $criteria->compare('vivienda', $this->vivienda);
        $criteria->compare('vehiculo', $this->vehiculo);
        $criteria->compare('asegurado', $this->asegurado);
        $criteria->compare('dirhabitacion', $this->dirhabitacion, true);
        $criteria->compare('correoelectronico', $this->correoelectronico, true);
        $criteria->compare('tlfhabitacion', $this->tlfhabitacion, true);
        $criteria->compare('celular', $this->celular, true);
        $criteria->compare('LOWER(lugartrabajo)', strtolower($this->lugartrabajo), true);
        $criteria->compare('estado', $this->estado);
        $criteria->compare('descripcion_estado', $this->descripcion_estado, true);
        $criteria->compare('ciudad', $this->ciudad, true);
        $criteria->compare('cargo', $this->cargo, true);
        $criteria->compare('tlfoficina', $this->tlfoficina, true);
        $criteria->compare('oficina', $this->oficina);
        $criteria->compare('empresa', $this->empresa, true);
        $criteria->compare('tipo_trabajador', $this->tipo_trabajador, true);
        $criteria->compare('fecha_ingreso', $this->fecha_ingreso, true);
        $criteria->compare('sueldo', $this->sueldo);
        $criteria->compare('tipoinscripcion', $this->tipoinscripcion);
        $criteria->compare('tipovivienda', $this->tipovivienda);
        $criteria->compare('blnborrado', $this->blnborrado);
        $criteria->compare('porcentaje', $this->porcentaje);
        $criteria->compare('porcentaje_descuento', $this->porcentaje_descuento, true);
        $criteria->compare('aniocarro', $this->aniocarro);
        $criteria->compare('activo_aportes', $this->activo_aportes);
        $criteria->compare('idunidad', $this->idunidad);
        $criteria->compare('id_estatus', $this->id_estatus);
        $criteria->compare('idtipotrabajador', $this->idtipotrabajador);
        $criteria->compare('unidad', $this->unidad, true);
        $criteria->compare('actualizado', $this->actualizado);
        $criteria->compare('cuenta_bancaria', $this->cuenta_bancaria, true);
        $criteria->compare('nombre_estatus', $this->nombre_estatus, true);
        $criteria->compare('id_sexo', $this->id_sexo);

        $from = $to = '';
        if (isset($this->desde)) {
            $from = $this->desde;
        }
        if (isset($this->hasta)) {
            $to = $this->hasta;
        }

        if ($from != '' || $to != '') {
            if ($from != '' && $to != '') {
                $from = date('d-m-Y', strtotime($from));
                $to = date('d-m-Y', strtotime($to));
                $criteria->compare('fechaingreso', ">= ${from}", false);
                $criteria->compare('fechaingreso', "<= ${to}", false);
            } else {
                if ($from != '') {
                    $creation_time = $from;
                }
                if ($to != '') {
                    $creation_time = $to;
                }
                $creation_time = date('d-m-Y', strtotime($creation_time));
                $criteria->compare('fechaingreso', "${creation_time}", false);
            }
        }

        if ($from != '' || $to != '') {
            if ($from != '' && $to != '') {
                $from = date('d-m-Y', strtotime($from));
                $to = date('d-m-Y', strtotime($to));
                $criteria->compare('fechaingreso', ">= ${from}", false);
                $criteria->compare('fechaingreso', "<= ${to}", false);
            } else {
                if ($from != '') {
                    $creation_time = $from;
                }
                if ($to != '') {
                    $creation_time = $to;
                }
                $creation_time = date('d-m-Y', strtotime($creation_time));
                $criteria->compare('fechaingreso', "${creation_time}", false);
            }
        }
        $criteria->compare('estadocivil', $this->estadocivil);

        return self::model()->findAll($criteria);
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     *
     * @param string $className active record class name
     *
     * @return Asociados the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }
}
