<?php
$page_title = 'Manage News';
require_once 'header.php';

$success = '';
$error = '';

// Handle delete
if (isset($_GET['delete']) && $pdo) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("SELECT image FROM news WHERE id=?");
    $stmt->execute([$id]);
    $item = $stmt->fetch();
    if ($item) {
        $imgPath = __DIR__ . '/../' . $item['image'];
        if ($item['image'] && file_exists($imgPath)) unlink($imgPath);
        $pdo->prepare("DELETE FROM news WHERE id=?")->execute([$id]);
        $success = 'News article deleted.';
    }
}

// Handle add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $id = (int)($_POST['id'] ?? 0);
    $title = sanitize($_POST['title'] ?? '');
    $slug = sanitize($_POST['slug'] ?? '');
    $excerpt = sanitize($_POST['excerpt'] ?? '');
    $body = $_POST['body'] ?? '';
    $status = $_POST['status'] ?? 'published';

    if (!$slug) $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $title));
    $slug = trim($slug, '-');

    $imagePath = $_POST['existing_image'] ?? '';

    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
        $allowed = ['jpg','jpeg','png','gif','webp'];
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowed) && $_FILES['image']['size'] <= UPLOAD_MAX_SIZE) {
            $filename = uniqid('news_') . '.' . $ext;
            $dest = __DIR__ . '/../uploads/news/' . $filename;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
                $imagePath = 'uploads/news/' . $filename;
                if ($_POST['existing_image']) {
                    $old = __DIR__ . '/../' . $_POST['existing_image'];
                    if (file_exists($old)) unlink($old);
                }
            }
        } else {
            $error = 'Invalid image file. Max 2MB, allowed: jpg, png, gif, webp.';
        }
    }

    if (!$error && $title && $slug) {
        if ($id) {
            $stmt = $pdo->prepare("UPDATE news SET title=?, slug=?, excerpt=?, body=?, image=?, status=? WHERE id=?");
            $stmt->execute([$title, $slug, $excerpt, $body, $imagePath, $status, $id]);
            $success = 'Article updated.';
        } else {
            $stmt = $pdo->prepare("INSERT INTO news (title, slug, excerpt, body, image, status) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$title, $slug, $excerpt, $body, $imagePath, $status]);
            $success = 'Article created.';
        }
    } elseif (!$error) {
        $error = 'Title and slug are required.';
    }
}

$articles = [];
if ($pdo) {
    $articles = $pdo->query("SELECT id, title, slug, status, created_at FROM news ORDER BY created_at DESC")->fetchAll();
}

// Get single article for editing
$editItem = null;
if (isset($_GET['edit']) && $pdo) {
    $stmt = $pdo->prepare("SELECT * FROM news WHERE id=?");
    $stmt->execute([(int)$_GET['edit']]);
    $editItem = $stmt->fetch();
}
?>

<h1>Manage News</h1>
<p class="subtitle">Create and manage news articles</p>

<?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?php echo $error; ?></div><?php endif; ?>

<div class="card-admin mb-4">
  <h5 class="fw-bold mb-3"><?php echo $editItem ? 'Edit Article' : 'Add New Article'; ?></h5>
  <form method="post" enctype="multipart/form-data">
    <input type="hidden" name="id" value="<?php echo $editItem['id'] ?? 0; ?>">
    <input type="hidden" name="existing_image" value="<?php echo $editItem['image'] ?? ''; ?>">
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label fw-semibold">Title</label>
        <input type="text" name="title" class="form-control" value="<?php echo $editItem ? htmlspecialchars($editItem['title']) : ''; ?>" required>
      </div>
      <div class="col-md-6">
        <label class="form-label fw-semibold">Slug</label>
        <input type="text" name="slug" class="form-control" value="<?php echo $editItem ? htmlspecialchars($editItem['slug']) : ''; ?>" placeholder="Auto-generated if empty">
      </div>
      <div class="col-12">
        <label class="form-label fw-semibold">Excerpt</label>
        <textarea name="excerpt" class="form-control" rows="2"><?php echo $editItem ? htmlspecialchars($editItem['excerpt']) : ''; ?></textarea>
      </div>
      <div class="col-12">
        <label class="form-label fw-semibold">Body (HTML)</label>
        <textarea name="body" class="form-control" rows="10"><?php echo $editItem ? htmlspecialchars($editItem['body']) : ''; ?></textarea>
      </div>
      <div class="col-md-6">
        <label class="form-label fw-semibold">Image</label>
        <input type="file" name="image" class="form-control" accept="image/*">
        <?php if ($editItem && $editItem['image']): ?>
        <div class="mt-2">
          <img src="../<?php echo htmlspecialchars($editItem['image']); ?>" style="height:60px;border-radius:8px;">
        </div>
        <?php endif; ?>
      </div>
      <div class="col-md-6">
        <label class="form-label fw-semibold">Status</label>
        <select name="status" class="form-select">
          <option value="published" <?php echo ($editItem && $editItem['status'] === 'published') ? 'selected' : ''; ?>>Published</option>
          <option value="draft" <?php echo ($editItem && $editItem['status'] === 'draft') ? 'selected' : ''; ?>>Draft</option>
        </select>
      </div>
      <div class="col-12">
        <button type="submit" name="save" class="btn btn-primary"><?php echo $editItem ? 'Update' : 'Create'; ?> Article</button>
        <?php if ($editItem): ?>
        <a href="news.php" class="btn btn-outline-secondary">Cancel</a>
        <?php endif; ?>
      </div>
    </div>
  </form>
</div>

<div class="card-admin">
  <div class="table-responsive">
    <table class="table table-admin mb-0">
      <thead>
        <tr>
          <th>Title</th>
          <th>Slug</th>
          <th>Status</th>
          <th>Date</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($articles as $a): ?>
        <tr>
          <td><?php echo htmlspecialchars($a['title']); ?></td>
          <td><?php echo htmlspecialchars($a['slug']); ?></td>
          <td><span class="badge bg-<?php echo $a['status'] === 'published' ? 'success' : 'secondary'; ?>"><?php echo $a['status']; ?></span></td>
          <td><?php echo date('j M Y', strtotime($a['created_at'])); ?></td>
          <td>
            <a href="?edit=<?php echo $a['id']; ?>" class="btn btn-sm btn-outline-primary btn-admin">Edit</a>
            <a href="?delete=<?php echo $a['id']; ?>" class="btn btn-sm btn-outline-danger btn-admin" onclick="return confirm('Delete this article?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

  </main>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
