<?php
// ทำให้รันได้ทั้งแบบ include ผ่าน index และเปิดตรง
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($conn)) { @include_once __DIR__ . "/connect.php"; }

// รับหมวดจาก query
$type = isset($_GET['type']) ? $_GET['type'] : 'all';
$valid = ['all','pr','teacher','student','procurement'];
if (!in_array($type, $valid, true)) { $type = 'all'; }

// helper สำหรับ active class ของแท็บ
function activeClass($t, $type) { return $t === $type ? 'active' : ''; }

// ดึงข่าวทั้งหมด (ไม่เปลี่ยน schema)
$sql = "SELECT news.*, user.fullname FROM news JOIN user ON news.uid=user.uid ORDER BY news.nid DESC";
$result = $conn->query($sql);

$rows = [];
if ($result && $result->num_rows > 0) {
  while ($r = $result->fetch_assoc()) { $rows[] = $r; }
}

// จัดหมวดด้วยคีย์เวิร์ด (ไทย/อังกฤษ) โดยไม่เพิ่มคอลัมน์
function detect_type($title, $body) {
  $txt = mb_strtolower($title . " " . $body, 'UTF-8');

  // จัดจ้าง/จัดซื้อ (ให้ความสำคัญก่อน)
  $proc_kw = ['จัดจ้าง','จัดซื้อจัดจ้าง','ประกวดราคา','ebidding','e-bidding','tor','สอบราคา','ราคากลาง','จัดซื้อ'];
  foreach ($proc_kw as $k) {
    if (mb_strpos($txt, mb_strtolower($k,'UTF-8')) !== false) return 'procurement';
  }

  // ข่าวอาจารย์/บุคลากร
  $teacher_kw = ['ครู','อาจารย์','บุคลากร','ข้าราชการครู','ครูผู้สอน'];
  foreach ($teacher_kw as $k) {
    if (mb_strpos($txt, mb_strtolower($k,'UTF-8')) !== false) return 'teacher';
  }

  // ข่าวนักเรียน/นักศึกษา
  $student_kw = ['นักเรียน','นักศึกษา','ผู้เรียน','นักศึกษาฝึกงาน','ชมรม'];
  foreach ($student_kw as $k) {
    if (mb_strpos($txt, mb_strtolower($k,'UTF-8')) !== false) return 'student';
  }

  // ดีฟอลต์ = ข่าวประชาสัมพันธ์
  return 'pr';
}

// กรองตามแท็บที่เลือก
$filtered = [];
foreach ($rows as $r) {
  $t = detect_type($r['headlines'] ?? '', $r['content'] ?? '');
  if ($type === 'all' || $type === $t) {
    $r['_type'] = $t;
    $filtered[] = $r;
  }
}
?>

<br><br><br><br>

<div class="container mt-3">
  <h2>ข่าวประชาสัมพันธ์</h2>

  <!-- แท็บหมวดข่าว -->
  <ul class="nav nav-tabs mt-3">
    <li class="nav-item"><a class="nav-link <?php echo activeClass('all',$type); ?>" href="?page=news&type=all">ทั้งหมด</a></li>
    <li class="nav-item"><a class="nav-link <?php echo activeClass('pr',$type); ?>" href="?page=news&type=pr">ข่าวประชาสัมพันธ์</a></li>
    <li class="nav-item"><a class="nav-link <?php echo activeClass('teacher',$type); ?>" href="?page=news&type=teacher">ข่าวอาจารย์</a></li>
    <li class="nav-item"><a class="nav-link <?php echo activeClass('student',$type); ?>" href="?page=news&type=student">ข่าวนักเรียน</a></li>
    <li class="nav-item"><a class="nav-link <?php echo activeClass('procurement',$type); ?>" href="?page=news&type=procurement">ข่าวการจัดจ้าง</a></li>
  </ul>

  <?php if (!empty($filtered)) { ?>
    <?php if (isset($_SESSION["login"]) && $_SESSION["login"]=="pass" && !empty($_SESSION["uid_login"])) { ?>
      <div class="text-end my-2">
        <a href="?page=news_form" class="btn btn-success btn-sm">+ เพิ่มข่าว</a>
      </div>
    <?php } ?>

    <div class="table-responsive mt-3">
      <table class="table table-striped align-middle">
        <thead class="table-light">
          <tr>
            <th style="width:60px;">ลำดับ</th>
            <th>หัวข้อข่าว</th>
            <th style="width:140px;">หมวด</th>
            <th style="width:160px;">วันที่</th>
            <th style="width:220px;">ผู้เผยแพร่</th>
            <?php if (isset($_SESSION["login"]) && $_SESSION["login"]=="pass" && !empty($_SESSION["uid_login"])) { ?>
            <th style="width:160px;">จัดการ</th>
            <?php } ?>
          </tr>
        </thead>
        <tbody>
        <?php $no=1; foreach ($filtered as $row): ?>
          <tr>
            <td><?php echo $no++; ?></td>
            <td>
              <a href="?page=show&nid=<?php echo (int)$row['nid']; ?>">
                <?php echo htmlspecialchars($row['headlines'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
              </a>
            </td>
            <td>
              <?php
                $label = [
                  'pr' => 'ประชาสัมพันธ์',
                  'teacher' => 'อาจารย์',
                  'student' => 'นักเรียน',
                  'procurement' => 'การจัดจ้าง'
                ][$row['_type']];
                echo $label;
              ?>
            </td>
            <td><?php echo htmlspecialchars(date('d/m/Y H:i', strtotime($row['date_add'] ?? 'now')), ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($row['fullname'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
            <?php if (isset($_SESSION["login"]) && $_SESSION["login"]=="pass" && !empty($_SESSION["uid_login"])) { ?>
            <td>
              <a class="btn btn-warning btn-sm" href="?page=news_edit&nid=<?php echo (int)$row['nid']; ?>">แก้ไข</a>
              <a class="btn btn-danger btn-sm" href="?page=news_delete&nid=<?php echo (int)$row['nid']; ?>" onclick="return confirm('ลบข่าวนี้?');">ลบ</a>
            </td>
            <?php } ?>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php } else { ?>
    <div class="alert alert-info mt-3">ยังไม่พบข่าวในหมวดนี้</div>
    <?php if (isset($_SESSION["login"]) && $_SESSION["login"]=="pass" && !empty($_SESSION["uid_login"])) { ?>
      <a href="?page=news_form" class="btn btn-success btn-sm">+ เพิ่มข่าว</a>
    <?php } ?>
  <?php } ?>

</div>
