<?php
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../lib/auth.php";
require_once __DIR__ . "/../lib/helpers.php";
require_once __DIR__ . "/../admin/admin_menu.php";
require_admin();

$issues = $pdo->query("SELECT id,title FROM journal_issues ORDER BY sort_order ASC, id DESC")->fetchAll();
$issueId = isset($_GET['issue_id']) ? (int)$_GET['issue_id'] : (int)($issues[0]['id'] ?? 0);

if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  if ($id>0) $pdo->prepare("DELETE FROM journal_articles WHERE id=?")->execute([$id]);
  header("Location: journal_articles.php?issue_id=".$issueId); exit;
}

$rows = [];
if ($issueId>0){
  $st=$pdo->prepare("SELECT id,title,slug,is_active,sort_order FROM journal_articles WHERE issue_id=? ORDER BY sort_order ASC, id DESC");
  $st->execute([$issueId]);
  $rows = $st->fetchAll() ?: [];
}
?>
<h2>Online Jurnal — Məqalələr</h2>

<form method="get" style="margin-bottom:10px">
  <select name="issue_id" onchange="this.form.submit()">
    <?php foreach($issues as $i): ?>
      <option value="<?= (int)$i['id'] ?>" <?= ((int)$i['id']===$issueId?'selected':'') ?>>
        <?= e($i['title']) ?>
      </option>
    <?php endforeach; ?>
  </select>
</form>

<p><a href="journal_article_form.php?new=1&issue_id=<?= $issueId ?>">+ Yeni məqalə</a></p>

<table border="1" cellpadding="10">
  <tr><th>Başlıq</th><th>Slug</th><th>Status</th><th></th></tr>
  <?php foreach($rows as $r): ?>
    <tr>
      <td><?= e($r['title']) ?></td>
      <td><?= e($r['slug']) ?></td>
      <td><?= (int)$r['is_active']===1 ? 'Aktiv' : 'Passiv' ?></td>
      <td>
        <a href="journal_article_form.php?edit=<?= (int)$r['id'] ?>&issue_id=<?= $issueId ?>">Redaktə</a> |
        <a href="journal_articles.php?issue_id=<?= $issueId ?>&delete=<?= (int)$r['id'] ?>" onclick="return confirm('Silinsin?')">Sil</a>
      </td>
    </tr>
  <?php endforeach; ?>
</table>