<?php

/**
 * This is the model class for table "proveedor_cuenta_banco".
 *
 * The followings are the available columns in table 'proveedor_cuenta_banco':
 *
 * @property string $id
 * @property string $idbanco
 * @property string $idproveedor
 * @property string $cuenta_bancaria
 * @property bool   $cuenta_corriente
 * @property bool   $cuenta_principal
 *
 * The followings are the available model relations:
 * @property Proveedor $idproveedor0
 * @property Banco     $idbanco0
 */
class ProveedorCuentaBanco extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'proveedor_cuenta_banco';
    }

    /**
     * @return array validation rules for model attributes
     */
    public function rules()
    {
        return [
            ['idbanco, cuenta_bancaria, cuenta_corriente', 'required', 'on' => 'registro'],
            [
                ['idproveedor', 'idbanco', 'cuenta_bancaria', 'cuenta_corriente', 'cuenta_principal'],
                'required',
                'on' => 'registro_simple',
            ],
            ['cuenta_bancaria', 'numerical'],
            ['cuenta_bancaria', 'length', 'min' => 20, 'max' => 20],
            ['cuenta_bancaria', 'validarCuenta'],
            ['idbanco, idproveedor, cuenta_bancaria, cuenta_corriente, cuenta_principal', 'safe'],
            ['id, idbanco, idproveedor, cuenta_bancaria, cuenta_corriente, cuenta_principal', 'safe', 'on' => 'search'],
        ];
    }

    /**
     * @return array relational rules
     */
    public function relations()
    {
        return [
            'idproveedor0' => [self::BELONGS_TO, 'Proveedor', 'idproveedor'],
            'idBanco' => [self::BELONGS_TO, 'Banco', 'idbanco'],
        ];
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'idbanco' => 'Banco',
            'idproveedor' => 'Idproveedor',
            'cuenta_bancaria' => 'Cuenta bancaria',
            'cuenta_corriente' => 'Cuenta corriente',
            'cuenta_principal' => 'Cuenta principal',
        ];
    }

    public function validarCuenta()
    {
        if ($this->hasErrors('idbanco') && $this->hasErrors('cuenta_bancaria')) {
            return;
        }

        $model = Banco::model()->findByPk($this->idbanco);

        if ($model->codigo != substr($this->cuenta_bancaria, 0, 4)) {
            $this->addError(
                'cuenta_bancaria',
                "El numero de cuenta proporcionado no coincide con el codigo: <b>{$model->codigo}</b> del banco seleccionado."
            );
        }

        if ($this->hasErrors('cuenta_bancaria')) {
            return;
        }

        if (empty($this->idproveedor)) {
            return;
        }

        $numeroCuentaDuplicado = Yii::app()
            ->getDb()
            ->createCommand(
                'select exists(
                    select 1
                    from proveedor_cuenta_banco
                    where cuenta_bancaria = :cuenta
                        and idproveedor <> :proveedor
                )'
            )
            ->queryScalar(['cuenta' => $this->cuenta_bancaria, 'proveedor' => $this->idproveedor]);

        if ($numeroCuentaDuplicado) {
            $this->addError('cuenta_bancaria', 'El número de cuenta se encuentra registrado a otro proveedor');
        }
    }

    /**
     * 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, true);
        $criteria->compare('idbanco', $this->idbanco, true);
        $criteria->compare('idproveedor', $this->idproveedor, true);
        $criteria->compare('cuenta_bancaria', $this->cuenta_bancaria, true);
        $criteria->compare('cuenta_corriente', $this->cuenta_corriente);
        $criteria->compare('cuenta_principal', $this->cuenta_principal);

        return new CActiveDataProvider($this, [
            '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 ProveedorCuentaBanco the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

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

        if (! $model->validate()) {
            throw self::exception($model);
        }

        if (! $model->save()) {
            throw self::exception($model);
        }

        return $model;
    }

    public static function exception($model)
    {
        $proveedor = Proveedor::model()->findByPk($model->idproveedor);

        return new Exception(
            "Error <strong>{$proveedor->razon_social}</strong>: ".array_values($model->getErrors())[0][0]
        );
    }
}
