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

require_once __DIR__ . '/../auth.php';

if (!is_admin()) {
    header('Location: ../login.php');
    exit;
}

$config = require __DIR__ . '/../config.php';
$db = db();

/* ---------- speichern ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $slug = trim($_POST['slug'] ?? '');
    $content = $_POST['content'] ?? '';

    if ($slug !== '') {
        $stmt = $db->prepare(
            "INSERT INTO contents (slug, content)
             VALUES (?, ?)
             ON CONFLICT(slug) DO UPDATE SET content = excluded.content"
        );
        $stmt->execute([$slug, $content]);
        $message = "Inhalt gespeichert.";
    }
}

/* ---------- löschen ---------- */
if (isset($_GET['delete'])) {
    $slug = $_GET['delete'];
    $stmt = $db->prepare("DELETE FROM contents WHERE slug = ?");
    $stmt->execute([$slug]);
    $message = "Inhalt '$slug' gelöscht.";
}

/* ---------- laden ---------- */
$rows = $db->query(
    "SELECT slug, content FROM contents ORDER BY slug"
)->fetchAll(PDO::FETCH_ASSOC);

/* ---------- gruppieren ---------- */
$groups = [];
foreach ($rows as $r) {
    if (preg_match('/^([a-zA-Z0-9_-]+?)[0-9_]*$/', $r['slug'], $m)) {
        $prefix = strtolower($m[1]);
    } else {
        $prefix = 'sonstiges';
    }
    $groups[$prefix][] = $r;
}

/* ---------- edit ---------- */
$edit_slug = $_GET['edit'] ?? '';
$edit_content = '';

if ($edit_slug) {
    $stmt = $db->prepare("SELECT content FROM contents WHERE slug = ?");
    $stmt->execute([$edit_slug]);
    $edit_content = $stmt->fetchColumn() ?: '';
}

/* ---------- Tiny ---------- */
$tinyUrl   = $config['TINYMCE'];
$uploadUrl = '../upload_image.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CMS Dashboard</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="<?= htmlspecialchars($tinyUrl) ?>"></script>

<script>
tinymce.init({
  selector:'#content',
  height:600,
  menubar:true,
  promotion:false,
  branding:false,
  language:'de',

  plugins:'link image code lists emoticons media table preview searchreplace visualblocks fullscreen',
  toolbar:[
    'undo redo | fontfamily styleselect fontselect fontsizeinput fontsizeselect bold italic underline | emoticons',
    'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor backcolor',
    'link image media table | preview fullscreen | code | bordercolorbutton'
  ].join(' '),

  relative_urls:false,
  images_upload_url:'<?= $uploadUrl ?>',

  setup:function(editor){
    editor.ui.registry.addButton('bordercolorbutton',{
      text:'🎨 Rahmen',
      onAction:function(){
        const img = editor.selection.getNode();
        if (img.nodeName !== 'IMG') return alert('Bild auswählen');
        const c = document.createElement('input');
        c.type='color'; c.style.position='fixed'; c.style.zIndex=9999;
        document.body.appendChild(c);
        c.oninput=()=>img.style.border='4px solid '+c.value;
        c.onblur=()=>c.remove();
        c.click();
      }
    });
  }
});
</script>
</head>

<body class="bg-light">
<div class="container my-4">

<div class="d-flex justify-content-between align-items-center mb-3">
  <h2>Inhalte verwalten</h2>
  <a href="../logout.php" class="btn btn-danger btn-sm">Logout</a>
  <a href="../admin/media.php" class="btn btn-info btn-sm">Medien</a>
</div>

<?php if (!empty($message)): ?>
<div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="card p-3 mb-4 shadow-sm">
<form method="post">
  <label class="form-label">Slug</label>
  <input name="slug" class="form-control mb-2" required value="<?= htmlspecialchars($edit_slug) ?>">

  <label class="form-label">Inhalt</label>
  <textarea id="content" name="content"><?= htmlspecialchars($edit_content) ?></textarea>

  <button name="save" class="btn btn-primary mt-3">💾 Speichern</button>
  <?php if ($edit_slug): ?>
    <a href="dashboard.php" class="btn btn-secondary mt-3">Abbrechen</a>
  <?php endif; ?>
</form>
</div>

<ul class="nav nav-tabs">
<?php $i=0; foreach ($groups as $g=>$e): ?>
<li class="nav-item">
<button class="nav-link <?= $i===0?'active':'' ?>" data-bs-toggle="tab"
 data-bs-target="#t<?= $i ?>"><?= ucfirst($g) ?> <span class="badge bg-secondary"><?= count($e) ?></span></button>
</li>
<?php $i++; endforeach ?>
</ul>

<div class="tab-content border border-top-0 p-3 bg-white">
<?php $i=0; foreach ($groups as $e): ?>
<div class="tab-pane fade <?= $i===0?'show active':'' ?>" id="t<?= $i ?>">
<table class="table table-bordered">
<tr><th>Slug</th><th>Vorschau</th><th>Aktion</th></tr>
<?php foreach ($e as $r): ?>
<tr>
<td><?= htmlspecialchars($r['slug']) ?></td>
<td><?= htmlspecialchars(mb_strimwidth(strip_tags($r['content']),0,120,'…')) ?></td>
<td>
<a href="?edit=<?= urlencode($r['slug']) ?>" class="btn btn-warning btn-sm">✏️</a>
<a href="?delete=<?= urlencode($r['slug']) ?>" class="btn btn-danger btn-sm"
 onclick="return confirm('Löschen?')">🗑️</a>
</td>
</tr>
<?php endforeach ?>
</table>
</div>
<?php $i++; endforeach ?>
</div>

</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
