<?php

class mfConfig {
  private $db;
  private $id;
  private $name;
  private $value;
  private $active;
  private $type;
  private $me;

  public function __construct($name) {
    $this->db = new FronkDB();

    $name = $this->db->escape($name);
    $this->name = $name;

    $me = new User();
    if(defined("INTERNAL_USER_ID")) {
      $me->id = INTERNAL_USER_ID;
    } else  {
      $me->loadMe();
    }
    $this->me = $me;
    
    $res = $this->db->select("System", "*", "name='$name'");
    if($this->db->num_rows($res)) {
      $data = $this->db->fetch_object($res);
      $this->id = $data->id;
      $this->value = $data->value;
      $this->active = $data->active;
      $this->type = $data->type;
    } else {
      $this->active = 1;
      $this->type = "string";
    }
  }

  public function value($value = null) {
    if($value !== null) {
      $this->value = $value;
    }
    return $this->value;
  }

  public function type($type = null) {
    if($type !== null) {
      $this->type = $type;
    }
    return $this->type;
  }

  public function active($active = null) {
    return $this->active;
  }


  public function save() {
    $id = $this->id;
    
    $values['name'] = $this->name;
    $values['value'] = $this->value;
    $values['active'] = ($this->active === true || $this->active === 1 || $this->active === (string) 1) ? 1 : 0;
    $values['type'] = $this->type;
    $values['edit_by'] = $this->me->id;
    $values['edit'] = date('U');
    
    if($id) {
      // update
      $this->db->update("System", $values, "id=$id");
    } else {
      // insert
      $values['create_by'] = $this->me->id;
      $values['create'] = date('U');
      $id = $this->db->insert("System", $values);
      $this->id = $id;
    }

  }

  public function __toString() {
    return (string) $this->value;
  }
}