<?php
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../lib/auth.php";
require_once __DIR__ . "/../lib/helpers.php";
require_once __DIR__ . "/../lib/upload.php";
require_once __DIR__ . "/../admin/admin_menu.php";

require_admin();

$uploadDir = __DIR__ . "/../uploads/journal/articles";

$issueId = isset($_GET['issue_id']) ? (int)$_GET['issue_id'] : (int)($_POST['issue_id'] ?? 0);
$editId  = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;

$item = [
  'issue_id'   => $issueId,
  'title'      => '',
  'slug'       => '',
  'image'      => '',
  'body_html'  => '',
  'is_active'  => 1,
  'sort_order' => 0,
];

if ($editId > 0) {
  $st = $pdo->prepare("SELECT * FROM journal_articles WHERE id=? LIMIT 1");
  $st->execute([$editId]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  if ($row) {
    $item = array_merge($item, $row);
    $issueId = (int)($item['issue_id'] ?? $issueId);
  } else {
    die("Məqalə tapılmadı.");
  }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $issueId = (int)($_POST['issue_id'] ?? 0);
  $title   = trim((string)($_POST['title'] ?? ''));
  $slug    = trim((string)($_POST['slug'] ?? ''));
  $body    = (string)($_POST['body_html'] ?? '');
  $active  = isset($_POST['is_active']) ? 1 : 0;
  $sort    = (int)($_POST['sort_order'] ?? 0);

  if ($title === '') die("Başlıq boş ola bilməz.");
  if ($issueId <= 0) die("Issue seçilməyib (issue_id yoxdur).");
  if ($slug === '') $slug = slugify($title);

  $image = upload_image('image', $uploadDir, $item['image'] ?? null);

  if ($editId > 0) {
    $q = $pdo->prepare("UPDATE journal_articles SET issue_id=?, title=?, slug=?, image=?, body_html=?, is_active=?, sort_order=? WHERE id=?");
    $q->execute([$issueId, $title, $slug, $image, $body, $active, $sort, $editId]);
  } else {
    $q = $pdo->prepare("INSERT INTO journal_articles(issue_id, title, slug, image, body_html, is_active, sort_order) VALUES(?,?,?,?,?,?,?)");
    $q->execute([$issueId, $title, $slug, $image, $body, $active, $sort]);
  }

  header("Location: journal_articles.php?issue_id=".$issueId);
  exit;
}

/* Issue list (dropdown üçün) */
$issues = $pdo->query("SELECT id,title FROM journal_issues ORDER BY sort_order ASC, id DESC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
?>
<!doctype html>
<html lang="az">
<head>
  <meta charset="utf-8">
  <title>Məqalə formu</title>
  <style>
    body{font-family:system-ui;margin:20px}
    label{display:block;margin:12px 0 6px}
    input,select,textarea{width:100%;padding:10px;border:1px solid #ccc;border-radius:10px}
    .row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
    .btn{display:inline-block;padding:10px 14px;border:1px solid #111;border-radius:10px;background:#fff;cursor:pointer}
    .thumb{max-width:260px;border-radius:12px;border:1px solid #eee;margin-top:10px}
  </style>
</head>
<body>

<p>
  <a class="btn" href="journal_articles.php?issue_id=<?= (int)$issueId ?>">← Məqalələr</a>
</p>

<h2><?= $editId>0 ? "Məqaləni redaktə" : "Yeni məqalə" ?></h2>

<form method="post" enctype="multipart/form-data">
  <label>Nömrə (issue)</label>
  <select name="issue_id" required>
    <option value="">— seç —</option>
    <?php foreach($issues as $i): ?>
      <option value="<?= (int)$i['id'] ?>" <?= ((int)$i['id']===$issueId ? 'selected' : '') ?>>
        <?= e($i['title']) ?>
      </option>
    <?php endforeach; ?>
  </select>

  <label>Başlıq</label>
  <input name="title" value="<?= e($item['title'] ?? '') ?>" required>

  <label>Slug (boş burax — özü düzəlsin)</label>
  <input name="slug" value="<?= e($item['slug'] ?? '') ?>">

  <label>Şəkil (jpg/png/webp)</label>
  <input type="file" name="image" accept=".jpg,.jpeg,.png,.webp">
  <?php if(!empty($item['image'])): ?>
    <img class="thumb" src="/v2/uploads/journal/articles/<?= e($item['image']) ?>" alt="">
  <?php endif; ?>

  <label>Mətn (HTML)</label>
  <textarea name="body_html" rows="10"><?= e($item['body_html'] ?? '') ?></textarea>

  <div class="row" style="margin-top:10px">
    <div>
      <label>Sort</label>
      <input name="sort_order" value="<?= (int)($item['sort_order'] ?? 0) ?>">
    </div>
    <div style="display:flex;align-items:end;gap:10px">
      <label style="display:flex;gap:10px;align-items:center;margin:0">
        <input type="checkbox" name="is_active" value="1" <?= ((int)($item['is_active'] ?? 1)===1 ? 'checked' : '') ?> style="width:auto">
        Aktiv
      </label>
    </div>
  </div>

  <p style="margin-top:14px">
    <button class="btn" type="submit">Yadda saxla</button>
  </p>
</form>

</body>
</html>