<?php

/**
 * This is the model class for table "contable.cierre_mes".
 *
 * The followings are the available columns in table 'contable.cierre_mes':
 * @property integer $id
 * @property integer $id_cierre
 * @property integer $id_usuario
 * @property string $observacion
 * @property integer $id_periodo
 * @property string $fecha_cierre
 *
 * The followings are the available model relations:
 * @property CrugeUser $idUsuario
 * @property EstatusEjercicio $idPeriodo
 */
class CierreMes extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
         
	public function tableName()
	{
		return 'contable.cierre_mes';
	}
      

	/**
	 * @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('id_cierre, id_usuario, id_periodo', 'numerical', 'integerOnly'=>true),
			array('observacion, fecha_cierre', 'safe'),
			array('fecha_cierre', 'validarcierre'),
			array('observacion,fecha_cierre', 'required'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, id_cierre, id_usuario, observacion, id_periodo, fecha_cierre', '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 array(
			'idUsuario' => array(self::BELONGS_TO, 'CrugeUser', 'id_usuario'),
			'idPeriodo' => array(self::BELONGS_TO, 'EstatusEjercicio', 'id_periodo'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'id_cierre' => 'Id registro',
			'id_usuario' => 'Id Usuario',
			'observacion' => 'Observacion',
			'id_periodo' => 'Id Periodo',
			'fecha_cierre' => 'Fecha cierre',
		);
	}

	/**
	 * 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('id',$this->id);
		$criteria->compare('id_cierre',$this->id_cierre);
		$criteria->compare('id_usuario',$this->id_usuario);
		$criteria->compare('observacion',$this->observacion,true);
		$criteria->compare('id_periodo',$this->id_periodo);
		$criteria->compare('fecha_cierre',$this->fecha_cierre,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$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 CierreMes the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
        
        public function periodonombre(){
            $id=$_GET['id'];
            $ejerciciocontable=  EjerciciosContables::model()->find("id=(select id_periodo from contable.cierre_mensual where id =$id)");
             return $ejerciciocontable->nombre_periodo;
          
        }
        public function periodoanio(){
            $id=$_GET['id'];
             $ejerciciocontable=  EjerciciosContables::model()->find("id=(select id_periodo from contable.cierre_mensual where id =$id)");
             return date('Y',  strtotime($ejerciciocontable->fecha_inicio));
          
        }
        public function periodomes(){
             $id=$_GET['id'];
             $modelocierre= CierreMensual::model()->find("id=$id");
             return $modelocierre->mes;
          
        }
        
  public function fechainicio(){
    Yii::import('application.modules.configuracion.models.*',true);
    Yii::import('application.modules.contable.models.*',true);
        if (ConfContable::config('CONFCONTABLE')=='SI'){
            $id=$_GET['id'];
            $ejerciciocontable=  EjerciciosContables::model()->find("id=(select id_periodo from contable.cierre_mensual where id =$id)");
            $modelcierre= CierreMensual::model()->findBySql("select * from contable.cierre_mensual where estatus=false and id_periodo = $ejerciciocontable->id and id =(select min(id) from contable.cierre_mensual where estatus=false and id_periodo =$ejerciciocontable->id )");
            if ($modelcierre && $ejerciciocontable){
                $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'){
            $id=$_GET['id'];
            $ejerciciocontable=  EjerciciosContables::model()->find("id=(select id_periodo from contable.cierre_mensual where id =$id)");
            $fecha= date('d-m-Y',strtotime($ejerciciocontable->fecha_fin));
        }else{
            $fecha='31-12-'.date('Y'); 
        }
    return $fecha;    
}
        
        
        public function validarcierre(){
            Yii::import('application.modules.configuracion.models.*',true);
            if(!$this->hasErrors('fecha_cierre')){
                        if (ConfContable::config('CONFCONTABLE')=='SI'){
               Yii::import('application.modules.contable.models.*',true);
                $id=$_GET['id'];
                $ejerciciocontable=  EjerciciosContables::model()->find("id=(select id_periodo from contable.cierre_mensual where id =$id)");
               $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=$ejerciciocontable->id)");
               $modeltrimestreprecierre= 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 estatus=2 and id!=$ejerciciocontable->id order by id))");
               $ejercicioprecierre= EjerciciosContables::model()->findAll("estatus=2 and id!=$ejerciciocontable->id");
               $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 and id_periodo=$ejerciciocontable->id )) as mes_anterior 
from contable.cierre_mensual where id= (select min(id) as id from contable.cierre_mensual where estatus=false  and id_periodo=$ejerciciocontable->id)
");
               $modelcomprobante= Comprobante::model()->findAllBySql("select * from contable.comprobante where fecha_comprobante between (select fecha_desde from contable.cierre_mensual where id= (select min(id) as id from contable.cierre_mensual where estatus=false and id_periodo=$ejerciciocontable->id)) and
(select fecha_hasta from contable.cierre_mensual where id= (select min(id) as id from contable.cierre_mensual where estatus=false and id_periodo=$ejerciciocontable->id))
and status=2");
               $cuenta=count($modelcomprobante);

               $fecha_desde= date('d-m-Y',strtotime($modeltrimestre->fecha_desde));
               $fecha_hasta= date('d-m-Y',strtotime($modeltrimestre->fecha_hasta));
               if ($cuenta >= 1 ){
                    $this->addError('fecha_cierre',"Hay comprobantes NO CONTABILIZADOS en el mes de $modelmes->mes <br/>");
                    foreach ($modelcomprobante as $comprobante):
                        
                        $this->addError('fecha_cierre',"
                                ".CHtml::link('N° Comprobante: '.$comprobante->num_comprobante,array('DetalleComprobante/create&id2='.$comprobante->id)) );
                    endforeach;
               }
               else if (($modelmes->mes=="ABRIL") && ($modeltrimestre->trimestre=="Trimestre 1")){
                       $this->addError('fecha_cierre',"Debe cerrar el $modeltrimestre->trimestre antes de continuar.<br/>");
                   
               }
               else if (($modelmes->mes=="JULIO") && ($modeltrimestre->trimestre=="Trimestre 2")){
                       $this->addError('fecha_cierre',"Debe cerrar el $modeltrimestre->trimestre antes de continuar.<br/>");
                   
               }
               else if (($modelmes->mes=="OCTUBRE") && ($modeltrimestre->trimestre=="Trimestre 3")){
                       $this->addError('fecha_cierre',"Debe cerrar el $modeltrimestre->trimestre antes de continuar.<br/>");
                   
               }
               else if (($modelmes->mes=="ENERO") && ($modeltrimestreprecierre)){
                       $añoprecierre=date('Y',strtotime($modeltrimestreprecierre->fecha_desde)); 
                       $this->addError('fecha_cierre',"Debe cerrar el $modeltrimestreprecierre->trimestre del año $añoprecierre antes de continuar.<br/>");
                   
               }
               else if (($modelmes->mes=="ENERO") && ($ejercicioprecierre)){
                       $añoprecierre=date('Y',strtotime($ejercicioprecierre[0]->fecha_inicio)); 
                       $nombre=$ejercicioprecierre[0]->nombre_periodo;
                       $this->addError('fecha_cierre',"Debe cerrar el periodo contable <strong>$nombre</strong> del año $añoprecierre antes de continuar.<br/>");
                   
               }
                 
              
           }
               
            }
            
        }
        
        
}