<?php
/**
 * Created by PhpStorm.
 * User: Nikola
 * Date: 2/6/2015
 * Time: 12:12 AM
 */

class DigHistoryMaker extends CActiveRecordBehavior {

    private $owner;

    private $relations;

    public function MakeTireHistory($model){

        $oldGuma = Guma::model()->findByPk($model->id_guma);

        if($oldGuma){
            //$iguma = $this->rutina($oldGuma);

            if($model->attributes != $oldGuma->attributes){
               $model->addhist = true;
            }
        }

    }

    public function MakeUpdateHistory($model){
        $iguma = $this->rutina($model);
        $iguma->status = 'U' ;
        $iguma->save();
    }

    public function MakeDeleteHistory($model){
        $iguma = $this->rutina($model);
        $iguma->status = 'D' ;
        $iguma->save();
    }

    public function MakeInsertHistory($model){

        $iguma = $this->rutina($model);
        $iguma->status = 'I' ;
        $iguma->save();
    }

    public function beforeSave($event){

        $this->MakeTireHistory($this->getOwner());

        return parent::beforeSave($event);
    }

    public function beforeDelete($event){

        $this->MakeDeleteHistory($this->getOwner());

        return parent::beforeDelete($event);
    }

    public function afterSave($event){

        if($this->getOwner()->isNewRecord){
            $this->MakeInsertHistory($this->getOwner());
        }
        if($this->getOwner()->addhist){
            $this->MakeUpdateHistory($this->getOwner());
            $this->getOwner()->addhist = false;
        }

        return parent::afterSave($event);
    }


    /**
     * @param $model
     * @return Iguma
     */
    public function rutina($model)
    {
        $iguma = new Iguma();
        $iguma->attributes = $model->attributes;
        $iguma->id_guma = $model->id_guma;
        return $iguma;
    }

} 