<?php

class Scripts extends GxActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'scripts';
    }

    public function behaviors()
    {
        return array('datetimeI18NBehavior' => array('class' => 'ext.DateTimeI18NBehavior'));
    }

    public function rules()
    {
        return array(
            array(
                '
                    SCR_SCRIPT, SCR_IDPENDENCIA, SCR_DATAHORA, SCR_ORDEMEXECUCAO,
                    SCR_IDFUNCIONARIO, SCR_ATIVO
                ',
                'required'
            ),
            array(
                'SCR_IDPENDENCIA, SCR_ORDEMEXECUCAO, SCR_IDFUNCIONARIO, SCR_ATIVO',
                'numerical',
                'integerOnly' => true
            ),
            array('SCR_SCRIPT', 'verificaScript'),
        );
    }

    public function relations()
    {
        return array(
            'Pendencia' => array(self::BELONGS_TO, 'Solicitacoes', 'SCR_IDPENDENCIA', 'joinType'=>'LEFT JOIN'),
            'Funcionario' => array(self::BELONGS_TO, 'Funcionarios', 'SCR_IDFUNCIONARIO', 'joinType'=>'LEFT JOIN'),
        );
    }

    public function attributeLabels()
    {
        return array(

        );
    }

    public function verificaScript($attribute, $params)
    {
/*        $newScript = str_replace("|||", "", str_replace([" ", "\n"], "|||", $this->SCR_SCRIPT));
        $newScript = strtolower($newScript);

        $conditions = array();
        $conditions[] = "
            LOWER(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            SCR_SCRIPT,
                            ' ',
                            \"|||\"
                        ),
                        '\n',
                        '|||'
                    ),
                    '|||',
                    ''
                )
            ) = \"{$newScript}\"
        ";
        if (!$this->isNewRecord) {
            $conditions[] = "SCR_IDPENDENCIA <> \"{$this->SCR_IDPENDENCIA}\"";
        }

        $conditions = implode(" AND ", $conditions);
        $sql = "
            SELECT SCR_IDSCRIPT, SCR_IDPENDENCIA
            FROM scripts
            WHERE
                {$conditions}
        ";
        $command = Yii::app()->db->createCommand($sql);
        $result = $command->queryAll();

        if (!empty($result)) {
            $this->addError($attribute, "Script já cadastrado na pendência Nº {$result[0]['SCR_IDPENDENCIA']}");
            return false;
        }*/

        return true;
    }
}
