<?php
namespace ProVM\Money;

use ProVM\Common\Alias\Model;
use ProVM\Common\Factory\Model as ModelFactory;

/**
 * @property int $id
 * @property Currency $currency_id
 * @property string $alias
 */
class Alias extends Model {
  public static $_table = 'aliases';

  protected $currency;
  public function currency() {
    if ($this->currency === null) {
      $this->currency = $this->childOf(Currency::class, [Model::SELF_KEY => 'currency_id']);
    }
    return $this->currency;
  }

  protected static $fields = ['currency_id', 'alias'];
  public static function add(ModelFactory $factory, $info) {
    $input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
    $alias = $factory->find(Alias::class)->where([['currency_id', $input['currency_id']], ['alias', $input['alias']]])->one();
    $created = false;
    $result = (object) compact('input', 'alias', 'created');
    if (!$alias) {
      $alias = $factory->create(Alias::class, $input);
      $created = $alias->save();
      $result->created = $created;
    }
    $result->source = $alias->asArray();
    return $result;
  }
  public function edit($info): bool {
    $data = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
    $edited = false;
    foreach ($data as $field => $value) {
      if ($this->{$field} != $value) {
        $this->{$field} = $value;
        $edited = true;
      }
    }
    if ($edited) {
      $edited = $this->save();
    }
    return $edited;
  }
  public function asArray(): array {
    $output = parent::asArray();
    $output['currency'] = $this->currency()->asArray();
    return $output;
  }
}
