<?php

class FavoriteStation 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;
  }


  /**
   * FavoriteStation class destructor
   ** Saves changes to the station favorite 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);
  }


  /**
   * Clone the object by erasing the unique ID, user ID, and set the isChanged flag
   *
   */
  public function __clone()
  {
    $this->_isChanged = true;
    $this->_id = 0;
    $this->userId = 0;
  }


  /**
   * Returns all FavoriteStation settings
   * @return array All currently saves session settings
   */
  public function getAll()
  {
    return $this->_values ?? [];
  }


  /**
   * Set AutoSave
   ** Allows (or prevents) changes to the FavoriteStation 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;
  }


  /**
   * Sets the optional favorite comment.
   ** Ensures it has a maximum length of 100 characters in length,
   ** and contains no invalid characters
   *
   * @param string $comment
   * @return boolean (True if name is acceptable and was set, otherwise false)
   */
  public function setComment($comment)
  {
    // Remove whitespace
    $name = strip_tags(trim($comment));

    // Test the comment and set it if passes
    if (strlen($comment) <= 100)
    {
        $this->comment = $comment;
        $this->_isChanged = true;
        return true;
    }
    else
    {
      $this->_lastError = 'Station comment is too long.  Must be less than 100 characters.';
    }
    return false;
  }


  /**
   * Save the FavoriteStation 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;
    }

    // Make sure all critical properties are completed
    if (is_null($this->userId) || is_null($this->stationId))
    {
      $this->_lastError = 'Cannot save, one or more station favorite settings are missing.';
      return false;
    }

    // Get the site backend database connection
    $pdo = PDOMysqlConnection::getInstance();

    // Inserting or saving?
    if ($this->isExistingObject())
    {
      $sql =
        'UPDATE favorite_stations
          SET
              comment = ?
          WHERE id = ?
          LIMIT 1';
      $stmt = $pdo->prepareAndExec($sql,
        [
          $this->comment,
          $this->_id
        ]);
      if ($stmt)
      {
        $this->_isChanged = false;
        return true;
      }
      $this->_lastError = 'An error occurred saving the station favorite record.';
    }
    else
    {
      $sql =
        'INSERT INTO favorite_stations
          (
           user_id, station_id, comment
          )
          VALUES (?, ?, ?)';

      $stmt = $pdo->prepareAndExec($sql,
        [
          $this->userId, $this->stationId, $this->comment
        ]);
      $id = $pdo->lastInsertId();
      if ($id)
      {
        $this->_id = $id;
        $this->_isChanged = false;
        return true;
      }

      $this->_lastError = 'An error occurred creating the station favorite record.';
    }

    return false;
  }


  /**
   * Delete the FavoriteStation record
   *
   * @return boolean (True if delete was successful, otherwise false)
   */
  public function delete()
  {
    if ($this->isExistingObject())
    {
      // Get the site backend database connection
      $pdo = PDOMysqlConnection::getInstance();

      $sql = 'DELETE FROM favorite_stations WHERE id = ? LIMIT 1';
      $stmt = $pdo->prepareAndExec($sql, [$this->_id]);
      if ($stmt)
      {
        return true;
      }
      $this->_lastError = 'An error occurred deleting the favorite station record.';
    }
  }


  /**
   * Returns the last error message set during a user 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;
  }
}
