<?php

/**
 * This is the model class for table "reporte_creditos".
 *
 * The followings are the available columns in table 'reporte_creditos':
 * @property integer $idasociado
 *
 * @property integer $idcredito
 * @property integer $cedula
 * @property string $nombre
 * @property string $apellidos
 * @property string $fecha_registro
 * @property integer $idunidad
 * @property integer $id_tipo_credito
 * @property double $prestamo
 * @property double $garantia
 * @property integer $interes
 * @property double $cuota_pagar
 * @property string $taza_taza_intereses
 * @property string $capital
 * @property string $mto_cancelado
 * @property double $deuda_actual
 * @property string $cuotas_pagadas
 * @property string $cuotas_pendientes
 */
class ReporteCreditos extends CActiveRecord {

    public $fecha_inicio, $fecha_fin, $descripcionEstatus;
    public $mes;
    public $consulta;
    public $fecha_estatus;
    public $id_titulo_tipo_credito;
    public $saldo_deudor;
    public $nombre_tipo_credito;

    //variables para el calculo de disponibilidad del socio
    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'reporte_creditos';
    }

    /**
     * @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 array(
            array('mes', 'required','on'=>'esc_periodo'),
            array('fecha_fin,fecha_inicio', 'required','on'=>'esc_fecha'),
            array('idasociado,  idcredito, cedula, idunidad, taza_interes', 'numerical', 'integerOnly' => true),
            array('prestamo, cuota_pagar, deuda_actual, cuotas_pagadas, cuotas_pendientes', 'numerical'),
            array('nombre, apellidos', 'length', 'max' => 100),
            array('mes,consulta,deuda_total ,capital_especial,nombre_titulo,idunidad,id_titulo,id_titulo_tipo_credito, id_tipo_credito,idtipotrabajador,id_estatus, fecha_registro, intereses, capital, mto_cancelado, cuotas_pagadas, cuotas_pendientes, fecha_inicio, fecha_fin', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('idasociado,intereses_total, idcredito,nombre_titulo,id_titulo,id_estatus,id_titulo_tipo_credito, cedula, nombre, apellidos,idtipotrabajador,idestatus, fecha_registro, idunidad, id_tipo_credito, prestamo, taza_interes, cuota_pagar, intereses, capital, mto_cancelado, deuda_actual, cuotas_pagadas, cuotas_pendientes', 'safe', 'on' => 'search'),
        );
    }

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

    /**
     * @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 array(
            'unidad' => array(self::BELONGS_TO, 'Unidad', 'idunidad'),
            'tipoCredito' => array(self::BELONGS_TO, 'TipoCredito', 'id_tipo_credito'),
            'tipoTitulo' => array(self::BELONGS_TO, 'TituloTipoCredito', 'id_titulo'),
            'idCredito' => array(self::BELONGS_TO, 'Credito', 'idcredito'),
            'tseg' => array(self::HAS_MANY, 'CreditoSeguimiento', 'id_credito'),

        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'idasociado' => 'Idasociado',
           // 'idtrabajador' => 'Idtrabajador',
            'idcredito' => 'N° de préstamo',
            'cedula' => 'Cédula',
            'nombre' => 'Nombre',
            'apellidos' => 'Apellidos',
            'fecha_registro' => 'Fecha de solicitud',
            'idunidad' => 'Unidad',
            'idtipotrabajador' => 'Tipo trabajador',
            'tipo_trabajador' => 'Tipo trabajador',
            'lugartrabajo' => 'Dependencia administrativa',
            'id_estatus' => 'Estatus asociado',
            'nombre_estatus' => 'Estatus asociado',
            'id_titulo' => 'Categoría',
            'nombre_titulo' => 'Categoría',
            'id_tipo_credito' => 'Plazo del préstamo',
            'prestamo' => 'Capital prestado',
            'taza_interes' => 'Tasa',
            'cuota_pagar' => 'Cuota a pagar',
            'intereses_total' => 'Interés total',
            'deuda_total' => 'Total préstamo',
            'intereses' => 'Interés ordinario',
            'intereses_esp' => 'Interés especial',
            'capital' => 'Capital ordinario',
            'capital_especial' => 'Capital especial',
            'mto_cancelado' => 'Monto cancelado',
            'deuda_actual' => 'Deuda Actual',
            'cuotas_pagadas' => 'Cuotas pagadas',
            'cuotas_pendientes' => 'Cuotas pendientes',
            'fecha_inicio' => 'Desde',
            'fecha_fin' => 'Hasta',
            'garantia' => 'Gastos Administrativo',
            'intereses_pagados' => 'Intereses pagado',
            'capital_pagados' => 'Capital pagado',
            'deudas_interes' => 'Deudas por interes',
            'nombre_estatus_credito' => 'Estatus del crédito',
        );
    }

    /**
     * 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->condition='blnborrado=false';
        $criteria->compare('idasociado', $this->idasociado);
        //$criteria->compare('idtrabajador', $this->idtrabajador);
        $criteria->compare('idcredito', $this->idcredito);
        $criteria->compare('cedula', $this->cedula);
        $criteria->compare('nombre', $this->nombre, true);
        $criteria->compare('apellidos', $this->apellidos, true);
        // $criteria->compare('fecha_registro',$this->fecha_registro,true);
        $criteria->compare('idunidad', $this->idunidad);
        $criteria->compare('idtipotrabajador', $this->idtipotrabajador);
        $criteria->compare('id_estatus', $this->id_estatus);
        $criteria->compare('id_titulo', $this->id_titulo);
        $criteria->compare('id_titulo_tipo_credito', $this->id_titulo_tipo_credito);
        $criteria->compare('id_tipo_credito', $this->id_tipo_credito);
        $criteria->compare('prestamo', $this->prestamo);
        $criteria->compare('taza_interes', $this->taza_interes);
        $criteria->compare('cuota_pagar', $this->cuota_pagar);
        $criteria->compare('intereses', $this->intereses, true);
        $criteria->compare('capital', $this->capital, true);
        $criteria->compare('mto_cancelado', $this->mto_cancelado, true);
        $criteria->compare('deuda_actual', $this->deuda_actual);
        $criteria->compare('cuotas_pagadas', $this->cuotas_pagadas, true);
        $criteria->compare('cuotas_pendientes', $this->cuotas_pendientes, true);


        $from = $to = '';
        if (isset($this->fecha_inicio)) {
            $from = $this->fecha_inicio;
        }
        if (isset($this->fecha_fin)) {
            $to = $this->fecha_fin;
        }
        if ($from != '' || $to != '') {
            if ($from != '' && $to != '') {
                $from = date("d-m-Y", strtotime($from));
                $to = date("d-m-Y", strtotime($to));
                $criteria->compare('fecha_registro', ">= $from", false);
                $criteria->compare('fecha_registro', "<= $to", false);
            } else {
                if ($from != '')
                    $creation_time = $from;
                if ($to != '')
                    $creation_time = $to;
                $creation_time = date("d-m-Y", strtotime($creation_time));
                $criteria->compare('fecha_registro', "$creation_time", false);
            }
        }
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria
        ));
    }

    public function searchCreditosXAsociado($id)
    {
        $criteria = new CDbCriteria();

        if (isset($_GET['cedula'])) {
            if (is_numeric($_GET['cedula'])) {
                $id = 0;
                $model = Asociado::model()->find('cedula=:cedula AND blnborrado= FALSE AND id_estatus in(1,4) ORDER BY idasociado desc', [':cedula' => $_GET['cedula']]);
                if ($model) {
                    $id = $model->idasociado;
                }
            } else {
                $id = 0;
            }
        }

        $criteria->select = 't.idcredito,
                             t.nombre_titulo,
                             t.prestamo,
                             t.fecha_registro,
                             t.cuotas_pagadas,
                             t.id_estatus_credito,
                             t.nombre_estatus_credito,
                             tc.descripcion as nombre_tipo_credito,
                             (
                                select coalesce(sum(monto),0)
                                from (
                                    select case coalesce(cdc.id::boolean, false)
                                            when false then coalesce(cta.monto_capital,0)
                                            when true then coalesce(cdc.capital_cobro,0)
                                        end as monto
                                    from prestamos.credito_tabla_amortizacion cta
                                    inner join prestamos.credito c on c.id=cta.idcredito
                                        and c.idasociado=t.idasociado
                                        and c.id=t.idcredito
                                        and c.blnborrado is false
                                    left join prestamos.datos_txt_tabla_amortizacion dtta on dtta.id_tabla_amortizacion=cta.id
                                        and dtta.actual is true
                                    left join prestamos.cobro_diferencial_cuota cdc on cdc.id_proceso=dtta.id
                                        and cdc.blnborrado is false
                                    where cta.blnborrado IS FALSE
                                        and (cta.id_estatus_cuota is null or cta.id_estatus_cuota in (1, 3, 6, 7, 8, 9, 12))
                                ) d
                             ) as saldo_deudor';
        $criteria->join = 'left join prestamos.tipo_credito tc on tc.id=t.id_tipo_credito';
        $criteria->addColumnCondition([
            'tc.blnborrado' => false,
            't.idasociado' => $id,
        ]);
        $criteria->compare('saldo_deudor', $this->saldo_deudor);
        $criteria->compare('nombre_tipo_credito', $this->nombre_tipo_credito);
        $criteria->compare('idcredito', $this->idcredito);
        $criteria->compare('cedula', $this->cedula);
        $criteria->compare('nombre', $this->nombre, true);
        $criteria->compare('apellidos', $this->apellidos, true);
        $criteria->compare('fecha_registro', $this->fecha_registro, true);
        $criteria->compare('idunidad', $this->idunidad);
        $criteria->compare('idtipotrabajador', $this->idtipotrabajador);
        $criteria->compare('id_estatus', $this->id_estatus);
        $criteria->compare('id_titulo', $this->id_titulo);
        $criteria->compare('id_titulo_tipo_credito', $this->id_titulo_tipo_credito);
        $criteria->compare('id_tipo_credito', $this->id_tipo_credito);
        $criteria->compare('prestamo', $this->prestamo);
        $criteria->compare('taza_interes', $this->taza_interes);
        $criteria->compare('cuota_pagar', $this->cuota_pagar);
        $criteria->compare('intereses', $this->intereses, true);
        $criteria->compare('capital', $this->capital, true);
        $criteria->compare('mto_cancelado', $this->mto_cancelado, true);
        $criteria->compare('deuda_actual', $this->deuda_actual);
        $criteria->compare('cuotas_pagadas', $this->cuotas_pagadas, true);
        $criteria->compare('cuotas_pendientes', $this->cuotas_pendientes, true);

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

        if (isset($this->fecha_fin)) {
            $to = $this->fecha_fin;
        }

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

        $criteria->order = 'fecha_registro DESC';

        return new CActiveDataProvider($this, [
            'criteria' => $criteria,
        ]);
    }
    public function searchAbonoPrestamo($id = null) {
        $criteria = new CDbCriteria;

        if (isset($_GET['cedula'])) {
            $id = $this->getAsociado($_GET['cedula']);
        }

        $criteria->select = '*,
            (
                select coalesce(sum(monto),0)
                from (
                    select case coalesce(cdc.id::boolean, false)
                            when false then coalesce(cta.monto_capital,0)
                            when true then coalesce(cdc.capital_cobro,0)
                        end as monto
                    from prestamos.credito_tabla_amortizacion cta
                    inner join prestamos.credito c on c.id=cta.idcredito
                        and c.idasociado=t.idasociado
                        and c.id=t.idcredito
                        and c.blnborrado is false
                    left join prestamos.datos_txt_tabla_amortizacion dtta on dtta.id_tabla_amortizacion=cta.id
                        and dtta.actual is true
                    left join prestamos.cobro_diferencial_cuota cdc on cdc.id_proceso=dtta.id
                        and cdc.blnborrado is false
                    where cta.blnborrado IS FALSE
                        and (cta.id_estatus_cuota is null or cta.id_estatus_cuota in (1, 3, 6, 7, 8, 9, 12))
                ) d
            ) as saldo_deudor
        ';

        $criteria->condition = 'idasociado=' . (INT)$id.' AND id_estatus_credito=4';
        // $criteria->compare('idtrabajador',$this->idtrabajador);
        $criteria->compare('idcredito', $this->idcredito);
        $criteria->compare('cedula', $this->cedula);
        $criteria->compare('nombre', $this->nombre, true);
        $criteria->compare('apellidos', $this->apellidos, true);
        $criteria->compare('fecha_registro',$this->fecha_registro,true);
        $criteria->compare('idunidad', $this->idunidad);
        $criteria->compare('idtipotrabajador', $this->idtipotrabajador);
        $criteria->compare('id_titulo', $this->id_titulo);
        $criteria->compare('id_titulo_tipo_credito', $this->id_tipo_credito);
        $criteria->compare('id_tipo_credito', $this->id_tipo_credito);
        $criteria->compare('id_estatus', $this->id_estatus);
        $criteria->compare('prestamo', $this->prestamo);
        $criteria->compare('taza_interes', $this->taza_interes);
        $criteria->compare('cuota_pagar', $this->cuota_pagar);
        $criteria->compare('intereses', $this->intereses, true);
        $criteria->compare('capital', $this->capital, true);
        $criteria->compare('mto_cancelado', $this->mto_cancelado, true);
        $criteria->compare('deuda_actual', $this->deuda_actual);
        $criteria->compare('cuotas_pagadas', $this->cuotas_pagadas, true);
        $criteria->compare('cuotas_pendientes', $this->cuotas_pendientes, true);
        //aprobado y pagado
        // $criteria->compare('estaus_credito',true);

        $from = $to = '';
        if (isset($this->fecha_inicio)) {
            $from = $this->fecha_inicio;
        }
        if (isset($this->fecha_fin)) {
            $to = $this->fecha_fin;
        }
        if ($from != '' || $to != '') {
            if ($from != '' && $to != '') {
                $from = date("d-m-Y", strtotime($from));
                $to = date("d-m-Y", strtotime($to));
                $criteria->compare('fecha_registro', ">= $from", false);
                $criteria->compare('fecha_registro', "<= $to", false);
            } else {
                if ($from != '')
                    $creation_time = $from;
                if ($to != '')
                    $creation_time = $to;
                $creation_time = date("d-m-Y", strtotime($creation_time));
                $criteria->compare('fecha_registro', "$creation_time", false);
            }
        }
        $criteria->order='fecha_registro DESC';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria
        ));
    }

    public function searchRoRPrestamo($id) {
        // @todo Please modify the following code to remove attributes that should not be searched.
        $criteria = new CDbCriteria;
        if(isset($_GET['cedula'])){//echo $_GET['cedula'];exit;
            if(is_numeric($_GET['cedula'])){
                $id= Asociado::model()->find('cedula=:cedula AND blnborrado= FALSE',array(':cedula'=>$_GET['cedula']))->idasociado;
            }
            else {
                $id = 0;
            }
        }

        $criteria->with='tipoCredito';
        $criteria->condition = 'idasociado=' . (INT)$id.' AND id_estatus_credito=4 AND (refinanciamiento = true or reestructuracion = true)';
        // $criteria->compare('idtrabajador',$this->idtrabajador);
        $criteria->compare('idcredito', $this->idcredito);
        $criteria->compare('cedula', $this->cedula);
        $criteria->compare('nombre', $this->nombre, true);
        $criteria->compare('apellidos', $this->apellidos, true);
        $criteria->compare('fecha_registro',$this->fecha_registro,true);
        $criteria->compare('idunidad', $this->idunidad);
        $criteria->compare('idtipotrabajador', $this->idtipotrabajador);
        $criteria->compare('id_titulo', $this->id_titulo);
        $criteria->compare('id_tipo_credito', $this->id_tipo_credito);
        $criteria->compare('prestamo', $this->prestamo);
        $criteria->compare('id_estatus', $this->id_estatus);
        $criteria->compare('taza_interes', $this->taza_interes);
        $criteria->compare('cuota_pagar', $this->cuota_pagar);
        $criteria->compare('intereses', $this->intereses, true);
        $criteria->compare('capital', $this->capital, true);
        $criteria->compare('mto_cancelado', $this->mto_cancelado, true);
        $criteria->compare('deuda_actual', $this->deuda_actual);
        $criteria->compare('cuotas_pagadas', $this->cuotas_pagadas, true);
        $criteria->compare('cuotas_pendientes', $this->cuotas_pendientes, true);
        //aprobado y pagado
        // $criteria->compare('estaus_credito',true);

        $from = $to = '';
        if (isset($this->fecha_inicio)) {
            $from = $this->fecha_inicio;
        }
        if (isset($this->fecha_fin)) {
            $to = $this->fecha_fin;
        }
        if ($from != '' || $to != '') {
            if ($from != '' && $to != '') {
                $from = date("d-m-Y", strtotime($from));
                $to = date("d-m-Y", strtotime($to));
                $criteria->compare('fecha_registro', ">= $from", false);
                $criteria->compare('fecha_registro', "<= $to", false);
            } else {
                if ($from != '')
                    $creation_time = $from;
                if ($to != '')
                    $creation_time = $to;
                $creation_time = date("d-m-Y", strtotime($creation_time));
                $criteria->compare('fecha_registro', "$creation_time", false);
            }
        }
        $criteria->order='fecha_registro DESC';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria
        ));
    }


    public function searchReporteCreditos() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;
        // $criteria->select = 'cedula,nombre,apellidos,fecha_registro,idunidad,id_tipo_credito,prestamo,taza_interes,garantia,cuota_pagar, '.
        // 										'intereses,capital,mto_cancelado,deuda_actual,cuotas_pagadas,cuotas_pendientes';
        //

		$criteria->compare('idasociado', $this->idasociado);
       // $criteria->compare('idtrabajador', $this->idtrabajador);
        $criteria->compare('idcredito', $this->idcredito);
        $criteria->compare('cedula', $this->cedula);
        $criteria->compare('nombre', $this->nombre, true);
        $criteria->compare('apellidos', $this->apellidos, true);
        // $criteria->compare('fecha_registro',$this->fecha_registro,true);
        $criteria->compare('idunidad', $this->idunidad);
        $criteria->compare('idtipotrabajador', $this->idtipotrabajador);
        $criteria->compare('id_estatus', $this->id_estatus);
        $criteria->compare('id_tipo_credito', $this->id_tipo_credito);
        $criteria->compare('id_titulo', $this->id_titulo);
        $criteria->compare('prestamo', $this->prestamo);
        $criteria->compare('taza_interes', $this->taza_interes);
        $criteria->compare('cuota_pagar', $this->cuota_pagar);
        $criteria->compare('intereses', $this->intereses);
        $criteria->compare('capital', $this->capital, true);
        $criteria->compare('mto_cancelado', $this->mto_cancelado);
        $criteria->compare('deuda_actual', $this->deuda_actual);
        $criteria->compare('cuotas_pagadas', $this->cuotas_pagadas);
        $criteria->compare('cuotas_pendientes', $this->cuotas_pendientes);
        // $criteria->compare('estaus_credito',true);
        // $criteria->limit = 10;

        $from = $to = '';
        if (isset($this->fecha_inicio)) {
            $from = $this->fecha_inicio;
        }
        if (isset($this->fecha_fin)) {
            $to = $this->fecha_fin;
        }
        // echo $from."-- ".$to;exit;
        if ($from != '' || $to != '') {
            if ($from != '' && $to != '') {
                // $from = date("d-m-Y", strtotime($from));
                // $to = date("d-m-Y", strtotime($to));
                $criteria->compare('fecha_registro', ">= $from", false);
                $criteria->compare('fecha_registro', "<= $to", false);
            } else {
                if ($from != '')
                    $creation_time = $from;
                if ($to != '')
                    $creation_time = $to;
                // $creation_time = date("d-m-Y", strtotime($creation_time));
                $criteria->compare('fecha_registro', "$creation_time", false);
            }
        }
        //  $criteria->order='cedula';
        return self::model()->findAll($criteria);
    }

    public function camposExcelOmitido($campo) {
        $campos = array(
            'idasociado',
            'idcredito',
        );
        return (in_array($campo, $campos));
    }

    public function configuracionCampo($campo) {
        $campos = array(
            'cedula' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'nombre' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'apellidos' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'fecha_registro' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
            'idunidad' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'tipo_trabajador' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'lugartrabajo' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'nombre_estatus' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'nombre_titulo' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'id_tipo_credito' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'prestamo' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'intereses_total' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'taza_interes' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
          //  'garantia' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'cuota_pagar' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'intereses_pagados' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'capital' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'intereses' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'capital_especial' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'interes_especial' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'deuda_total' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'capital_pagados' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'mto_cancelado' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'deuda_actual' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'deudas_interes' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'cuotas_pagadas' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
            'cuotas_pendientes' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
            'nombre_estatus_credito' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
        );

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

    public function configuracionCampo2() {
        return array(
            'idcredito' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'cedula' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'nombre' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'apellidos' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'fecha_registro' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
            'idunidad' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'tipo_trabajador' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'lugartrabajo' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'nombre_estatus' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'nombre_titulo' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'id_tipo_credito' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_LEFT'),
            'prestamo' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'intereses_total' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'taza_interes' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
           // 'garantia' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'cuota_pagar' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'capital' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'intereses' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'capital_especial' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'interes_especial' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'deuda_total' => array('color' => '04B486', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'capital_pagados' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'intereses_pagados' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'mto_cancelado' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'deuda_actual' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'deudas_interes' => array('color' => 'C00000', 'resumen' => true, 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_RIGHT', 'formato' => '#,##0.00'),
            'cuotas_pagadas' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
            'cuotas_pendientes' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
            'nombre_estatus_credito' => array('color' => 'C00000', 'alineacion' => 'PHPExcel_Style_Alignment::HORIZONTAL_CENTER'),
        );
    }

    public function getTotalMontoAprobado($id) {
        $total = 0;
        $model = self::model()->find(array('select' => 'sum(prestamo) AS prestamo',
            'condition' => 'idasociado=:idasociado AND id_estatus_credito IN(2,4,7,9)',
            'params' => array(':idasociado' => $id)));
        if ($model)
            $total = $model->prestamo;

        return $total;
    }

    public function getTotalMontoDeuda($id)
    {
        return Yii::app()->db->createCommand('
            SELECT case tc.metodo_liberacion_capital
                      when 1 then sum(coalesce(t.deuda_actual, 0)) + sum(coalesce(t.deuda_actual_esp, 0))
                      when 2 then sum(coalesce(t.prestamo, 0))
                   end as total
            FROM "reporte_creditos" "t"
            inner join prestamos.tipo_credito tc on t.id_tipo_credito=tc.id
            WHERE t.idasociado=:id
                AND t.afecta_disponibilidad_haberes=TRUE
                AND t.id_estatus_credito IN (4,7,9,15,16)
            group by tc.metodo_liberacion_capital
        ')->bindValue('id', $id)->queryRow()['total'];
    }

    public function getTotalMontoDeudaConBloqueo($id)
    {
        $total = 0;
        $model = Yii::app()->db->createCommand('
            SELECT t.idasociado,
                   t.id_tipo_credito,
                   t.prestamo,
                   t.deuda_actual,
                   t.deuda_actual_esp,
                   tc.metodo_liberacion_capital,
                   tc.monto_disponibilidad_solicitudes
            FROM "reporte_creditos" "t"
            inner join prestamos.tipo_credito tc on t.id_tipo_credito=tc.id
            WHERE t.idasociado=:id
                AND t.afecta_disponibilidad_haberes=TRUE
                AND t.id_estatus_credito IN (4,7,9,15,16)
        ')->bindValue('id', $id)->queryAll();

        if (! $model) {
            return $total;
        }

        foreach ($model as $prestamo) {
            if ($prestamo['metodo_liberacion_capital'] == 2) {
                $total += $prestamo['prestamo'];
            } else {
                $total += $this->calcularSaldoDeudorConBloqueo($prestamo);
            }
        }

        return $total;
    }

    protected function calcularSaldoDeudorConBloqueo($prestamo)
    {
        Yii::import('application.modules.prestamo.models.*', true);
        $bloqueo = new DeudaActual($prestamo['idasociado']);

        if ($bloqueo->isEmpty($prestamo)) {
            return $prestamo['deuda_actual'] + $prestamo['deuda_actual_esp'];
        }

        return $bloqueo->get($prestamo);
    }

    public function getTotalMontoDeudaSinGarantia($id) {
        $total = 0;
        $model = self::model()->find(array('select' => 'sum(deuda_actual)+sum(deuda_actual_esp) AS deuda_actual',
            'condition' => 'idasociado=:idasociado AND id_clasificacion_tipo_credito !=2 AND id_estatus_credito IN(4,7,9,15,16)',
            'params' => array(':idasociado' => $id)));
        if ($model)
            $total = $model->deuda_actual;

        return $total;
    }

    public function getTotalMontoDeudaConGarantia($id) {
        $total = 0;
        $model = self::model()->find(array('select' => 'sum(COALESCE(deuda_actual, 0::numeric))+sum(COALESCE(deuda_actual_esp, 0::numeric)) AS deuda_actual',
            'condition' => 'idasociado=:idasociado AND id_clasificacion_tipo_credito =2 AND id_estatus_credito IN(4,7,9,15,16)',
            'params' => array(':idasociado' => $id)));
        if ($model)
            $total = $model->deuda_actual;

        return $total;
    }

    public function getTotalMontoRemanenteComprometido($id) {
        $total = 0;

       // $model = Credito::model()->find(array('select' => 'sum(haberes) AS haberes',
       //     'condition' => 'idasociado=:idasociado AND id_tipo_credito =7 AND pagado = true',
       //     'params' => array(':idasociado' => $id)));
       // $modelCreditoPagado = self::model()->find(array('select' => 'sum(capital_pagados) AS capital_pagados',
       //     'condition' => 'idasociado=:idasociado AND id_tipo_credito =7',
       //     'params' => array(':idasociado' => $id)));
       // if ($model)
       //     $total = $model->haberes - $modelCreditoPagado->capital_pagados;

        return $total;
    }

    public function getTotalCuotasPagada($id) {
        $total = 0;
        $model = self::model()->find(array('select' => 'sum(cuotas_pagadas) AS cuotas_pagadas',
            'condition' => 'idasociado=:idasociado AND id_estatus_credito IN(2,4)',
            'params' => array(':idasociado' => $id)));
        // print_r($model);exit;
        // print number_format($model->deuda_actual,2,",",".") ;exit;
        if ($model)
            $total = $model->cuotas_pagadas;

        return $total;
    }

    public function getTotalMontoFiador($id) {/*
        $total = '0';
        $model = CreditoFiador::model()->find(array('select' => 'sum(monto_credito) AS monto_credito',
            'condition' => 'estatus=1 and idasociado=:idtrabajador',
            'params' => array(':idtrabajador' => $id)));

        if ($model)
            $total = $model->monto_credito;*/

        return 0;
    }

    public function getMontoDeudaActual($id = null, $id_in  = null)
    {
        if(! is_null($id_in) && $id_in != ''){
            $id = trim($id_in, ',');
        }

        return Yii::app()->getDb()->createCommand("
            select coalesce(sum(monto),0)
            from (
                select case coalesce(cdc.id::boolean, false)
                        when false then coalesce(cta.monto_capital,0)
                        when true then coalesce(cdc.capital_cobro,0)
                    end as monto
                from prestamos.credito_tabla_amortizacion cta
                inner join prestamos.credito c on c.id=cta.idcredito
                    and c.id in ({$id})
                    and c.blnborrado is false
                left join prestamos.datos_txt_tabla_amortizacion dtta on dtta.id_tabla_amortizacion=cta.id
                    and dtta.actual is true
                left join prestamos.cobro_diferencial_cuota cdc on cdc.id_proceso=dtta.id
                    and cdc.blnborrado is false
                where cta.blnborrado IS FALSE
                    and (cta.id_estatus_cuota is null or cta.id_estatus_cuota in (1, 3, 6, 7, 8, 9, 12))
            ) d
        ")->queryScalar();
    }

    public function getMontoDeudaActualConfigurado($id)
    {
        $model = Credito::model()->findAll('id in ('.trim($id, ',').')');

        $total = 0;
        foreach ($model as $key => $value) {
            $estatusCuotaParaSaldoDeudor = ConfCreditoAbono::model()->getCondicionCuotasCredito($value->id_tipo_nomina);

            $saldoParaAbono = Yii::app()->getDb()->createCommand("
                select coalesce(sum(monto),0)
                from (
                    select case coalesce(cdc.id::boolean, false)
                            when false then coalesce(cta.monto_capital,0)
                            when true then coalesce(cdc.capital_cobro,0)
                        end as monto
                    from prestamos.credito_tabla_amortizacion cta
                    inner join prestamos.credito c on c.id=cta.idcredito
                        and c.id=:credito
                        and c.blnborrado is false
                    left join prestamos.datos_txt_tabla_amortizacion dtta on dtta.id_tabla_amortizacion=cta.id
                        and dtta.actual is true
                    left join prestamos.cobro_diferencial_cuota cdc on cdc.id_proceso=dtta.id
                        and cdc.blnborrado is false
                    where cta.blnborrado IS FALSE
                        {$estatusCuotaParaSaldoDeudor}
                ) d")->bindValue('credito', $value->id)->queryScalar();

            $total += $saldoParaAbono;
        }

        return $total;
    }

    public function getMontoDeudaActualConfiguradoViejo($id)
    {
        $total = 0;
        $model = Credito::model()->findByPk($id);
        $sql = ConfCreditoAbono::model()->getCondicionCuotasCredito($model->id_tipo_nomina);

        $modelTabla = CreditoTablaAmortizacion::model()->find([
            'select' => 'sum(monto_capital) as monto_capital',
            'condition' => 'idcredito in(:idcredito) '.$sql.' AND blnborrado= false',
            'params' => [
                'idcredito' => $id,
            ],
        ]);

        if ($modelTabla) {
            $total = $modelTabla->monto_capital;
        }

        return $total;
    }

    public static function getMontoDeudaActualConfiguradoTipoNomina($idCredito, $idTipoNomina)
    {
        $total = 0;
        $sql = ConfCreditoAbono::model()->getCondicionCuotasCredito($idTipoNomina);

        $modelTabla = CreditoTablaAmortizacion::model()->find([
            'select' => 'sum(monto_capital) as monto_capital',
            'condition' => 'idcredito =:idcredito '.$sql.' AND blnborrado= false',
            'params' => [
                'idcredito' => $idCredito,
            ],
        ]);

        if ($modelTabla) {
            $total = $modelTabla->monto_capital;
        }

        return $total;
    }

    public function getTotalMontoTotalDeuda($id) {
        $total = 0;
        $sql ='SELECT sum(monto_capital) as monto_capital
            FROM "prestamos"."credito_tabla_amortizacion" "t"
            LEFT OUTER JOIN "prestamos"."credito" "idCredito" ON ("t"."idcredito"="idCredito"."id")
            LEFT OUTER JOIN "prestamos"."credito_seguimiento" "idCreditoSeguimiento" ON ("idCreditoSeguimiento"."id_credito"="idCredito"."id" AND "actual" = true)
            WHERE (idasociado=:idasociado AND id_estatus_credito IN(4,7,9,15,16) AND id_estatus_cuota is NULL) AND t.blnborrado= false';
        $model = CreditoTablaAmortizacion::model()->findBySql($sql,array(':idasociado' => $id));
        if ($model)
            $total = $model->monto_capital;

        return $total;
    }

    public function afterFind() {
       // if ($this->fecha_registro != '')
       //     $this->fecha_registro = date('d/m/Y', strtotime($this->fecha_registro));

        // if(isset($this->prestamo))
        // $this->prestamo=number_format($this->prestamo,2,",", ".");
        // if(isset($this->cuota_pagar))
        // $this->cuota_pagar=number_format($this->cuota_pagar,2,",", ".");
        // if(isset($this->intereses))
        // $this->intereses=number_format($this->intereses,2,",", ".");
        // if(isset($this->capital))
        // $this->capital=number_format($this->capital,2,",", ".");
        // if(isset($this->mto_cancelado))
        // $this->mto_cancelado=number_format($this->mto_cancelado,2,",", ".");
        // if(isset($this->deuda_actual))
        // $this->deuda_actual=number_format($this->deuda_actual,2,",", ".");
        // if(isset($this->garantia))
        // $this->garantia=number_format($this->garantia,2,",", ".");

        if ($this->mto_cancelado == '')
            $this->mto_cancelado = 0;

        if ($this->cuotas_pagadas == '')
            $this->cuotas_pagadas = 0;

        if ($this->intereses_pagados == '')
            $this->intereses_pagados = 0;

        if ($this->capital_pagados == '')
            $this->capital_pagados = 0;

       // if ($this->garantia == '')
       //     $this->garantia = 0;

        if ($this->deuda_actual == '')
            $this->deuda_actual = 0;

        if ($this->cuotas_pendientes == '')
            $this->cuotas_pendientes = 0;

        if ($this->deudas_interes == '')
            $this->deudas_interes = 0;



       // $model = CreditoSeguimiento::model()->find('id_credito=:id AND actual =  TRUE',array(':id'=>  $this->idcredito));
       // if($model){
       //     $this->nombre_estatus = $model->idEstatusCredito->nombre_estatus;
       //     $this->id_estatus = $model->id_estatus_credito;
       // }
       // $model = CreditoSeguimiento::model()->find('id_credito=:id AND id_estatus_credito =1',array(':id'=>  $this->idcredito));
       // if($model){
       //     $this->fecha_registro = $model->fecha_registro;
       // }
        //  [deuda_actual] => 4767.44
        //  [cuotas_pagadas] => 3
        //  [cuotas_pendientes] => 9

        return parent::afterFind();
    }

    /**
     * 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 ReporteCreditos the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    private function getAsociado($cedula)
    {
        if(! is_numeric($cedula)) {
            return 0;
        }

        $asociado = Asociado::model()->find('cedula=:cedula AND blnborrado= FALSE AND id_estatus in(1,4) ORDER BY idasociado desc', array(
            'cedula' => $cedula
        ));

        if (is_null($asociado)) {
            return null;
        }

        return $asociado->idasociado;
    }
}
