<?php

class Language extends Model
{
  private bool $_isChanged = false;
  private bool $_autoSave = true;
  private string $_lastError = '';

  public function __construct($id)
  {
    parent::__construct($id);

    // Critical properties
    $this->_isChanged = false;
  }


  /**
   * Language class destructor
   ** Saves changes to the language record if there are any (and autoSave is not disabled)
   */
  public function __destruct()
  {
    if ($this->_autoSave && $this->_isChanged) $this->save();
  }


  /**
   * Makes it possible to set $object->field
   *
   * @param string $key
   * @param mixed
   */
  public function __set($key, $value)
  {
    $this->_isChanged = true;
    parent::__set($key, $value);
  }


  /**
   * Returns all Language Preferences
   * @param boolean $asJSON - Return results as a JSON string
   * @return array All currently saves session settings
   */
  public function getAll($asJSON = false)
  {
    return $asJSON ? json_encode(($this->_values ?? [])) : ($this->_values ?? []);
  }


  /**
   * Set AutoSave
   ** Allows (or prevents) changes to the language record from being saved to the database at
   ** completion of script execution.  Enabled by default.
   *
   * @param string $autoSave (True if changes are to be saved automatically, otherwise false)
   */
  public function setAutoSave($autoSave)
  {
    $this->_autoSave = $autoSave;
  }


  /**
   * Save the language record if there are any changes pending
   *
   * @return boolean (True if save was successful, otherwise false)
   */
  public function save()
  {
    // Don't save unless something has been changed
    if ($this->_isChanged === false)
    {
      $this->_lastError = 'No changes have been made to save.';
      return false;
    }

    // Do nothing as this is a read only class
    return false;
  }


  /**
   * Delete the language record
   *
   * @return boolean (True if delete was successful, otherwise false)
   */
  public function delete()
  {
    // Do nothing as this is a read only class
    return false;
  }


  /**
   * Returns the last error message set during a language action then
   * sets _lastError to an empty string.
   *
   * @return string (Text of the last recorded error)
   */
  public function getLastError()
  {
    $last_error = $this->_lastError;
    $this->_lastError = '';
    return $last_error;
  }
}
