<?
require_once("../mobile_base.php");

// チームIDの取得
$teamID = checkTeamId();

// チーム名取得
$teamNameResult = pg_query_params($conn, "SELECT tmname FROM teammt WHERE delkn = FALSE AND teamid = $1", array($teamID));
if ($teamNameResult && pg_num_rows($teamNameResult) == 1) {
    $teamNameArray = pg_fetch_array($teamNameResult, 0);
    $teamName = $teamNameArray[0];
}

$pageTitle = "新着情報";

// 1ページに表示する記事数
$perPage = 5;

// 現在ページ 取得、設定 $currentPage
if (isset($_POST["page"])) {
    $currentPage = $_POST["page"];
} else if (isset($_GET["page"])) {
    $currentPage = $_GET["page"];
} else {
    $currentPage = 1;
}
if (!(is_numeric($currentPage) && $currentPage >= 1)) {
    $currentPage = 1;
}

// 検索結果を何行目から取得するか
$offset = ($currentPage - 1) * $perPage;

// 総件数
$totalCountResult = pg_query_params($conn, "SELECT COUNT(*) FROM latestnews WHERE delkn = FALSE AND teamid = $1", array($teamID));
if ($totalCountResult && pg_num_rows($totalCountResult) == 1) {
    $totalCountArray = pg_fetch_array($totalCountResult, 0);
    $totalCount = $totalCountArray[0];
} else {
    $totalCount = 0;
}

// 総ページ数
$totalPages = floor($totalCount / $perPage);
$totalPages += ($totalCount % $perPage != 0) ? 1 : 0;

// 現在ページ分のレコード取得
$sql = <<<EOD
SELECT
    newstitle
    , newscontent
    , to_char(entrydt, 'YYYY年MM月DD日') AS entrydt_str_ja
  FROM
    latestnews
  WHERE
    delkn = FALSE
    AND teamid = $1
  ORDER BY
    entrydt DESC
    , COALESCE(modidt, regidt) DESC
  OFFSET $2 LIMIT $3
EOD;

$newsRowsResult = pg_query_params($conn, $sql, array($teamID, $offset, $perPage));
if ($newsRowsResult && pg_num_rows($newsRowsResult) > 0) {
    $newsRows = pg_fetch_all($newsRowsResult);
} else {
    $newsRows = array();
}

?>
<?=getHtmlHeader($teamName)?>

<div align="center"><br><font size="+1" color="#666666"><?=h($teamName)?></font><br><br></div>

<hr noshade size="1">

<div align="center"><font size="-1" color="#666666"><?=h($pageTitle)?></font></div>
<hr noshade size="1">

<font size="-1">0.<a href="index.php?t=<?=$teamID?>" accesskey="0">トップページ</a></font><br>
<hr noshade size="1">

<div>
<?foreach ($newsRows as $row) {?>
    <?=h($row["entrydt_str_ja"])?><br>
    <?=h($row["newstitle"])?><br><br>
    <?=nl2br(h($row["newscontent"]))?><br>
    <hr noshade size="1">
<?}?>
</div>

<?if ($currentPage < $totalPages) {?>
    <font size="-1">1.<a href="news.php?t=<?=$teamID?>&page=<?=h($currentPage + 1)?>" accesskey="1">次のページ</a></font><br>
<?}?>
<?if ($currentPage != 1) {?>
    <font size="-1">2.<a href="news.php?t=<?=$teamID?>&page=<?=h($currentPage - 1)?>" accesskey="2">前のページ</a></font><br>
<?}?>
<br>

<font size="-1">0.<a href="index.php?t=<?=$teamID?>" accesskey="0">トップページ</a></font><br>

<?=getHtmlFooter()?>
<?outputBuffer();?>
