<?php

/**
 * This is the model base class for the table "bi_report".
 * DO NOT MODIFY THIS FILE! It is automatically generated by giix.
 * If any changes are necessary, you must set or override the required
 * property or method in class "Report".
 *
 * Columns in table "bi_report" available as properties of the model,
 * followed by relations of table "bi_report" available as properties of the model.
 *
 * @property integer $report_id
 * @property string $name
 * @property string $sql_query
 * @property string $pivot_config
 * @property integer $disable_edit
 * @property integer $date_range
 * @property string $date_from
 * @property string $date_to
 * @property string $date_field
 * @property integer $active
 * @property string $note
 * @property integer $order_number
 */
abstract class BaseReport extends GxActiveRecord
{

    public $pivot_config_temp;

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

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


    /**
     * Validizacije setuje user id -eve
     *
     */


    public static function label($n = 1)
    {
        return Yii::t('app', 'Izveštaj|Izveštaji', $n);
    }

    public static function representingColumn()
    {
        return 'name';
    }


    /**
     * @return string
     * generiše JSON na osnovu rezultata sql upita
     */
    public function convertToJSON($limit = 100000)
    {
        if ($this->isValidSQL()) {
            if ($this->sql_query) {
                $sql = $this->sql_query;
                $imawhere = true;
                if (($this->date_range == 1) && ($this->date_field != null)) {
                    $a = 'where';

                    // ako ne postoji where dodaje

                    if (strpos($sql, $a) == false) {
                        $sql .= ' where ';
                        $imawhere = false;
                    }
                    // dodaje polja za filtriranje perioda
                    if ($this->date_from) {

                        if ($imawhere) {
                            $sql .= ' and ';
                        }

                        $sql .= '   ' . $this->date_field . '  >= "' . $this->date_from . '"';
                    }
                    if ($this->date_to) {
                        $sql .= ' and ' . $this->date_field . '  <= "' . $this->date_to . '"';
                    }


                }


                //$results = VDocument::model()->findAllBySql($this->sql_query);
                $dataProvider = new CSqlDataProvider($sql, array('pagination' => array('pageSize' => $limit),));
                // return CJSON::encode($dataProvider->getData()); //$dataProvider->getData()
                //$labels = VDocument::model()->attributeLabels();
                // return CJSON::encode($this->convertDataToTranslateLabelArray($dataProvider->getData(), $labels));
                return json_encode($dataProvider->getData());
            } else
                return null;
        } else
            return CJSON::encode('SQL error!');
    }


    public function convertModelToTranslateLabelArray($models, $labels)
    {
        $all = array();

        foreach ($models as $model) {
            $result = array();

            $attributes = $model->getAttributes();
            foreach ($attributes as $key => $att) {
                // prevodi key
                $label = $labels[$key];
                $result[$label] = $att;
            }
            array_push($all, $result);

        }
        return $all;
    }

    public function convertDataToTranslateLabelArray($models, $labels)
    {
        $all = array();

        foreach ($models as $model) {
            $result = array();

            $attributes = $model;
            foreach ($attributes as $key => $att) {
                // prevodi key
                $label = $labels[$key];
                $result[$label] = $att;
            }
            array_push($all, $result);

        }
        return $all;
    }


    /**
     * @return string
     * generiše JSON na osnovu rezultata sql upita
     */
    public function vratiDataProvider($limit = 100000)
    {
        if ($this->isValidSQL()) {
            if ($this->sql_upit) {

                $list = Yii::app()->db->createCommand($this->sql_upit)->queryAll();

                return CJSON::encode($list); //$dataProvider->getData()
            } else
                return null;
        } else
            return CJSON::encode('SQL nije ispravan');
    }

    public function rules()
    {
        return array(
            array('name, sql_query', 'required'),
            array('disable_edit, date_range, active, order_number', 'numerical', 'integerOnly' => true),
            array('name,date_field', 'length', 'max' => 100),
            array('sql_query', 'length', 'max' => 2000),
            array('note', 'length', 'max' => 400),
            array('pivot_config, date_from, date_to', 'safe'),
            array('date_field, pivot_config, disable_edit, date_range, date_from, date_to, active, note, order_number', 'default', 'setOnEmpty' => true, 'value' => null),
            array('date_field, report_id, name, sql_query, pivot_config, disable_edit, date_range, date_from, date_to, active, note, order_number', 'safe', 'on' => 'search'),
        );
    }


    /**
     * @param $attribute
     * @param null $params
     */
    public function validSQL($attribute, $params = null)
    {

        if (!$this->returnValidationSQLResult()) {
            $this->addError($attribute, 'SQL upit ima greku!');
        }


    }

    public function isValidSQL()
    {
        try {
            // $sql = Yii::app()->db->createCommand($this->sql_upit)->queryScalar();
            return true;

        } catch (CDbException $e) {

            //return false;
        }
    }

    public function returnValidationSQLResult()
    {
        if ($this->isValidSQL()) {
            return true;
        } else return false;
    }


    public function pivotModels()
    {
        return array();
    }

    public function attributeLabels()
    {
        return array(
            'report_id' => Yii::t('app', 'Izvestaj'),

            'name' => Yii::t('app', 'Ime'),
            'sql_query' => Yii::t('app', 'Sql Query'),
            'pivot_config' => Yii::t('app', 'Pivot Config'),
            'disable_edit' => Yii::t('app', 'Disable Edit'),
            'date_range' => Yii::t('app', 'Date Range'),
            'date_from' => Yii::t('app', 'Datum od'),
            'date_to' => Yii::t('app', 'Datum do'),
            'active' => Yii::t('app', 'Active'),
            'note' => Yii::t('app', 'Napomena'),
            'order_number' => Yii::t('app', 'RB'),
            'date_field' => Yii::t('app', 'kolona za filter datuma'),

        );
    }

    public function search()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('report_id', $this->report_id);

        $criteria->compare('name', $this->name, true);
        $criteria->compare('sql_query', $this->sql_query, true);
        $criteria->compare('pivot_config', $this->pivot_config, true);
        $criteria->compare('disable_edit', $this->disable_edit);
        $criteria->compare('date_range', $this->date_range);
        $criteria->compare('date_from', $this->date_from, true);
        $criteria->compare('date_to', $this->date_to, true);
        $criteria->compare('active', $this->active);
        $criteria->compare('note', $this->note, true);
        $criteria->compare('date_field', $this->date_field, true);
        $criteria->compare('order_number', $this->order_number);


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

    public function defaultPivotConfig()
    {
        return '
        {
        "hiddenAttributes": [],
        "menuLimit": 1000,
        "cols": [ ],
        "rows": [ ],
        "vals": [ ],
        "exclusions": {},
        "inclusions": {},
        "unusedAttrsVertical": 85,
        "autoSortUnusedAttrs": false,
        "exportCSV": true,
        "inclusionsInfo": {},
        "aggregatorName": "Count",
        "rendererName": "Table",
         "renderers": $.extend(
              $.pivotUtilities.renderers,
              $.pivotUtilities.c3_renderers,
              $.pivotUtilities.export_renderers

            )
        }';
    }

    public function pivotConfigRenders()
    {

        $json = $this->pivot_config;
        $json = trim($json, " \t\n\r");

        $config = json_decode($json, true);
        $config['renderers'] = 'extend_code';

        $extend_code = "$.extend(
              $.pivotUtilities.renderers,
              $.pivotUtilities.c3_renderers
            )";

        $config = str_replace('"extend_code"', $extend_code, json_encode($config));


        return $config;
    }

    /**
     * Posle pamcenja kreira i dodelu autoru
     */

    protected function afterSave()
    {


        return parent::afterSave();
    }
}