<?php
require_once 'config/db.php';
require_once 'includes/header.php';

// Handle Add Tag
if (isset($_POST['add_tag'])) {
    $name = trim($_POST['name']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    
    if (!empty($name)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO blog_tags (name, slug) VALUES (?, ?)");
            $stmt->execute([$name, $slug]);
            $success = "Blog tag added successfully.";
        } catch (PDOException $e) {
            $error = "Error adding tag. Slug might already exist.";
        }
    } else {
        $error = "Tag name cannot be empty.";
    }
}

// Handle Delete Tag
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM blog_tags WHERE id = ?");
        $stmt->execute([$id]);
        $success = "Blog tag deleted successfully.";
    } catch (PDOException $e) {
        $error = "Error deleting tag: " . $e->getMessage();
    }
}

// Handle Update Tag
if (isset($_POST['update_tag'])) {
    $id = (int)$_POST['id'];
    $name = trim($_POST['name']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    
    if (!empty($name)) {
        try {
            $stmt = $pdo->prepare("UPDATE blog_tags SET name=?, slug=? WHERE id=?");
            $stmt->execute([$name, $slug, $id]);
            $success = "Blog tag updated successfully.";
        } catch (PDOException $e) {
            $error = "Error updating tag.";
        }
    }
}

// Fetch all tags
$stmt = $pdo->query("SELECT * FROM blog_tags ORDER BY created_at DESC");
$tags = $stmt->fetchAll();

// Edit Mode Check
$edit_tag = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM blog_tags WHERE id = ?");
    $stmt->execute([$id]);
    $edit_tag = $stmt->fetch();
}
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-tags"></i> Blog Tags</h2>
        <p>Manage the tags that can be assigned to your blog articles.</p>
    </div>

    <?php if (isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="about-grid" style="align-items: start;">
        <!-- Add / Edit Form -->
        <div class="recent-activity">
            <h3><?= $edit_tag ? 'Edit Tag' : 'Add New Tag' ?></h3>
            <form action="blog_tags.php" method="POST" style="margin-top: 15px;">
                <?php if ($edit_tag): ?>
                    <input type="hidden" name="id" value="<?= $edit_tag['id'] ?>">
                <?php endif; ?>
                
                <div style="margin-bottom: 20px;">
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Tag Name</label>
                    <input type="text" name="name" required value="<?= $edit_tag ? htmlspecialchars($edit_tag['name']) : '' ?>" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                </div>
                
                <?php if ($edit_tag): ?>
                    <button type="submit" name="update_tag" class="logout-btn" style="background:var(--primary); border:none; width:100%; cursor:pointer;">Update Tag</button>
                    <a href="blog_tags.php" style="display:block; text-align:center; margin-top:10px; color:var(--text); text-decoration:none; font-size:0.9rem;">Cancel</a>
                <?php else: ?>
                    <button type="submit" name="add_tag" class="logout-btn" style="background:var(--primary); border:none; width:100%; cursor:pointer;">Add Tag</button>
                <?php endif; ?>
            </form>
        </div>

        <!-- Tags List -->
        <div class="recent-activity">
            <h3>Existing Tags</h3>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Slug</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($tags) > 0): ?>
                            <?php foreach ($tags as $tag): ?>
                                <tr>
                                    <td style="font-weight:600;"><?= htmlspecialchars($tag['name']) ?></td>
                                    <td style="color:#94a3b8; font-size:0.85rem;"><?= htmlspecialchars($tag['slug']) ?></td>
                                    <td>
                                        <a href="blog_tags.php?edit=<?= $tag['id'] ?>" style="color:var(--primary); margin-right:10px;"><i class="fa-solid fa-pen-to-square"></i></a>
                                        <a href="blog_tags.php?delete=<?= $tag['id'] ?>" onclick="return confirm('Are you sure you want to delete this tag?');" style="color:var(--danger);"><i class="fa-solid fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="3" style="text-align: center; color: #94a3b8;">No tags found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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