<?php

// =============
// Journal Class
// =============

class Journal extends Base {

  // Variables.

  private $current_user_id    = "";
  private $current_user_name  = "";
  private $current_user_email = "";
  
  private $pagination_page    = 1;
  private $pagination_size    = 20;

  // ==================
  // Class Constructor.
  // ==================
   
  public function __construct() {
    
    set_error_handler(array($this, "displayError"));
    
    date_default_timezone_set(self::TIMEZONE);
     
    $this->current_user_id    = $_SESSION[self::USER_ID]    ?? "";
    $this->current_user_name  = $_SESSION[self::USER_NAME]  ?? "";
    $this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
    
    $this->pagination_page    = $_SESSION[self::PAGINATION_PAGE] ?? 1;
    
  }
  
  // =================
  // Clear the Journal
  // =================

  public function clearJournal() {
 
    $SQL = "truncate journal";
    
    $this->executeSQL($SQL);
    
    $this->journalEntry("Journal was Cleared.");
    
  }

  // =======================
  // Return a Journal Object
  // =======================
  
  public function getJournal($limit = 500) {

    $SQL = "select journal.*,
                   date_format(journal.journal_timestamp, '%Y-%m-%d %h:%i %p') as journal_timestamp_verbose
              from journal
          order by journal.journal_timestamp desc
             limit {$limit}";
    
    return $this->getTable("journal", $SQL);
    
  }

  // ============================
  // Return a Journal Page Object
  // ============================
  
  public function getJournalPage() {

    // Find Criteria
    
    $find_journal = filter_input(INPUT_POST, "find_journal") ?: "";
    $find_words   = $this->sanitizeString($find_journal);
    
    // Show Per Page
    
    $this->pagination_size = filter_input(INPUT_POST, "journals_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
    
    // Record Count

    $connection = $this->connect();
    
    $SQL = "select count(*) as count
              from view_journal
             where journal_timestamp       regexp :journal_timestamp
                or journal_origin          regexp :journal_origin
                or journal_ip              regexp :journal_ip
                or journal_entry           regexp :journal_entry";

    $statement = $connection->prepare($SQL);

    $statement->bindValue(":journal_timestamp", $find_words);
    $statement->bindValue(":journal_origin",    $find_words);
    $statement->bindValue(":journal_ip",        $find_words);
    $statement->bindValue(":journal_entry",     $find_words);

    $statement->execute();
    
    $recordset = $statement->fetch(PDO::FETCH_ASSOC);

    $count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;

    // Pagination
    
    $pagination = filter_input(INPUT_POST, "pagination") ?: "";
    
    switch ($pagination) {
      
      case "first"    : $this->pagination_page = 1;                                    break;
      case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1); break;
      case "next"     : $this->pagination_page = ($this->pagination_page + 1);         break;
      case "last"     : $this->pagination_page = ($count / $this->pagination_size);    break;
      
    }
    
    $offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
    $start  = ($offset + 1);
    $end    = min($count, (($start + $this->pagination_size) - 1));

    // Data
    
    $SQL = "select view_journal.*
              from view_journal
             where journal_timestamp       regexp :journal_timestamp
                or journal_origin          regexp :journal_origin
                or journal_ip              regexp :journal_ip
                or journal_entry           regexp :journal_entry
             limit {$this->pagination_size}
            offset {$offset}";

    $statement = $connection->prepare($SQL);

    $statement->bindValue(":journal_timestamp", $find_words);
    $statement->bindValue(":journal_origin",    $find_words);
    $statement->bindValue(":journal_ip",        $find_words);
    $statement->bindValue(":journal_entry",     $find_words);

    $statement->execute();

    $journal = $this->getTableXML("journal", $statement);

    // Insert Pagination Attributes
    
    $journal->addAttribute("count", $count);
    $journal->addAttribute("start", $start);
    $journal->addAttribute("end",   $end);
    $journal->addAttribute("page",  $this->pagination_page);
    
    $_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;

    return $journal;
    
  }

  // ======================
  // Create a Journal Entry
  // ======================
  
  public function journalEntry($journal_entry = "") {

    if (empty($journal_entry)) {
      return;
    }

    $SQL = "insert into journal
      
                      ( journal_origin,
                        journal_ip,
                        journal_entry )

              VALUES ( :journal_origin,
                       :journal_ip,
                       :journal_entry )";

    $statement = $this->connect()->prepare($SQL);

    $statement->bindValue(":journal_origin", $this->current_user_name);
    $statement->bindValue(":journal_ip",     $_SERVER["REMOTE_ADDR"] ?? "");
    $statement->bindValue(":journal_entry",  $journal_entry);

    $statement->execute();
    
  }
  
  // ============
  // View Journal
  // ============
  
  public function viewJournal() {

    $journal  = $this->getJournalPage();
    $popovers = (new Popovers())->getPopovers();
    
    $XML = $this->mergeXML($journal,  "<XML/>");
    $XML = $this->mergeXML($popovers, $XML);

    $content = $this->applyXSL($XML, $this->getXSL("viewJournal"));

    $this->displayContent($content);
    
  }
  
}

?>
