<?php
session_start();
include '../includes/db.php';
include '../includes/header.php';
include '../includes/nav.php';

if (!isset($_SESSION['user_id']) || $_SESSION['is_admin'] != 1) {
    echo "<div class='container mt-5'><div class='alert alert-danger'>Zugriff verweigert.</div></div>";
    include '../includes/footer.php';
    exit;
}

$meldung = '';

// News löschen
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM news WHERE id = ?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $meldung = "<div class='alert alert-success'>✅ News gelöscht.</div>";
    }
}

// News speichern oder aktualisieren
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $titel = trim($_POST['titel']);
    $inhalt = trim($_POST['inhalt']);
    $highlight = isset($_POST['highlight']) ? 1 : 0;
    $verfasser = $_SESSION['user_vorname'] . ' ' . $_SESSION['user_nachname'];
    $kategorie = $_POST['kategorie'] ?? '';
    $versionnr = trim($_POST['versionnr'] ?? '');
    $news_id = isset($_POST['news_id']) ? (int)$_POST['news_id'] : 0;

    // Datei-Uploads
    $bildname = $_POST['bild_alt'] ?? null;
    $pdfname = $_POST['pdf_alt'] ?? null;

    if (!empty($_FILES['bild']['name'])) {
        $ext = pathinfo($_FILES['bild']['name'], PATHINFO_EXTENSION);
        $bildname = uniqid('news_') . '.' . $ext;
        move_uploaded_file($_FILES['bild']['tmp_name'], "../uploads/news_bilder/$bildname");
    }

    if (!empty($_FILES['dokument']['name'])) {
        $ext = pathinfo($_FILES['dokument']['name'], PATHINFO_EXTENSION);
        $pdfname = uniqid('doc_') . '.' . $ext;
        move_uploaded_file($_FILES['dokument']['tmp_name'], "../uploads/news_dokumente/$pdfname");
    }

    // Automatische Versionierung bei "Update"
    if ($kategorie === 'Update' && !$versionnr) {
        $stmt = $conn->prepare("SELECT versionnr FROM news WHERE kategorie = 'Update' AND versionnr != '' ORDER BY erstellt_am DESC LIMIT 1");
        $stmt->execute();
        $res = $stmt->get_result();
        $letzte = $res->fetch_assoc()['versionnr'] ?? '1.0';

        if (preg_match('/^(\d+)\.(\d+)$/', $letzte, $matches)) {
            $major = $matches[1];
            $minor = $matches[2] + 1;
            $versionnr = $major . '.' . $minor;
        } else {
            $versionnr = '1.0';
        }
    }

    if ($titel && $inhalt && $kategorie) {
        if ($news_id > 0) {
            $stmt = $conn->prepare("UPDATE news SET titel=?, inhalt=?, highlight=?, bild=?, dokument=?, verfasser=?, kategorie=?, versionnr=? WHERE id=?");
            $stmt->bind_param("ssisssssi", $titel, $inhalt, $highlight, $bildname, $pdfname, $verfasser, $kategorie, $versionnr, $news_id);
        } else {
            $stmt = $conn->prepare("INSERT INTO news (titel, inhalt, highlight, bild, dokument, verfasser, kategorie, versionnr) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssisssss", $titel, $inhalt, $highlight, $bildname, $pdfname, $verfasser, $kategorie, $versionnr);
        }

        if ($stmt->execute()) {
            $meldung = "<div class='alert alert-success'>✅ News erfolgreich gespeichert.</div>";
            include '../mail/mail_news.php';
        } else {
            $meldung = "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
        }
    } else {
        $meldung = "<div class='alert alert-warning'>Bitte alle Pflichtfelder ausfüllen.</div>";
    }
}

// Bestehende News laden
$bearbeiten = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $conn->prepare("SELECT * FROM news WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $bearbeiten = $stmt->get_result()->fetch_assoc();
}
?>

<div class="container my-5">
  <h2 class="mb-4">📰 News & Infos verwalten</h2>
  <?= $meldung ?>

  <form method="post" enctype="multipart/form-data" class="card p-4 bg-white shadow-sm mb-4">
    <input type="hidden" name="news_id" value="<?= $bearbeiten['id'] ?? '' ?>">
    <input type="hidden" name="bild_alt" value="<?= $bearbeiten['bild'] ?? '' ?>">
    <input type="hidden" name="pdf_alt" value="<?= $bearbeiten['dokument'] ?? '' ?>">

    <div class="mb-3">
      <label class="form-label">Titel</label>
      <input type="text" name="titel" class="form-control" value="<?= htmlspecialchars($bearbeiten['titel'] ?? '') ?>" required>
    </div>

    <div class="mb-3">
      <label class="form-label">Inhalt</label>
      <textarea name="inhalt" class="form-control" rows="5" required><?= htmlspecialchars($bearbeiten['inhalt'] ?? '') ?></textarea>
    </div>

    <div class="mb-3">
      <label class="form-label">Kategorie</label>
      <select name="kategorie" class="form-select" id="kategorie" required>
        <option value="">– bitte wählen –</option>
        <?php
        $kategorien = ['Allgemein', 'Technik', 'PSA', 'Lager', 'Wartung', 'Info', 'Update'];
        foreach ($kategorien as $kat):
        ?>
          <option <?= ($bearbeiten['kategorie'] ?? '') == $kat ? 'selected' : '' ?>><?= $kat ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="mb-3">
      <label class="form-label">Versionsnummer</label>
      <input type="text" name="versionnr" id="versionnr" class="form-control"
             value="<?= htmlspecialchars($bearbeiten['versionnr'] ?? '') ?>"
             placeholder="z. B. 1.0">
    </div>

    <div class="mb-3">
      <label class="form-label">Bild (optional)</label>
      <input type="file" name="bild" accept="image/*" class="form-control">
    </div>

    <div class="mb-3">
      <label class="form-label">PDF (optional)</label>
      <input type="file" name="dokument" accept=".pdf" class="form-control">
    </div>

    <div class="form-check mb-3">
      <input class="form-check-input" type="checkbox" name="highlight" id="highlight" <?= isset($bearbeiten['highlight']) && $bearbeiten['highlight'] ? 'checked' : '' ?>>
      <label class="form-check-label" for="highlight">Highlight (wird besonders hervorgehoben)</label>
    </div>

    <button type="submit" name="submit_news" class="btn btn-primary">Speichern</button>
    <?php if ($bearbeiten): ?>
      <a href="news_admin.php" class="btn btn-secondary">Abbrechen</a>
    <?php endif; ?>
  </form>

  <hr>

  <h4 class="mb-3">🗂 Alle News</h4>
  <table class="table table-bordered table-hover bg-white">
    <thead class="table-light">
      <tr>
        <th>Titel</th>
        <th>Kategorie</th>
        <th>Version</th>
        <th>Verfasser</th>
        <th>Datum</th>
        <th>Aktionen</th>
      </tr>
    </thead>
    <tbody>
      <?php
      $result = $conn->query("SELECT * FROM news ORDER BY erstellt_am DESC");
      while ($n = $result->fetch_assoc()):
      ?>
      <tr>
        <td><?= htmlspecialchars($n['titel']) ?></td>
        <td><?= htmlspecialchars($n['kategorie']) ?></td>
        <td><?= htmlspecialchars($n['versionnr']) ?></td>
        <td><?= htmlspecialchars($n['verfasser']) ?></td>
        <td><?= date("d.m.Y H:i", strtotime($n['erstellt_am'])) ?></td>
        <td>
          <a href="?edit=<?= $n['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>
          <a href="?delete=<?= $n['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Wirklich löschen?')">Löschen</a>
        </td>
      </tr>
      <?php endwhile; ?>
    </tbody>
  </table>
</div>

<script>
document.getElementById('kategorie').addEventListener('change', function () {
  if (this.value === 'Update' && document.getElementById('versionnr').value.trim() === '') {
    fetch('get_latest_version.php')
      .then(r => r.text())
      .then(v => {
        const [major, minor] = v.trim().split('.');
        const next = major + '.' + (parseInt(minor) + 1);
        document.getElementById('versionnr').value = next;
      });
  }
});
</script>

<?php include '../includes/footer.php'; ?>
