<?php
$db = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $slug = $_POST['slug'] ?? '';
    $excerpt = $_POST['excerpt'] ?? '';
    $content = $_POST['content'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $category_id = $_POST['category_id'] ?? null;
    $author = $_POST['author'] ?? 'Alpha Genomics';
    $published = isset($_POST['published']) ? true : false;
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        if (!$slug) {
            $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $title));
        }
        if ($category_id === '' || $category_id === null) {
            $category_id = null;
        }

        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE articles SET title=?, slug=?, excerpt=?, content=?, image_url=?, category_id=?, author=?, published=?, updated_at=CURRENT_TIMESTAMP WHERE id=?");
                $stmt->execute([$title, $slug, $excerpt, $content, $image_url, $category_id, $author, $published ? 1 : 0, $id]);
                $message = 'Article updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO articles (title, slug, excerpt, content, image_url, category_id, author, published) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$title, $slug, $excerpt, $content, $image_url, $category_id, $author, $published ? 1 : 0]);
                $message = 'Article added successfully.';
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'duplicate') !== false || strpos($e->getMessage(), '23505') !== false) {
                $message = 'Error: An article with that slug already exists. Please use a different slug.';
            } else {
                $message = 'Database error: ' . htmlspecialchars($e->getMessage());
            }
        }
    }
}

$categories = getArticleCategories();
$articles = $db->query("SELECT a.*, ac.name as category_name FROM articles a LEFT JOIN article_categories ac ON a.category_id = ac.id ORDER BY a.created_at DESC")->fetchAll();
$editArticle = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM articles WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editArticle = $stmt->fetch();
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Manage Articles</h2>
</div>

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

<div class="admin-card">
    <h3><?= $editArticle ? 'Edit Article' : 'Add New Article' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editArticle): ?>
        <input type="hidden" name="id" value="<?= $editArticle['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Title</label>
            <input type="text" name="title" value="<?= htmlspecialchars($editArticle['title'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Slug (URL-friendly name, auto-generated if blank)</label>
            <input type="text" name="slug" value="<?= htmlspecialchars($editArticle['slug'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Excerpt</label>
            <textarea name="excerpt" rows="3"><?= htmlspecialchars($editArticle['excerpt'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Content</label>
            <textarea name="content" rows="8"><?= htmlspecialchars($editArticle['content'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Image URL</label>
            <input type="url" name="image_url" value="<?= htmlspecialchars($editArticle['image_url'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Category</label>
            <select name="category_id">
                <option value="">-- No Category --</option>
                <?php foreach ($categories as $cat): ?>
                <option value="<?= $cat['id'] ?>" <?= ($editArticle['category_id'] ?? '') == $cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Author</label>
            <input type="text" name="author" value="<?= htmlspecialchars($editArticle['author'] ?? 'Alpha Genomics') ?>">
        </div>
        <div class="form-group">
            <label><input type="checkbox" name="published" <?= ($editArticle['published'] ?? true) ? 'checked' : '' ?>> Published</label>
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editArticle ? 'Update' : 'Add' ?> Article</button>
        <?php if ($editArticle): ?>
        <a href="/admin/articles" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Articles</h3>
    <table>
        <thead>
            <tr><th>Image</th><th>Title</th><th>Category</th><th>Published</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($articles as $a): ?>
            <tr>
                <td><img src="<?= htmlspecialchars($a['image_url']) ?>" class="admin-img-preview"></td>
                <td><?= htmlspecialchars($a['title']) ?></td>
                <td><?= htmlspecialchars($a['category_name'] ?? 'Uncategorized') ?></td>
                <td><?= $a['published'] ? 'Yes' : 'No' ?></td>
                <td class="actions">
                    <a href="/admin/articles?edit=<?= $a['id'] ?>" class="btn-sm btn-sm-primary">Edit</a>
                    <form method="post" action="/admin/delete" style="display:inline" onsubmit="return confirm('Are you sure?')"><input type="hidden" name="type" value="articles"><input type="hidden" name="delete_id" value="<?= $a['id'] ?>"><?= csrfField() ?><button type="submit" class="btn-sm btn-sm-danger">Delete</button></form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
