<?php
namespace Incoviba\common;

use Carbon\Carbon;
use Incoviba\Common\Alias\OldModel as Model;

/**
 * @property int $id
 * @property User $user
 * @property string $action
 * @property string $time
 */
class Registry extends Model
{
  public static $_table = 'registries';

  public function user()
  {
    return $this->belongsTo(User::class, 'user')->findOne();
  }
  protected $model;
  public function model()
  {
    if ($this->model == null) {
      list($model, $actions) = explode(']', $this->action);
      $model = str_replace(['Incoviba\\old\\', 'Incoviba\\nuevo\\', '\\'], ['', '', '->'], trim($model, '['));
      $this->model = $model;
    }
    return $this->model;
  }
  protected $actions;
  public function actions()
  {
    if ($this->actions == null) {
      list($model, $actions) = explode(']', $this->action);
      $actions = explode(', ', trim($actions));
      $resultados = [];
      foreach ($actions as $action) {
        if (strpos($action, ': ') !== false) {
          list($columna, $valor) = explode(': ', $action);
        } else {
          $columna = '';
          $valor = $action;
        }
        if (strpos($valor, ' -> ') !== false) {
          list($old, $new) = explode(' -> ', $valor);
        } else {
          $old = '';
          $new = $valor;
        }
        $resultados[$columna] = (object) ['old' => $old, 'new' => $new];
      }
      $this->actions = $resultados;
    }
    return $this->actions;
  }
  public function time(Carbon $time = null)
  {
    if ($time == null) {
      return Carbon::parse($this->time);
    }
    $this->time = $time->toDateTimeString();
  }
}
