<?php
require_once "../../config/settings.inc.php";
define("IEM_APPID", 22);
require_once "../../include/myview.php";
$t = new MyView();
require_once "../../include/database.inc.php";
require_once "../../include/forms.php";
$dbconn = iemdb("mesosite");

$id = get_int404("id");
$q = isset($_GET["q"]) ? pg_escape_string($dbconn, xssafe($_GET["q"])) : "";
$tag = isset($_GET['tag']) ? pg_escape_string($dbconn, xssafe($_GET['tag'])) : null;
$content = <<< EOM
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/">Home</a></li>
    <li class="breadcrumb-item active" aria-current="page">News and Notes</li>
  </ol>
</nav>

<h1 class="mb-4">News and Notes</h1>

<div class="card mb-4">
  <div class="card-body">
    <form method="GET" action="news.phtml" name="searchnews" class="row g-3 align-items-end">
      <div class="col-12 col-md-8">
        <label for="search-query" class="form-label">Search Archive</label>
        <input type="text" id="search-query" name="q" value="{$q}" class="form-control" placeholder="Enter search terms...">
      </div>
      <div class="col-12 col-md-4">
        <button type="submit" class="btn btn-primary w-100">Search</button>
      </div>
    </form>
  </div>
</div>
EOM;

if ($id > 0) {
    $stname = iem_pg_prepare($dbconn, "UPDATE news SET views = views + 1
      WHERE id = $1");
    pg_execute($dbconn, $stname, array($id));
    $stname = iem_pg_prepare($dbconn, "SELECT *,
      to_char(entered, 'YYYY-MM-DD HH:MI AM') as webdate
      from news WHERE id = $1");
    $result = pg_execute($dbconn, $stname, array($id));
} else if ($q != "") {
    $stname = iem_pg_prepare($dbconn, "SELECT *,
      to_char(entered, 'YYYY-MM-DD HH:MI AM') as webdate
      from news WHERE (title ~* $1 or body ~* $1)
      ORDER by entered DESC");
    $result = pg_execute($dbconn, $stname, array($q));
} else if (!is_null($tag)) {
    $stname = iem_pg_prepare($dbconn, "SELECT *,
      to_char(entered, 'YYYY-MM-DD HH:MI AM') as webdate
      from news WHERE tags @> Array[$1]::varchar[]
      ORDER by entered DESC");
    $result = pg_execute($dbconn, $stname, array($tag));
} else {
    $q = "SELECT *, to_char(entered, 'YYYY-MM-DD HH:MI AM') as webdate
           from news ORDER by entered DESC LIMIT 1";
    $result = pg_query($dbconn, $q);
    $row = pg_fetch_assoc($result);
    $id = intval($row["id"]);
}
if ($result === false) {
    die405();
}

if (pg_num_rows($result) == 1 && $id > 0) {
    $prev = $id - 1;
    $next = $id + 1;
    $content .= '<nav aria-label="Article navigation" class="mb-3">';
    $content .= '<div class="d-flex justify-content-between">';
    $content .= "<a rel=\"nofollow\" href=\"news.phtml?id=$prev\" class=\"btn btn-outline-primary\">";
    $content .= '<i class="bi bi-arrow-left" aria-hidden="true"></i> Previous Article</a>';
    $content .= "<a rel=\"nofollow\" href=\"news.phtml?id=$next\" class=\"btn btn-outline-primary\">";
    $content .= 'Next Article <i class="bi bi-arrow-right" aria-hidden="true"></i></a>';
    $content .= '</div></nav>';
}

/**
 * Print tags as links to the news.phtml page with the tag as a query parameter.
 * @param string $str Comma-separated list of tags in the format "{tag1,tag2,...}"
 * @return string HTML string with tags as links or "none" if no tags are present
 */
function print_tags($str)
{
    if ($str == "" || is_null($str)) return "none";

    $ar  = explode(",", trim($str, "{}"));
    $s = "";
    foreach ($ar as $k => $v) {
        $s .= sprintf("<a href='news.phtml?tag=%s'>%s</a> ", $v, $v);
    }
    return $s;
}

$title = "News and Notes";
while ($row = pg_fetch_assoc($result)) {
    $id = $row["id"];
    $title = $row["title"];
    $content .= '<article class="card border-success mb-4">';
    $content .= "<header class=\"card-header bg-success text-white d-flex justify-content-between align-items-center\">";
    $content .= "<h2 class=\"h5 mb-0\">" . htmlspecialchars($row["title"]) . "</h2>";
    $content .= "<span class=\"badge bg-light text-dark\" aria-label=\"{$row["views"]} page views\">{$row["views"]} Views</span>";
    $content .= "</header>";
    $content .= "<div class=\"card-body\">";

    // Metadata section
    $content .= '<div class="row g-2 mb-3">';
    $link = sprintf("<a href='news.phtml?id=%s'>ID #%s</a> ", $id, $id);
    $content .= "<div class=\"col-12 col-md-auto\"><span class=\"badge bg-secondary\">Permalink: {$link}</span></div>";
    $content .= "<div class=\"col-12 col-md-auto\"><span class=\"badge bg-secondary\">Date: " . htmlspecialchars($row["webdate"]) . "</span></div>";
    $content .= "<div class=\"col-12 col-md-auto\"><span class=\"badge bg-secondary\">Author: " . htmlspecialchars($row["author"]) . "</span></div>";
    if (!is_null($row["tags"])) {
        $content .= "<div class=\"col-12 col-md-auto\"><span class=\"badge bg-secondary\">Tags: " . print_tags($row["tags"]) . "</span></div>";
    }
    $content .= '</div>';

    if (strlen($row["url"]) > 0) {
        $content .= "<div class=\"alert alert-info mb-3\"><strong>Link:</strong> <a href=\"{$row["url"]}\" target=\"_blank\" rel=\"noopener\">{$row["url"]}</a></div>\n";
    }
    $content .= "<div class=\"content\">{$row["body"]}</div>";
    $content .= "</div>";
    $content .= "</article>";
} // End of for

if (pg_num_rows($result) == 1) {
    $t->title = $title;
} else {
    $t->title = "News and Notes";
}
if (pg_num_rows($result) == 0) {
    $content .= <<<EOM
    <div class="alert alert-danger">No news items were found based on your
    search parameters!
    </div>
EOM;
}
$t->content = $content;
$t->render('single.phtml');
