<?php
/*
 * Create lists of links to archived AFOS products based on what the user wants
 */
require_once "../../../config/settings.inc.php";
define("IEM_APPID", 48);
require_once "../../../include/forms.php";
require_once "../../../include/myview.php";
require_once "../../../include/network.php";
require_once "../../../include/mlib.php";
require_once "../../../include/reference.php";

$ARCHIVE_BEGIN = 1983;

$t = new MyView();
$t->iemselect2 = TRUE;
$t->title = "NWS Text Product by Issuing Center by Date";
$t->headextra = '<link rel="stylesheet" href="list.css" />';
$t->jsextra = <<<EOM
<script src="list.module.js?v=2" type="module"></script>
EOM;

// A dance here to get a 4-char and 3-char identifier
$source = get_str404("source", 'DMX', 4);
$pil = get_str404("pil", "AFD", 6);
$by = get_str404("by", "cccc");
$view = get_str404("view", 'grid');
$order = get_str404("order", "asc");

$year = get_int404("year", date("Y"), $minval=$ARCHIVE_BEGIN);
$month = get_int404("month", date("m"));
$day = get_int404("day", date("d"));
$year2 = get_int404("year2", date("Y"), $minval=$ARCHIVE_BEGIN);
$month2 = get_int404("month2", date("m"));
$day2 = get_int404("day2", date("d"));

$pilselect = make_select("pil", $pil, $reference['prodDefinitions'], $jscallback = "",
    $cssclass = "form-select iemselect2",
    $multiple=FALSE,
    $showvalue=TRUE);

$cccc = $source;
$sesource = $source;
if (strlen($source) == 3) {
    $cccc = "K$source";
}
if ((strlen($source) == 4) && (substr($source, 0, 1) == 'K')) {
    $sesource = substr($source, 1, 3);
}

// Belt-suspenders check here
$dt = new DateTime("$year-$month-$day");
$datequeue = array($dt->format("Y-m-d"));

$d2display = "none";
$ariaexpanded = "false"; // ARIA initial collapsed state for date range
$ariahidden = "true"; // ARIA hidden state for end date container

$timeformat = "H:i";
if (isset($_REQUEST['drange'])) {
    $dt2 = new Datetime("$year2-$month2-$day2");
    // Enforce the 10 day limit on range
    if ($dt2->diff($dt)->days > 10) {
        $dt2 = $dt->add(new DateInterval("P10D"));
        $year2 = $dt2->format("Y");
        $month2 = $dt2->format("m");
        $day2 = $dt2->format("d");
    }

    // Loop through all the days in the range from $dt to $dt2
    while (($dt <= $dt2) && sizeof($datequeue) < 10) {
        $datequeue[] = $dt->format("Y-m-d");
        $dt->modify("+1 day");
    }
    $d2display = "block";
    $ariaexpanded = "true";
    $ariahidden = "false";
    $timeformat = "d/H:i";
}

$ar = array(
    "asc" => "Time Ascending",
    "desc" => "Time Descending"
);
if (!array_key_exists($order, $ar)) {
    $order = 'asc';
}
$oselect = make_select("order", $order, $ar);

$table = "";
$atags = "";
$totalcount = 0; // Count rows for ARIA summary

// Loop over dates in the datequeue
$prods = array();
$columns = array();
$params = array();
if ($by == "cccc") {
    $params["cccc"] = $cccc;
} else {
    $params["pil"] = $pil;
}
$antiby = ($by == "cccc") ? "pil": "cccc";
foreach ($datequeue as $dt) {
    $params["date"] = $dt;
    $res = iemws_json("nws/afos/list.json", $params);
    $rows = $res["data"];
    if ($order == "desc") {
        $rows = array_reverse($rows);
    }
    if (is_array($rows)) { $totalcount += count($rows); }
    if (is_null($rows) || sizeof($rows) == 0) {
        $table .= "<h3>No products found for $dt</h3>\n";
        continue;
    }

    if ($view == "prod") {
        foreach ($rows as $row) {
            $ts = strtotime($row["entered"]);
            if (!array_key_exists($row[$antiby], $prods)) {
                $prods[$row[$antiby]] = "";
            }
            $prods[$row[$antiby]] .= sprintf(
                "<tr><td>%s</td><td><a href=\"%s\">%s</a>%s</td><td>%s</td><td>%s</td></tr>",
                $row["cccc"],
                $row["link"],
                $row["pil"],
                ($row["count"] > 1) ? " {$row['count']}x": "",
                gmdate("Y-m-d", $ts),
                gmdate("H:i", $ts)
            );
        }
    } else if ($view == "grid") {
        foreach ($rows as $row) {
            $ts = strtotime($row["entered"]);
            if (!array_key_exists($row[$antiby], $columns)) {
                $columns[$row[$antiby]] = "";
            }
            $columns[$row[$antiby]] .= sprintf(
                "<a href=\"%s\">%s</a> %s@%s<br />",
                $row["link"],
                $row["pil"],
                ($row["count"] > 1) ? "{$row['count']}x": "",
                gmdate($timeformat, $ts)
            );
        }
    } else {
        // Chronological mode: build hour-based columns and rows
        $lasthour = "";
        $colnum = 0;
        $rowopen = false;
        $containeropen = false;
    $atags .= '<div class="clearfix"></div><nav class="mb-3" aria-label="Hour navigation"><strong class="d-block">Skip to Hour:</strong><div class="d-flex flex-wrap gap-1 mt-2">';
        foreach ($rows as $row) {
            $ts = strtotime($row["entered"]);
            if (gmdate("H", $ts) != $lasthour) {
                if ($lasthour != "") {
                    // End previous card/col
                    $table .= "</div></div></div>\n";
                }
                $lasthour = gmdate("H", $ts);
                // Use data-jump attribute; JS adds listener (Rule: no JS embedded in HTML files)
                $atags .= sprintf(
                    "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" data-jump=\"%s\" aria-label=\"Jump to hour %s UTC\">%s</button>",
                    $lasthour,
                    $lasthour,
                    $lasthour
                );
                if ($colnum % 6 == 0) {
                    if ($rowopen) {
                        // End previous row and container
                        $table .= "</div></div>\n";
                        $rowopen = false;
                        $containeropen = false;
                    }
                    $table .= "<div class=\"container\"><div class=\"row mb-3\">\n";
                    $rowopen = true;
                    $containeropen = true;
                }
                $table .= "<div id=\"sect$lasthour\" class=\"col-lg-2 col-md-2 col-sm-2 col-4 mb-2\"><div class=\"card h-100\"><div class=\"card-body\">";
                $table .= sprintf("<strong>%s UTC</strong><br />", gmdate('d M Y : H', $ts));
                $colnum += 1;
            }
            $table .= sprintf(
                "<a href=\"%s\">%s</a> %s@%s<br />",
                $row["link"],
                $row["pil"],
                ($row["count"] > 1) ? "{$row['count']}x": "",
                gmdate("H:i", $ts)
            );
        }
        // Close any open card/col
        $table .= "</div></div></div>\n";
        // Close any open row/container
        if ($rowopen) {
            $table .= "</div></div>\n";
        }
    $atags .= '</div></nav>';
    }
}
if ($view == "prod") {
    $keys = array_keys($prods);
    asort($keys);
    $table .= <<<EOM
<table class="table table-sm table-striped" aria-describedby="resultsSummary">
<caption class="visually-hidden">NWS text products listing</caption>
<thead><tr><th scope="col">Source</th><th scope="col">Product Link</th><th scope="col">Date</th><th scope="col">UTC Time</th></tr></thead>
<tbody>
EOM;
    foreach ($keys as $i => $k) {
        $table .= sprintf("%s", $prods[$k]);
    }
    $table .= "</tbody></table>";
} else if ($view == "grid") {
    ksort($columns);
    $keys = array_keys($columns);
    $table = "";
    $atags .= '<div class="clearfix"></div><nav class="mb-3" aria-label="' . htmlspecialchars($antiby) . ' navigation"><strong class="d-block">Skip to ' . $antiby . ':</strong><div class="d-flex flex-wrap gap-1 mt-2">';
    foreach ($keys as $i => $k) {
        // Use data-jump attribute; JS adds listener (Rule: no JS embedded in HTML files)
        $labelcontext = ($antiby == 'pil') ? 'product' : 'center';
        $atags .= sprintf(
            "<button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" data-jump=\"%s\" aria-label=\"Jump to %s %s\">%s</button>",
            $k,
            $labelcontext,
            $k,
            $k
        );
        if ($i % 6 == 0) {
            if ($i > 0) {
                $table .= "</div>";
            }
            $table .= "<div class=\"row mb-3\">\n";
        }
        $table .= sprintf(
            "<div id=\"sect$k\" class=\"col-lg-2 col-md-2 col-sm-2 col-4 mb-2\"><div class=\"card h-100\"><div class=\"card-body\">%s</div></div></div>\n",
            $columns[$k]
        );
    }
    $table .= "</div>\n";
    $atags .= '</div></nav>';
}

$drangecheck = (isset($_REQUEST["drange"])) ? "checked='checked'" : "";
$groups = array("WFO", "RFC", "NWS", "NCEP", "CWSU", "WSO");
$groupnames = array(
    "Weather Forecast Offices (WFO)",
    "River Forecast Centers (RFC)",
    "NWS Admin Organizations",
    "NCEP Centers",
    "Center Weather Service Units (CWSU)",
    "Weather Service Offices (WSO)",
);
$sources = array();
foreach ($groups as $key => $s) {
    $sources[$groupnames[$key]] = array();
    $nt = new NetworkTable($s);
    foreach ($nt->table as $sid => $tbl) {
        $sources[$groupnames[$key]][$sid] = sprintf(
            "[%s] %s",
            $sid,
            $tbl['name']
        );
    }
}
$netselect = make_select(
    "source",
    $sesource,
    $sources,
    $jscallback = "",
    $cssclass = "form-select iemselect2"
);

$yselect = yearSelect($ARCHIVE_BEGIN, $year, "year");
$mselect = monthSelect($month, "month");
$dselect = daySelect($day, "day");
$y2select = yearSelect($ARCHIVE_BEGIN, $year2, "year2");
$m2select = monthSelect($month2, "month2");
$d2select = daySelect($day2, "day2");

$ar = array(
    "time" => "Chronological",
    "grid" => "Grid",
    "prod" => "Product List"
);
$vselect = make_select("view", $view, $ar, "", "form-select");
$ar2 = array(
    "asc" => "Ascending",
    "desc" => "Descending"
);
$oselect = make_select("order", $order, $ar2, "", "form-select");
$bycccc = ($by == "cccc") ? ' checked="checked"' : "";
$bypil = ($by == "pil") ? ' checked="checked"' : "";


$t->content = <<<EOM
<h3>NWS Text Products by Date and Issuance Center or PIL</h3>
<p>This application prints out a listing of IEM archived text products.
After about
seven days, the IEM purges a lot of the frequently issued products like
SHEF and METAR data. Please be patient with this page if you select a
range of dates.</p>

<p>See this <a href="/onsite/news.phtml?id=1408">news item</a> for more details
on this archive and sources used.  You can also find a listing of
<a href="https://forecast.weather.gov/product_types.php?site=NWS">three character PILs</a>
and a brief associated product name on the NWS website.</p>

<p><strong>Archive Completeness:</strong>
<ul>
 <li><strong>{$ARCHIVE_BEGIN} thru 2001</strong>: Sometimes sparse / missing data.
 Also note that product source IDs
 are likely different back then (prior to NWS Modernization), some work was
 done to assign present day WMO source IDs to the product metadata stored in
 the database. The original text was not modified. To find text from a now
 closed WSO from the period, try using the present day WFO center that covers
 the location.</li>
 <li><strong>2002 thru 2007</strong>: More consistent archives, but still likely
 missing things.  Much better coverage though.</li>
 <li><strong>2008 thru now</strong>: Very good data coverage and higher fidelity
 archiving.</li>
 </ul>
</p>

<p>This data presentation is powered by a <a href="/api/1/docs#/nws/service_nws_afos_list__fmt__get">IEM API Web Service</a>.</p>

<form name="selector" method="GET">
<div class="card">
<div class="card-header">
<h4 class="card-title mb-0">Search Parameters</h4>
</div>
<div class="card-body">
<div class="row">

<div class="col-lg-4 col-md-6 mb-3">
<h5>Search Method</h5>
<div class="form-check">
<input type="radio" name="by" value="cccc" id="bycccc" class="form-check-input"{$bycccc}>
<label for="bycccc" class="form-check-label">By Center</label>
</div>
<div class="mt-2">
{$netselect}
</div>

<div class="form-check mt-3">
<input type="radio" name="by" value="pil" id="bypil" class="form-check-input"{$bypil}>
<label for="bypil" class="form-check-label">By Product ID</label>
</div>
<div class="mt-2">
{$pilselect}
</div>
</div>

<div class="col-lg-4 col-md-6 mb-3">
<h5>Date Selection</h5>
<label class="form-label fw-bold">For UTC Date:</label>
<div class="d-flex gap-2 mb-3">
{$yselect} {$mselect} {$dselect}
</div>

<div class="form-check">
<input id="drange" type="checkbox" name="drange" value="yes" class="form-check-input" {$drangecheck} aria-controls="d2" aria-expanded="{$ariaexpanded}"/>
<label for="drange" class="form-check-label">List over UTC date range through (max 10 days)</label>
</div>

<div id="d2" class="mt-2" style="display: {$d2display}" aria-hidden="{$ariahidden}">
<label class="form-label">End Date:</label>
<div class="d-flex gap-2">
{$y2select} {$m2select} {$d2select}
</div>
</div>
</div>

<div class="col-lg-4 col-md-12 mb-3">
<h5>Display Options</h5>
<div class="mb-3">
<label class="form-label">How to view:</label>
{$vselect}
</div>

<div class="mb-3">
<label class="form-label">Sort order:</label>
{$oselect}
</div>

<div class="d-grid">
<input type="submit" value="Giveme Giveme!" class="btn btn-primary">
</div>
</div>

</div>
</div>
</div>
</form>
<div id="resultsSummary" class="visually-hidden" aria-live="polite">Loaded {$totalcount} product rows in {$view} view.</div>
{$atags}

{$table}

EOM;

$t->render('full.phtml');
