<?php
// news_list.php

require_once "config.php";

require_once __DIR__ . '/auth_guard.php';


// DEV: show errors (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/* --------------------- JSON API (AJAX) --------------------- */
if (isset($_GET['api'])) {
  header('Content-Type: application/json; charset=utf-8');
  try {
    $action = $_GET['api'];

    if ($action === 'list') {
      $stmt = $conn->query("SELECT id, title, content, COALESCE(`date`, created_at) AS dt FROM news ORDER BY id DESC");
      $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
      echo json_encode(['ok'=>true, 'data'=>$rows]); exit;
    }

    if ($action === 'get') {
      $id = (int)($_GET['id'] ?? 0);
      $stmt = $conn->prepare("SELECT id, title, content, COALESCE(`date`, created_at) AS dt FROM news WHERE id = ?");
      $stmt->execute([$id]);
      $row = $stmt->fetch(PDO::FETCH_ASSOC);
      echo json_encode(['ok'=>true, 'data'=>$row]); exit;
    }

    // Read JSON body for create/update/delete
    $body = json_decode(file_get_contents('php://input'), true) ?? [];

    if ($action === 'create') {
      $title = trim($body['title'] ?? '');
      $content = trim($body['content'] ?? '');
      if ($title === '' || $content === '') {
        throw new Exception("Title and Content are required.");
      }
      $stmt = $conn->prepare("INSERT INTO news (title, content, `date`) VALUES (?, ?, NOW())");
      $stmt->execute([$title, $content]);
      $id = (int)$conn->lastInsertId();
      $stmt = $conn->prepare("SELECT id, title, content, COALESCE(`date`, created_at) AS dt FROM news WHERE id = ?");
      $stmt->execute([$id]);
      $row = $stmt->fetch(PDO::FETCH_ASSOC);
      echo json_encode(['ok'=>true, 'data'=>$row]); exit;
    }

    if ($action === 'update') {
      $id = (int)($body['id'] ?? 0);
      $title = trim($body['title'] ?? '');
      $content = trim($body['content'] ?? '');
      if (!$id) throw new Exception("Invalid ID.");
      if ($title === '' || $content === '') throw new Exception("Title and Content are required.");
      $stmt = $conn->prepare("UPDATE news SET title = ?, content = ? WHERE id = ?");
      $stmt->execute([$title, $content, $id]);
      $stmt = $conn->prepare("SELECT id, title, content, COALESCE(`date`, created_at) AS dt FROM news WHERE id = ?");
      $stmt->execute([$id]);
      $row = $stmt->fetch(PDO::FETCH_ASSOC);
      echo json_encode(['ok'=>true, 'data'=>$row]); exit;
    }

    if ($action === 'delete') {
      $id = (int)($body['id'] ?? 0);
      if (!$id) throw new Exception("Invalid ID.");
      $stmt = $conn->prepare("DELETE FROM news WHERE id = ?");
      $stmt->execute([$id]);
      echo json_encode(['ok'=>true]); exit;
    }

    echo json_encode(['ok'=>false, 'error'=>'Unknown action']); exit;

  } catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(['ok'=>false, 'error'=>$e->getMessage()]); exit;
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>News List</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    .btn-sm{ padding:.25rem .5rem; font-size:.75rem; line-height:1rem; border-radius:.375rem; }
    .modal{ position:fixed; inset:0; display:none; align-items:center; justify-content:center; background:rgba(0,0,0,.5); padding:1rem; z-index:50; }
    .modal.show{ display:flex; }
  </style>
</head>
<body class="bg-gray-100">
<?php include "header.php"; ?>

<div class="flex flex-col md:flex-row min-h-screen">
  <!-- Sidebar -->
  <div class="min-h-screen bg-gray-100 md:pl-64">
    <?php include "side_bar.php"; ?>

    <!-- Main -->
    <main class="px-4 sm:px-6 py-6">
      <div class="container mx-auto bg-white p-4 md:p-6 shadow-lg rounded-lg">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-xl md:text-2xl font-bold text-gray-700">News List</h2>
          <button onclick="openCreate()" class="px-4 py-2 bg-[#CD7F32] text-white rounded-md hover:bg-blue-700">Add News</button>
        </div>

        <div class="overflow-x-auto">
          <table class="min-w-full border-collapse border border-gray-200" id="data-table">
            <thead class="bg-[#CD7F32] text-white">
              <tr>
                <th class="p-2 md:p-3 border text-left text-sm md:text-base">Serial No.</th>
                <th class="p-2 md:p-3 border text-left text-sm md:text-base">Title</th>
                <th class="p-2 md:p-3 border text-left text-sm md:text-base">Content</th>
                <th class="p-2 md:p-3 border text-left text-sm md:text-base">Date</th>
                <th class="p-2 md:p-3 border text-left text-sm md:text-base">Action</th>
              </tr>
            </thead>
            <tbody id="news-table-body">
              <!-- filled by JS -->
            </tbody>
          </table>
        </div>
      </div>
    </main>
  </div>
</div>

<?php include "footer.php"; ?>

<!-- Add/Edit Modal -->
<div id="edit-modal" class="modal">
  <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-md">
    <h3 id="edit-modal-title" class="text-lg md:text-xl font-semibold mb-4">Add News</h3>
    <form id="edit-form">
      <input type="hidden" id="news_id">
      <div class="mb-3">
        <label class="block text-sm font-medium text-gray-700">Title</label>
        <input type="text" id="title" class="w-full p-2 border border-gray-300 rounded-md" required>
      </div>
      <div class="mb-4">
        <label class="block text-sm font-medium text-gray-700">Content</label>
        <textarea id="content" rows="4" class="w-full p-2 border border-gray-300 rounded-md" required></textarea>
      </div>
      <div class="flex justify-end gap-2">
        <button type="button" onclick="closeEdit()" class="px-3 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600">Cancel</button>
        <button type="submit" class="px-3 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700" id="save-btn">Save</button>
      </div>
    </form>
  </div>
</div>

<!-- View Modal -->
<div id="view-modal" class="modal">
  <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-md">
    <h3 class="text-lg md:text-xl font-semibold mb-2" id="view-title"></h3>
    <div class="text-sm text-gray-500 mb-3" id="view-date"></div>
    <div class="text-gray-800 whitespace-pre-wrap" id="view-content"></div>
    <div class="mt-4 flex justify-end">
      <button type="button" onclick="closeView()" class="px-3 py-2 bg-gray-700 text-white rounded-md hover:bg-gray-800">Close</button>
    </div>
  </div>
</div>

<script>
let NEWS = []; // in-memory cache for rendering

function escapeHtml(s){ return (s ?? '').toString().replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m])); }
function fmtDate(dt){
  if (!dt) return '-';
  // Support "YYYY-MM-DD HH:MM:SS"
  const d = new Date(dt.replace(' ', 'T'));
  if (isNaN(d)) return dt;
  return d.toISOString().slice(0,10);
}

async function loadList(){
  const r = await fetch('?api=list');
  const j = await r.json();
  if (!j.ok) { alert(j.error || 'Failed to load'); return; }
  NEWS = j.data || [];
  renderTable();
}

function renderTable(){
  const tb = document.getElementById('news-table-body');
  tb.innerHTML = '';
  if (!NEWS.length) {
    const tr = document.createElement('tr');
    tr.innerHTML = `<td class="p-3 border text-center text-gray-500" colspan="5">No news found.</td>`;
    tb.appendChild(tr);
    return;
  }
  NEWS.forEach((row, idx) => {
    const tr = document.createElement('tr');
    tr.className = 'hover:bg-gray-50';
    tr.innerHTML = `
      <td class="p-2 md:p-3 border">${idx + 1}</td>
      <td class="p-2 md:p-3 border">${escapeHtml(row.title)}</td>
      <td class="p-2 md:p-3 border whitespace-nowrap overflow-hidden text-ellipsis" title="${escapeHtml(row.content)}">
        ${escapeHtml(row.content)}
      </td>
      <td class="p-2 md:p-3 border">${fmtDate(row.dt)}</td>
      <td class="p-2 md:p-3 border">
        <div class="flex flex-wrap gap-1">
          <button class="btn-sm bg-amber-200 hover:bg-amber-300 text-gray-900" onclick="viewNews(${row.id})">View</button>
          <button class="btn-sm bg-yellow-300 hover:bg-yellow-400 text-gray-900" onclick="editNews(${row.id})">Edit</button>
          <button class="btn-sm bg-red-300 hover:bg-red-400 text-gray-900" onclick="deleteNews(${row.id})">Delete</button>
        </div>
      </td>
    `;
    tb.appendChild(tr);
  });
}

/* --------- Modals: open/close helpers --------- */
function openCreate(){
  document.getElementById('edit-modal-title').textContent = 'Add News';
  document.getElementById('news_id').value = '';
  document.getElementById('title').value = '';
  document.getElementById('content').value = '';
  document.getElementById('edit-modal').classList.add('show');
}
function editNews(id){
  const row = NEWS.find(r => r.id == id);
  if (!row) return;
  document.getElementById('edit-modal-title').textContent = 'Edit News';
  document.getElementById('news_id').value = row.id;
  document.getElementById('title').value = row.title;
  document.getElementById('content').value = row.content;
  document.getElementById('edit-modal').classList.add('show');
}
function closeEdit(){ document.getElementById('edit-modal').classList.remove('show'); }

async function viewNews(id){
  const r = await fetch(`?api=get&id=${id}`);
  const j = await r.json();
  if (!j.ok || !j.data) { alert(j.error || 'Failed to fetch'); return; }
  document.getElementById('view-title').textContent = j.data.title || '(Untitled)';
  document.getElementById('view-date').textContent  = fmtDate(j.data.dt);
  document.getElementById('view-content').textContent = j.data.content || '';
  document.getElementById('view-modal').classList.add('show');
}
function closeView(){ document.getElementById('view-modal').classList.remove('show'); }

/* --------- Create/Update --------- */
document.getElementById('edit-form').addEventListener('submit', async function(e){
  e.preventDefault();
  const id = document.getElementById('news_id').value.trim();
  const title = document.getElementById('title').value.trim();
  const content = document.getElementById('content').value.trim();
  if (!title || !content) { alert('Title and Content are required.'); return; }

  const payload = { id: id ? Number(id) : undefined, title, content };
  const api = id ? 'update' : 'create';

  const r = await fetch(`?api=${api}`, {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify(payload)
  });
  const j = await r.json();
  if (!j.ok) { alert(j.error || 'Save failed'); return; }

  if (id) {
    // update in-place
    const ix = NEWS.findIndex(r => r.id == id);
    if (ix >= 0) NEWS[ix] = j.data;
  } else {
    // prepend new
    NEWS.unshift(j.data);
  }
  closeEdit();
  renderTable();
});

/* --------- Delete --------- */
async function deleteNews(id){
  if (!confirm('Delete this news item?')) return;
  const r = await fetch(`?api=delete`, {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify({id})
  });
  const j = await r.json();
  if (!j.ok) { alert(j.error || 'Delete failed'); return; }
  NEWS = NEWS.filter(r => r.id != id);
  renderTable();
}

/* Init */
loadList();
</script>
</body>
</html>
