<?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/issues";

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

$item = [
  'title'      => '',
  'issue_no'   => '',
  'year'       => '',
  'slug'       => '',
  'cover'      => '',
  'intro_html' => '',
  'is_active'  => 1,
  'sort_order' => 0
];

if ($editId > 0) {
  try {
    $st = $pdo->prepare("SELECT * FROM journal_issues WHERE id=? LIMIT 1");
    $st->execute([$editId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) die("Nömrə tapılmadı.");
    $item = array_merge($item, $row);
  } catch (Throwable $e) {
    die("SELECT xətası: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'));
  }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $title    = trim((string)($_POST['title'] ?? ''));
  $issue_no = trim((string)($_POST['issue_no'] ?? ''));
  $year     = trim((string)($_POST['year'] ?? ''));
  $slug     = trim((string)($_POST['slug'] ?? ''));
  $intro    = (string)($_POST['intro_html'] ?? '');
  $active   = isset($_POST['is_active']) ? 1 : 0;
  $sort     = (int)($_POST['sort_order'] ?? 0);

  if ($title === '' && ($issue_no === '' || $year === '')) {
    die("Başlıq boş ola bilməz (və ya ən azı № və il doldur).");
  }

  if ($slug === '') {
    $base = $title !== '' ? $title : ("jurnal-" . $issue_no . "-" . $year);
    $slug = slugify($base);
  }

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

  try {
    if ($editId > 0) {
      $q = $pdo->prepare("UPDATE journal_issues SET title=?, issue_no=?, year=?, slug=?, cover=?, intro_html=?, is_active=?, sort_order=? WHERE id=?");
      $q->execute([$title,$issue_no,$year,$slug,$cover,$intro,$active,$sort,$editId]);
    } else {
      $q = $pdo->prepare("INSERT INTO journal_issues(title, issue_no, year, slug, cover, intro_html, is_active, sort_order) VALUES(?,?,?,?,?,?,?,?)");
      $q->execute([$title,$issue_no,$year,$slug,$cover,$intro,$active,$sort]);
    }
  } catch (Throwable $e) {
    die("SAVE xətası: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'));
  }

  header("Location: journal_issues.php");
  exit;
}
?>
<!doctype html>
<html lang="az">
<head>
  <meta charset="utf-8">
  <title><?= $editId>0 ? "Jurnal nömrəsi redaktə" : "Yeni jurnal nömrəsi" ?></title>
  <style>
    body{font-family:system-ui;margin:20px}
    label{display:block;margin:12px 0 6px}
    input,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_issues.php">← Nömrələr</a></p>
<h2><?= $editId>0 ? "Nömrəni redaktə et" : "Yeni nömrə" ?></h2>

<form method="post" enctype="multipart/form-data">
  <label>Başlıq</label>
  <input name="title" value="<?= e($item['title'] ?? '') ?>">

  <div class="row">
    <div>
      <label>Nömrə (№)</label>
      <input name="issue_no" value="<?= e($item['issue_no'] ?? '') ?>">
    </div>
    <div>
      <label>İl</label>
      <input name="year" value="<?= e($item['year'] ?? '') ?>">
    </div>
  </div>

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

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

  <label>Giriş mətni (HTML)</label>
  <textarea name="intro_html" rows="7"><?= e($item['intro_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">Yadda saxla</button></p>
</form>

</body>
</html>