<?php

/**
 * This is the model class for table "blagajna".
 *
 * The followings are the available columns in table 'blagajna':
 * @property integer    $id
 * @property integer    $user_id
 * @property string     $datum
 * @property integer    $tip_promene
 * @property double     $suma
 * @property string     $komentar
 * @property integer    $vreme
 *
 * The followings are the available model relations:
 * @property Blagajna   $tipPromene
 * @property Blagajna[] $blagajnas
 * @property User       $user
 */
class Blagajna extends CActiveRecord
{


    public $datum_od;
    public $datum_do;

    /**
     * Returns the static model of the specified AR class.
     *
     * @param string $className active record class name.
     *
     * @return Blagajna the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

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

    public function getTippromeneopis()
    {
        $opis = "+";
        if ($this->tipPromene->ulaz_izlaz == 1) {
            $opis = "+";
        } else {
            $opis = "-";
        }

        return $opis . ' ' . $this->tipPromene->naziv;
    }

    public function getZnakpromene()
    {
        $opis = "+";
        if ($this->tipPromene->ulaz_izlaz == 1) {
            $opis = "+";
        } else {
            $opis = "-";
        }

        return $opis;
    }

    /**
     * @return int|mixed
     */
    public function vratiStanje()
    {

        //        $model = Blagajna::model()->findAll();
        //        foreach ($model as $promena) {
        //            if ($promena->tipPromene->ulaz_izlaz == 1) {
        //                $stanje += $promena->suma;
        //            }
        //            if ($promena->tipPromene->ulaz_izlaz == 2) {
        //                $stanje -= $promena->suma;
        //            }
        //
        //        }


        // V1.3
        // prepravljeno na sql kako bi brže radilo
        //        $ulaz = 1; // +
        //        $izlaz = 2; // -
        $sql = "select  sum(if(tip.ulaz_izlaz = 1, bl.suma, -bl.suma)) as stanje from blagajna as bl
                join tippromene as tip on tip.id = bl.tip_promene";

        $stanje = Yii::app()->db->createCommand($sql)->queryScalar();

        return $stanje;

    }

    public function vratiStanjenadan($datum)
    {
        //$datum = date('d-m-Y', strtotime("$datum + 1 day")); // pomera do kraja dana
        $datum = Yii::app()->dateFormatter->format("yyyy-MM-dd", $datum);

        // tip promene
        $ulaz = 1; // +
        $izlaz = 2; // -

        // ulaz na dan
        $sql_ulaz = "
                select sum(suma) as ukupno from blagajna as b
                join tippromene as t on t.id = b.tip_promene
                where t.ulaz_izlaz = $ulaz and b.datum <= '$datum'
        ";

        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql_ulaz);
        $sum_ulaz = $command->queryAll();

        // izlaz na dan
        $sql_izlaz = "
                select sum(suma) as ukupno from blagajna as b
                join tippromene as t on t.id = b.tip_promene
                where t.ulaz_izlaz = $izlaz and b.datum <= '$datum'
        ";

        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql_izlaz);
        $sum_izlaz = $command->queryAll();

        $stanje = $sum_ulaz[0]['ukupno'] - $sum_izlaz[0]['ukupno'];


        return $stanje;

    }


    public function getTotal($records, $column)
    {
        $total = 0;
        foreach ($records as $record) {
            if ($record->znakpromene == '+') {
                $total += $record->$column;
            } else {
                $total -= $record->$column;
            }
        }
        return $total;
    }


    public function korisnikTipUnterval($tip, $user)
    {

        $stanje = 0;

        $model = Blagajna::model()->findAllByAttributes(array('tip_promene' => $tip, 'user_id' => $user));
        foreach ($model as $promena) {
            if ((strtotime($this->datum_od) <= strtotime($promena->datum)) && (strtotime($this->datum_do) >= strtotime($promena->datum))) {
                if ($promena->tipPromene->ulaz_izlaz == 1) {
                    $stanje += $promena->suma;
                }
                if ($promena->tipPromene->ulaz_izlaz == 2) {
                    $stanje -= $promena->suma;
                }
            }
        }
        return $stanje;


    }


    public function poslednjaNedelja()
    {

        $danas = date('d-m-Y');
        $danas = date('d-m-Y', strtotime("$danas -1 day"));
        //  $presedamdana = '1-3-2015';
        $presedamdana = date('d-m-Y', strtotime("$danas -8 day"));
        $dani = $this->dateRange($presedamdana, $danas);

        $lista = array();
        foreach ($dani as $stanjenadan) {
            $lista[$stanjenadan] = $this->vratiStanjenadan($stanjenadan);
        }
        return $lista;

    }
    /**
     * @return array validation rules for model attributes.
     */
    /**
     * @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('user_id, datum, tip_promene, suma', 'required'),
            array('user_id, tip_promene', 'numerical', 'integerOnly' => true),
            array('suma', 'numerical'),
            array('komentar', 'length', 'max' => 200),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id,datum_od,datum_do, user_id, datum, tip_promene, suma, komentar, vreme', '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(
            'tipPromene' => array(self::BELONGS_TO, 'Tippromene', 'tip_promene'),
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        );
    }


    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'user_id' => 'User',
            'datum' => 'Datum',
            'tip_promene' => 'Tip Promene',
            'suma' => 'Iznos',
            'komentar' => 'Komentar',
            'vreme' => 'Vreme',
            'tippromeneopis' => 'Top promene',
            'znakpromene' => 'Znak',
            'datum_od' => 'Datum OD',
            'datum_do' => 'Datum DO'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('user_id', $this->user_id);
        $criteria->compare('datum', $this->datum, true);
        $criteria->compare('tip_promene', $this->tip_promene);
        $criteria->compare('suma', $this->suma);
        $criteria->compare('komentar', $this->komentar, true);
        $criteria->compare('vreme', $this->vreme);

        return new CActiveDataProvider($this, array(
            'pagination' => array(
                'pageSize' => Yii::app()->user->getState('pageSize', 20),
            ),
            'sort' => array('defaultOrder' => ' id DESC'),
            'criteria' => $criteria,
        ));
    }

    protected function beforeSave()
    {

        if ($this->isNewRecord) {
            $this->vreme = new CDbExpression('NOW()');
        } else {
            if ($this->vreme) {
                $this->vreme = Yii::app()->dateFormatter->format("yyyy-MM-dd hh:mm:ss", $this->vreme);
            }
        }

        if ($this->datum) {
            $this->datum = Yii::app()->dateFormatter->format("yyyy-MM-dd", $this->datum);
        }


        return parent::beforeSave();
    }

    protected function afterFind()
    {
        if ($this->datum) {
            $this->datum = Yii::app()->dateFormatter->format("dd-MM-yyyy", $this->datum);
        }

        if ($this->vreme) {
            $this->vreme = Yii::app()->dateFormatter->format("dd-MM-yyyy hh:mm:ss", $this->vreme);
        }

        return parent::afterFind();
    }


    function dateRange($first, $last, $step = '+1 day', $format = 'd-m-Y')
    {

        $dates = array();
        $current = strtotime($first);
        $last = strtotime($last);

        while ($current <= $last) {

            $dates[] = date($format, $current);
            $current = strtotime($step, $current);
        }

        return $dates;
    }
}