<?php

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


  /**
   * Announcement 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 set the isChanged flag
   *
   */
  public function __clone()
  {
    $this->_isChanged = true;
    $this->_id = 0;
  }


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


  /**
   * Set AutoSave
   ** Allows (or prevents) changes to the Announcement 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 announcement title.
   ** Ensures it has a maximum length of 100 characters in length,
   ** and contains no invalid characters
   *
   * @param string $content
   * @return boolean (True if name is acceptable and was set, otherwise false)
   */
  public function setTitle($title)
  {
    // Remove whitespace
    $name = trim($title);

    // Test the title to ensure it does not exceed 100 characters
    if (strlen($title) <= 100)  //8k
    {
        $this->title = $title;
        $this->_isChanged = true;
        return true;
    }
    else
    {
      $this->_lastError = 'Title is too long.  Must be less than or equal to 100 characters.';
    }
    return false;
  }


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

    // Test the content to ensure it's at least 100 characters and set it if passes
    if (strlen($comment) <= 8192)  //8k
    {
        $this->comment = $comment;
        $this->_isChanged = true;
        return true;
    }
    else
    {
      $this->_lastError = 'Content is too long.  Must be less than or equal to 8192 characters.';
    }
    return false;
  }


  /**
   * Save the Announcement 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->content))
    {
      $this->_lastError = 'Cannot save, content is missing.';
      return false;
    }

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

    // Inserting or saving?
    if ($this->isExistingObject())
    {
      $sql =
        'UPDATE announcements
          SET
              start_date = ?, end_date = ?, title = ?, content = ?
          WHERE id = ?
          LIMIT 1';
      $stmt = $pdo->prepareAndExec($sql,
        [
          $this->startDate,
          $this->endDate,
          $this->title,
          $this->content,
          $this->_id
        ]);
      if ($stmt)
      {
        $this->_isChanged = false;
        return true;
      }
      $this->_lastError = 'An error occurred saving the announcement record.';
    }
    else
    {
      $sql =
        'INSERT INTO announcements
          (
           start_date, end_date, title, content
          )
          VALUES (?, ?, ?, ?)';

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

      $this->_lastError = 'An error occurred creating anouncement record.';
    }

    return false;
  }


  /**
   * Delete the Announcement 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 announcements WHERE id = ? LIMIT 1';
      $stmt = $pdo->prepareAndExec($sql, [$this->_id]);
      if ($stmt)
      {
        return true;
      }
      $this->_lastError = 'An error occurred deleting the announcement 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;
  }
}
