<?php
/**
 * Created by PhpStorm.
 * User: Peak
 * Date: 3/14/2016
 * Time: 9:53 PM
 */

namespace common\components;
use yii\base\Behavior;
use yii\behaviors\AttributeBehavior;
use yii\db\ActiveRecord;

class DateBehavior extends Behavior
{
    public $date_time_attributes = [];

    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
        ];
    }
    public function init()
    {
        parent::init();

    }

    public function afterFind()
    {
        foreach($this->attributes as $name => $attribute){
            if(preg_match('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/', $attribute)){

                if($attribute == '0000-00-00 00:00:00'){
                    $this->setAttribute($name, null);
                }else{
                    $dt_t = explode('.', $attribute);
                    $dt = explode(' ', $dt_t[0]);
                    if($dt[1] == '00:00:00'){
                        $dt[1] = '';
                    }else{
                        $dt[1] = ' ' . $dt[1];
                    }

                    $data = explode('-', $dt[0]);
                    $y = (int) $data[0];
                    $y = $y + 543;
                    $collect_at = $data[2] . '/' . $data[1] . '/' . $y . $dt[1];
                    $this->setAttribute($name, $collect_at);
                }
            }
            if($name == 'age'){
                if(round($attribute) == $attribute){
                    $this->setAttribute($name, (int) $attribute);
                }
            }
        }

    }

    public function beforeInsert()
    {

        foreach($this->getTableSchema()->columns as $column){
            $name = $column->name;
            $attribute = $this->getAttribute($column->name);

            if(empty($attribute)){
                $column->allowNull == 1 ? $this->setAttribute($name, null) : null;
            }else if($column->dbType == 'datetime2' && preg_match('/(\d{1,2}\s?\/\s?\d{1,2}\s?\/\s?\d{4}\s?\w*)/', $attribute)){
                if(stripos($attribute,':') !== false){
                    $dt = explode(' ', $attribute);
                    $time = ' ' . trim($dt[1]);
                }else{
                    $dt[0] = $attribute;
                    $time = '';
                }

                $data = preg_split('/(\s?\/\s?)/', $dt[0]);
                $y = (int) $data[2];
                $y = $y - 543;
                $collect_at = $y . '-' . $data[1] . '-' . $data[0] . $time;
                $this->setAttribute($name, $collect_at);
            }
        }

    }

   

}