<?php

/**
 * This is the model class for table "comprobante".
 *
 * The followings are the available columns in table 'comprobante':
 * @property integer $id
 * @property string $fecha_comprobante
 * @property integer $numero
 * @property string $descripcion
 * @property integer $id_cuenta
 * @property integer $status
 * @property string $centro_costo
 * @property integer $id_usuario
 * @property string $nombre_auxiliar
 * @property string $nro_documento
 * @property string $fecha_registro
 * @property boolean $blnborrado
 * @property boolean $fechainicio
 */
class Comprobante extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'contable.comprobante';
	}
        public $fecha_comprobante_range = array();
	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('numero,status, id_usuario', 'numerical', 'integerOnly'=>true),
			array('fecha_comprobante,descripcion', 'required','on'=>'crea'),
			array('observacion_anulacion', 'required','on'=>'anular'),
			// array('fecha_comprobante', 'validarfecha','on'=>array('crea','actualiza')),
			array('fecha_comprobante,mes,num_comprobante, clvejercicio,descripcion, nro_documento,mov_apertura, fecha_registro, blnborrado,fecha_anulacion,observacion_anulacion,usuario_anulacion,id_automatico, id_tipo_comprobante', 'safe'),
			array('fecha_comprobante, numero, descripcion,fecha_comprobante_range, status,  id_usuario,  nro_documento, fecha_registro, blnborrado,fecha_anulacion,observacion_anulacion,usuario_anulacion,id_automatico', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
    {
        return [
            //'cuenta' => array(self::BELONGS_TO, 'CuentasConsolidada', 'id_cuenta'),
            'estatus' => [self::BELONGS_TO, 'EstatusComprobante', 'status'],
            'usuario' => [self::BELONGS_TO, 'CrugeUserI', 'id_usuario'],
            'usuario2' => [self::BELONGS_TO, 'CrugeUserI', 'usuario_anulacion'],
            'eje' => [self::BELONGS_TO, 'EjerciciosContables', 'clvejercicio'],
            'detalleComprobante' => [self::HAS_MANY, 'DetalleComprobante', 'clv_comprobante'],
        ];
    }

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'fecha_comprobante' => 'Fecha comprobante',
			'numero' => 'Número',
			'descripcion' => 'Descripción',
			'mov_apertura' => '<b>¿Movimiento de apertura?</b>',
			//'id_cuenta' => 'Id Cuenta',
			'status' => 'Estatus',
			//'centro_costo' => 'Centro Costo',
			'id_usuario' => 'Usuario',
			'mes' => 'Mes',
			'num_comprobante' => 'N° comprobante',
			//'nombre_auxiliar' => 'Nombre Auxiliar',
			'nro_documento' => 'N° documento',
			'fecha_registro' => 'Fecha registro',
			'blnborrado' => 'Blnborrado',
			'observacion_anulacion' => 'Motivo anulación',
			'usuario_anulacion' => 'Usuario anula',
		);
	}

	/**
	 * 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()
    {
        $act = EjerciciosContables::model()->find('activo=1');
        $criteria = new CDbCriteria();
        $criteria->compare('fecha_comprobante',$this->fecha_comprobante,true);
        $criteria->compare('numero', $this->numero, true);
        $criteria->compare('num_comprobante', $this->num_comprobante, true);
        $criteria->compare('mes', $this->mes);
        $criteria->compare('LOWER(descripcion)', strtolower($this->descripcion), true);
        $criteria->compare('status', $this->status);
        $criteria->compare('lower(nro_documento)', strtolower($this->nro_documento), true);

        $from = $to = '';
        if (count($this->fecha_comprobante_range) >= 1) {
            if (isset($this->fecha_comprobante_range['from'])) {
                $from = $this->fecha_comprobante_range['from'];
            }
            if (isset($this->fecha_comprobante_range['to'])) {
                $to = $this->fecha_comprobante_range['to'];
            }
        }

        if ($from != '' || $to != '') {
            if ($from != '' && $to != '') {
                $from = date('d-m-Y', strtotime($from));
                $to = date('d-m-Y', strtotime($to));
                $criteria->compare('fecha_comprobante', ">= $from", false);
                $criteria->compare('fecha_comprobante', "<= $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_comprobante', "$creation_time", false);
            }
        }

        $criteria->addCondition('blnborrado IS FALSE');
        $criteria->addCondition("clvejercicio={$act->id}");
        $criteria->order = 'fecha_comprobante desc,numero desc';

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

    public function searchDetalleComprobante()
    {
        $sql = $this->sqlDetalleComprobante();
        $rawData = Yii::app()->db->createCommand($sql);
        $count = Yii::app()->db->createCommand('SELECT COUNT(*) FROM (' . $sql . ') as count_alias')->queryScalar();

        return new CSqlDataProvider($rawData, [
            'keyField' => 'id',
            'totalItemCount' => $count,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);
    }

    public function sqlDetalleComprobante()
    {
        return "SELECT dc.id,
                       cc.id AS id_cuenta,
                       dc.clv_comprobante,
                       cc.cuenta,
                       concat(cc.codigo_cuenta, ' ', cc.descripcion) AS codigo_cuenta,
                       dc.descripcion,
                       dc.fecha_referencia,
                       dc.referencia,
                       cc.naturaleza,
                       dc.monto_debe,
                       dc.monto_haber
                FROM contable.det_comprobante dc
                INNER JOIN contable.cuentas_consolidada cc ON cc.id=dc.id_cuenta
                WHERE dc.clv_comprobante={$this->id}
                    AND dc.blnborrado IS FALSE
                ORDER BY CASE WHEN dc.monto_debe<>0
                            THEN 1
                            ELSE 2
                         END ASC,
                         cc.cuenta";
    }

    public function detalleComprobante()
    {
        return Yii::app()->db->createCommand(
            $this->sqlDetalleComprobante()
        )->queryAll();
    }

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

        public function concatenar($nombre,$apellido){

            $nombrec=$nombre.' '.$apellido;

            return $nombrec;
        }
        public function beforeSave(){
            $this->id_usuario=Yii::app()->user->id;

            return parent::beforeSave();

        }

        public function validarEjercioContable($id){
            Yii::import('application.modules.contable.models.*',true);
           $ejerciciocontable=  EjerciciosContables::model()->find("estatus=1 or estatus=2  and activo=1");
           $mensaje='';
                  if (!isset($ejerciciocontable->id)){
                     $mensaje.="No hay ningún ejercicio contable<strong> abierto o en pre-cierre</strong> deberá crearlo o seleccionarlo para continuar.<br/>";
                  }
            return $mensaje;
        }

public function fechainicio(){
    Yii::import('application.modules.configuracion.models.*',true);
    Yii::import('application.modules.contable.models.*',true);
        if (ConfContable::config('CONFCONTABLE')=='SI'){
            $modelejercicio = EjerciciosContables::model()->find('activo=1 and estatus=1 or estatus=2 order by id desc');
            $modelcierre= CierreMensual::model()->findBySql("select * from contable.cierre_mensual where estatus=false and id_periodo = $modelejercicio->id and id =(select min(id) from contable.cierre_mensual where estatus=false and id_periodo =$modelejercicio->id )");
            if ($modelcierre && $modelejercicio){
                $fecha=date('d-m-Y',strtotime($modelcierre->fecha_desde));
            }else{
                 $fecha= '01-01-'.date('Y');
            }

        }else{
            $fecha='01-01-'.date('Y');
        }
    return $fecha;
}

public function fechafin(){
    Yii::import('application.modules.configuracion.models.*',true);
    Yii::import('application.modules.contable.models.*',true);
        if (ConfContable::config('CONFCONTABLE')=='SI'){
            $modelejercicio = EjerciciosContables::model()->find('activo=1');
            $fecha= date('d-m-Y',strtotime($modelejercicio->fecha_fin));
        }else{
            $fecha='31-12-'.date('Y');
        }
    return $fecha;
}


public function validarfecha(){
    Yii::import('application.modules.configuracion.models.*',true);
        if(!$this->hasErrors('fecha_comprobante') && $this->isNewRecord){
            if (ConfContable::config('CONFCONTABLE')=='SI'){
               Yii::import('application.modules.contable.models.*',true);
               $modeltrimestre= CierreTrimestral::model()->findBySql('select * from contable.cierre_trimestral where id = (select min(id) as id from contable.cierre_trimestral where estatus=false and id_periodo=(
               select id from contable.ejercicios where activo=1))');
               $modelmes= CierreMensual::model()->findBySql('select *,
               (select mes from contable.cierre_mensual where id= (select max(id) as id from contable.cierre_mensual where estatus=true)) as mes_anterior
               from contable.cierre_mensual where id= (select min(id) as id from contable.cierre_mensual where estatus=false and id_periodo=(
               select id from contable.ejercicios where activo=1) )');
               if ($modeltrimestre && $modelmes){
               $fecha=date('Y-m-d',  strtotime($this->fecha_comprobante));
               $fecha_desde= date('d-m-Y',strtotime($modeltrimestre->fecha_desde));
               $fecha_hasta= date('d-m-Y',strtotime($modeltrimestre->fecha_hasta));
               $fecha_desdemes= date('d-m-Y',strtotime($modelmes->fecha_desde));
               $fecha_hastames= date('d-m-Y',strtotime($modelmes->fecha_hasta));
               $anio=date('Y',  strtotime($this->fecha_comprobante));
               $anio_hasta=date('Y',  strtotime($modelmes->fecha_hasta));
               if ($modelmes->mes=='ENERO'){
                   $modelmes->mes_anterior=', ya que las fechas de años anteriores no pertenecen a este periodo contable.';
               }else {
                   $modelmes->mes_anterior=', ya que el mes de '.$modelmes->mes_anterior.' está cerrado.';
               }
                   if ($anio < $anio_hasta){
                        $this->addError('fecha_comprobante','Usted no puede ingresar comprobantes en un año distinto al periodo contable que está seleccionado.');
                   }
                   else if ($fecha < $modelmes->fecha_desde){
                        $this->addError('fecha_comprobante','La fecha debe estar en el rango del '.$modeltrimestre->trimestre.' que va desde '.$fecha_desde.' al '.$fecha_hasta.' y debe ser mayor a '.$fecha_desdemes.' '.$modelmes->mes_anterior.'');
                   }
                   else  if ($anio > $anio_hasta){
                        $this->addError('fecha_comprobante','Usted no puede ingresar comprobantes en un año distinto al periodo contable que está seleccionado.');
                   }
               }
               else if (!$modelmes){
                    $this->addError('fecha_comprobante','Usted no puede ingresar comprobantes en esta fecha, ya que tiene todos los meses cerrados.');
               }
               else {
                    $this->addError('fecha_comprobante','En base de datos no estan cargados los meses para este periodo contable.');

               }

            }

        }

}


public function mes($mes){

      switch ($mes){
        case '01':
        $mes='ENERO';
        break;
        case '02':
        $mes='FEBRERO';
        break;
        case '03':
        $mes='MARZO';
        break;
        case '04':
        $mes='ABRIL';
        break;
        case '05':
        $mes='MAYO';
        break;
        case '06':
        $mes='JUNIO';
        break;
        case '07':
        $mes='JULIO';
        break;
        case '08':
        $mes='AGOSTO';
        break;
        case '09':
        $mes='SEPTIEMBRE';
        break;
        case '10':
        $mes='OCTUBRE';
        break;
        case '11':
        $mes='NOVIEMBRE';
        break;
        case '12':
        $mes='DICIEMBRE';
        break;

    }
     $sql= CierreMensual::model()->findBySql('select * from contable.cierre_mensual where estatus=false and id_periodo=(
               select id from contable.ejercicios where activo=1) and mes=\''.$mes.'\'');
    if ($sql){
        // Abierto
        $estatus='A';
    }else {
        // Cerrado
        $estatus='C';
    }

    return $estatus;

}
}
