<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();
$pageTitle = 'Blog Management';

$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);
$success = $error = '';

// Delete
if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM blog_posts WHERE id=?", [$id]);
  logActivity('admin', $_SESSION['admin_id'], "Deleted blog post #$id");
  header('Location: /admin/blog.php?deleted=1'); exit;
}

// Toggle published
if ($action === 'toggle' && $id) {
  $post = Database::fetchOne("SELECT is_published FROM blog_posts WHERE id=?", [$id]);
  if ($post) {
    $newState = $post['is_published'] ? 0 : 1;
    Database::execute("UPDATE blog_posts SET is_published=?, published_at=? WHERE id=?",
      [$newState, $newState ? date('Y-m-d H:i:s') : null, $id]);
  }
  header('Location: /admin/blog.php'); exit;
}

// Save post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $title    = trim($_POST['title'] ?? '');
  $slug     = trim($_POST['slug'] ?? '');
  $category = trim($_POST['category'] ?? 'General');
  $excerpt  = trim($_POST['excerpt'] ?? '');
  $body     = trim($_POST['body'] ?? '');
  $author   = trim($_POST['author'] ?? 'Rig N Dig Team');
  $tags     = trim($_POST['tags'] ?? '');
  $pub      = isset($_POST['is_published']) ? 1 : 0;

  if (!$title || !$body) {
    $error = 'Title and body are required.';
  } else {
    if (!$slug) $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $title));
    $slug = preg_replace('/[^a-z0-9\-]/', '', strtolower($slug));
    $slug = trim($slug, '-');

    // Handle image upload
    $image = $_POST['existing_image'] ?? null;
    if (!empty($_FILES['image']['tmp_name'])) {
      $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
      if (in_array($ext, ['jpg','jpeg','png','webp'])) {
        $fname = 'blog_' . time() . '_' . rand(100,999) . '.' . $ext;
        move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_PATH . '/' . $fname);
        $image = $fname;
      }
    }

    if ($id) {
      Database::execute("UPDATE blog_posts SET title=?,slug=?,category=?,excerpt=?,body=?,author=?,tags=?,image=?,is_published=?,published_at=? WHERE id=?",
        [$title,$slug,$category,$excerpt,$body,$author,$tags,$image,$pub,$pub ? date('Y-m-d H:i:s') : null,$id]);
      logActivity('admin', $_SESSION['admin_id'], "Updated blog post: $title");
    } else {
      $id = Database::insert("INSERT INTO blog_posts (title,slug,category,excerpt,body,author,tags,image,is_published,published_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
        [$title,$slug,$category,$excerpt,$body,$author,$tags,$image,$pub,$pub ? date('Y-m-d H:i:s') : null]);
      logActivity('admin', $_SESSION['admin_id'], "Created blog post: $title");
    }
    $success = 'Post saved.';
    $action = 'edit';
  }
}

$post = ($action === 'edit' || $action === 'new') && $id ? Database::fetchOne("SELECT * FROM blog_posts WHERE id=?", [$id]) : null;
$posts = $action === 'list' ? Database::fetchAll("SELECT * FROM blog_posts ORDER BY created_at DESC") : [];
require_once __DIR__ . '/includes/header.php';
?>


  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">📝 Blog Posts</h1>
    <a href="?action=new" class="btn-primary text-sm px-4 py-2">+ New Post</a>
  </div>
  <?php if (isset($_GET['deleted'])): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4">Post deleted.</div><?php endif; ?>
  <div class="card-dark overflow-hidden">
    <table class="w-full text-sm">
      <thead class="bg-navy-700 text-xs text-gray-400 uppercase">
        <tr><th class="px-4 py-3 text-left">Title</th><th class="px-4 py-3 text-left">Category</th><th class="px-4 py-3 text-left">Author</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3 text-left">Views</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$posts): ?><tr><td colspan="6" class="px-4 py-8 text-center text-gray-500">No posts yet. <a href="?action=new" class="text-orange-400">Write your first post →</a></td></tr><?php endif; ?>
        <?php foreach ($posts as $p): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3 font-medium"><?= e($p['title']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($p['category']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($p['author']) ?></td>
          <td class="px-4 py-3">
            <a href="?action=toggle&id=<?= $p['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $p['is_published'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>">
              <?= $p['is_published'] ? 'Published' : 'Draft' ?>
            </a>
          </td>
          <td class="px-4 py-3 text-gray-400"><?= number_format($p['views']) ?></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $p['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <?php if ($p['is_published']): ?><a href="/blog-post.php?slug=<?= e($p['slug']) ?>" target="_blank" class="text-xs text-blue-400 hover:underline">View</a><?php endif; ?>
            <a href="?action=delete&id=<?= $p['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Delete this post?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php else: ?>
  <!-- Editor -->
  <div class="flex items-center gap-3 mb-6">
    <a href="/admin/blog.php" class="text-gray-400 hover:text-white text-sm">← All Posts</a>
    <h1 class="text-xl font-bold"><?= $id && $post ? 'Edit Post' : 'New Blog Post' ?></h1>
  </div>
  <?php if ($success): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="bg-red-600/10 border border-red-600/30 text-red-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($error) ?></div><?php endif; ?>

  <form method="POST" enctype="multipart/form-data" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- Main content -->
    <div class="lg:col-span-2 space-y-5">
      <div class="card-dark p-5">
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Post Title *</label>
          <input type="text" name="title" value="<?= e($post['title'] ?? '') ?>" class="input-field" required placeholder="e.g. What is API 6A?">
        </div>
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">URL Slug</label>
          <input type="text" name="slug" value="<?= e($post['slug'] ?? '') ?>" class="input-field" placeholder="auto-generated if empty">
        </div>
        <div>
          <label class="block text-xs text-gray-400 mb-1">Excerpt</label>
          <textarea name="excerpt" rows="2" class="input-field" placeholder="Short description (shown on listing page)"><?= e($post['excerpt'] ?? '') ?></textarea>
        </div>
      </div>
      <div class="card-dark p-5">
        <label class="block text-xs text-gray-400 mb-1">Post Body * (HTML supported)</label>
        <textarea name="body" rows="20" class="input-field font-mono text-xs" placeholder="<h2>Introduction</h2><p>...</p>"><?= e($post['body'] ?? '') ?></textarea>
        <p class="text-xs text-gray-500 mt-1">Use H2/H3 for headings, &lt;ul&gt; for lists, &lt;strong&gt; for bold, &lt;table&gt; for tables.</p>
      </div>
    </div>
    <!-- Sidebar -->
    <div class="space-y-5">
      <div class="card-dark p-5">
        <h3 class="font-semibold text-sm mb-4">Publish Settings</h3>
        <div class="mb-4">
          <label class="flex items-center gap-3 cursor-pointer">
            <input type="checkbox" name="is_published" value="1" <?= !empty($post['is_published']) ? 'checked' : '' ?> class="w-4 h-4 accent-orange-600">
            <span class="text-sm">Published (visible on site)</span>
          </label>
        </div>
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Category</label>
          <input type="text" name="category" value="<?= e($post['category'] ?? 'General') ?>" class="input-field" list="cat-suggestions">
          <datalist id="cat-suggestions">
            <option>API Standards</option><option>Technical</option><option>Sourcing</option>
            <option>Industry News</option><option>Products</option><option>General</option>
          </datalist>
        </div>
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Author</label>
          <input type="text" name="author" value="<?= e($post['author'] ?? 'Rig N Dig Team') ?>" class="input-field">
        </div>
        <div>
          <label class="block text-xs text-gray-400 mb-1">Tags (comma separated)</label>
          <input type="text" name="tags" value="<?= e($post['tags'] ?? '') ?>" class="input-field" placeholder="API 6A, valves, flanges">
        </div>
      </div>
      <div class="card-dark p-5">
        <label class="block text-xs text-gray-400 mb-2">Feature Image</label>
        <?php if (!empty($post['image'])): ?>
        <img src="/uploads/<?= e($post['image']) ?>" class="w-full h-32 object-cover rounded-lg mb-2">
        <input type="hidden" name="existing_image" value="<?= e($post['image']) ?>">
        <?php endif; ?>
        <input type="file" name="image" accept="image/*" class="text-sm text-gray-400">
      </div>
      <div class="flex gap-3">
        <button type="submit" class="btn-primary flex-1 py-2.5">Save Post</button>
        <a href="/admin/blog.php" class="btn-outline px-4 py-2.5">Cancel</a>
      </div>
    </div>
  </form>
  <?php endif; ?>

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