<?php

/**
 * This is the model class for table "proveedor".
 *
 * The followings are the available columns in table 'proveedor':
 * @property integer $id
 * @property string $razon_social
 * @property string $telefono
 * @property string $correo_electronico
 * @property string $rif
 * @property string $direccion_fiscal
 * @property string $id_tipo_persona
 * @property boolean $blnborrado
 *
 * The followings are the available model relations:
 * @property TipoPersona $idTipoPersona
 * @property ProveedorCuentaBanco[] $proveedorCuentaBancos
 */
class Proveedor extends CActiveRecord
{
    public $cuenta_descripcion;

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

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
            array('razon_social, correo_electronico, rif, direccion_fiscal, id_tipo_persona, id_tipo_proveedor', 'required','on'=>'registro'),
            [['razon_social','id_tipo_persona','rif','id_cuenta',], 'required', 'on' => 'registro_simple'],
			array('razon_social, rif, id_tipo_persona', 'required','on' => 'simple'),
			array('rif', 'validarProveedor','on'=>'registro, actulizar'),
			array('telefono', 'validarTelefono','on'=>'registro, actulizar'),
			array('correo_electronico', 'validarCorreo','on'=>'registro, actulizar'),
			array('correo_electronico', 'email','message'=>"El email no es correcto"),
 			array('razon_social, telefono, correo_electronico, rif, direccion_fiscal, id_tipo_persona, cuenta_descripcion, id_cuenta, id_tipo_proveedor', 'safe'),
 			array('rif', 'length', 'max'=>9),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, razon_social, telefono, correo_electronico, rif, direccion_fiscal, id_tipo_persona, id_estatus_proveedor', '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(
			'idTipoPersona' => array(self::BELONGS_TO, 'TipoPersona', 'id_tipo_persona'),
            'idEstatusProveedor' => array(self::BELONGS_TO, 'ProveedorEstatus', 'id_estatus_proveedor'),
            'proveedorCuentaBancos' => array(self::HAS_MANY, 'ProveedorCuentaBanco', 'idproveedor'),
            'proveedorCuentaBancosPrincipal' => array(self::HAS_ONE, 'ProveedorCuentaBanco', 'idproveedor','condition'=>'cuenta_principal = TRUE'),
			'cuenta' => array(self::BELONGS_TO, 'CuentasConsolidada', 'id_cuenta'),
			'tipoProveedor' => array(self::BELONGS_TO, 'TipoProveedor', 'id_tipo_proveedor'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'razon_social' => 'Nombre y Apellido / Razón social',
			'telefono' => 'Teléfono',
			'correo_electronico' => 'Correo electrónico',
			'rif' => 'Cédula/ Rif',
			'direccion_fiscal' => 'Dirección fiscal',
			'id_tipo_persona' => 'Tipo de persona',
            'id_estatus_proveedor' => 'Estatus',
			'id_cuenta' => 'Cuenta',
            'id_tipo_proveedor' => 'Tipo',
		);
	}

	/**
	 * 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()
	{
		$criteria=new CDbCriteria;
        $criteria->with = ['idTipoPersona', 'idEstatusProveedor', 'tipoProveedor'];
		$criteria->compare('id',$this->id);
		$criteria->compare('LOWER(razon_social)', strtolower($this->razon_social), true);
		$criteria->compare('telefono',$this->telefono,true);
		$criteria->compare('correo_electronico',$this->correo_electronico,true);
		$criteria->compare('rif',$this->rif,true);
		$criteria->compare('direccion_fiscal',$this->direccion_fiscal,true);
		$criteria->compare('id_tipo_persona',$this->id_tipo_persona);
		$criteria->compare('blnborrado',$this->blnborrado);
        $criteria->compare('id_estatus_proveedor',$this->id_estatus_proveedor);
        $criteria->compare('id_tipo_proveedor',$this->id_tipo_proveedor);
		$criteria->order = 'razon_social ASC';

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function validarTelefono(){
		if(is_array($this->telefono)){
			$nError = true;

			$array_telefono =[];
			foreach ($this->telefono as $key => $value) {
				if(array_key_exists($value, $array_telefono)){
                    $nError = false && $nError ;
                }
                else{
                	 $array_telefono[$value] = 1;
                }
			}
			if(!$nError)
				$this->addError('telefono','Existe un número de teléfono repetido');
		}
	}

	public function validarProveedor(){
		if(!$this->hasErrors('rif') && !$this->hasErrors('id_tipo_persona')){
			$model = self::model()->find('id_tipo_persona=:id_tp AND rif=:rif',[':id_tp'=>$this->id_tipo_persona,':rif'=>$this
				->rif]);
			if($model){
				if($this->isNewRecord){
					$this->addError('rif','Existe un proveedor registrado con esa cédula/ rif');
				}
				else{
					if($this->id != $model->id)
						$this->addError('rif','Existe un proveedor registrado con esa cédula/ rif');
				}
			}

		}
		if(!$this->hasErrors('razon_social')){
			$model = self::model()->find('razon_social=:razon_social',[':razon_social'=>$this->razon_social]);
			if($model){
				if($this->isNewRecord){
					$this->addError('razon_social','Existe un proveedor registrado con esa razón social');
				}
				else{
					if($this->id != $model->id)
						$this->addError('razon_social','Existe un proveedor registrado con esa razón social');
				}
			}

		}
	}
	public function validarCorreo(){
		if(!$this->hasErrors('correo_electronico')){
			$model = self::model()->find('correo_electronico=:correo_electronico',[':correo_electronico'=>$this->correo_electronico]);
			if($model){
				if($this->isNewRecord){
					$this->addError('correo_electronico','Ya se ha registrado un proveedor con ese correo electrónico');
				}
				else{
					if($this->id != $model->id)
						$this->addError('correo_electronico','Ya se ha registrado un proveedor con ese correo electrónico');
				}
			}

		}
	}

    public function getCuentaContable()
    {
        if ($this->isNewRecord || is_null($this->id_cuenta)) {
            return '';
        }

        return $this->cuenta->codigo_cuenta . '-' . $this->cuenta->descripcion;
    }

    public function setCuentaContable($descripcion)
    {
        $codigo = explode('-', $descripcion);
        $cuenta = CuentasConsolidada::model()->find('"codigo_cuenta"=:id', array(':id' => $codigo[0]));

        if (! $cuenta) {
            return;
        }

        $this->id_cuenta = $cuenta->id;
    }

    public function checkTelefono()
    {
        if (is_null($this->telefono)) {
            return false;
        }

        return ! empty(array_filter(json_decode($this->telefono)));
    }

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

    public static function getAll()
    {
        return CHtml::listData(
            Yii::app()->getDb()->createCommand('
                SELECT p.id, concat(tp.descripcion, p.rif, \' \', p.razon_social) AS descripcion
                FROM proveedor p
                INNER JOIN tipo_persona tp ON tp.id=p.id_tipo_persona
                WHERE blnborrado IS FALSE;
            ')->query()
        , 'id', 'descripcion');
    }

    public static function generar($datos = [])
    {
        $model = new self('registro_simple');
        $model->setAttributes($datos);

        if (! $model->validate()) {
            throw new Exception('Error al crear proveedor: '. array_values($model->getErrors())[0][0]);
        }

        if (! $model->save()) {
            throw new Exception('Error al guardar proveedor.');
        }

        return $model;
    }

    public static function getIf($datos)
    {
        $proveedor = self::model()->find([
            'condition' => 'rif=:rif AND id_tipo_persona=:tipo_persona AND id_tipo_proveedor=:tipo_proveedor',
            'params' => $datos
        ]);

        if (! $proveedor) {
            return false;
        }

        return $proveedor;
    }
}
