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

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/layout.php';
require_once __DIR__ . '/includes/header.php';

// Fetch all tags
try {
    $stmt = $pdo->query("SELECT * FROM tags ORDER BY name ASC");
    $tags = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}
?>

<h1>All Tags</h1>

<div class="d-flex justify-content-end mb-3">
  <a href="create-tag.php" class="btn btn-sm btn-success" style="width: 120px;">Create Tag</a>
</div>

<table class="table table-striped align-middle">
    <thead>
        <tr>
            <th>Tag Name</th>
            <th>Preview</th>
            <th>Color Code</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
        <?php if (empty($tags)): ?>
            <tr><td colspan="5" class="text-center">No tags found.</td></tr>
        <?php else: ?>
            <?php foreach ($tags as $tag): ?>
                <tr>
                    <td><?= htmlspecialchars($tag['name']) ?></td>
                    <td>
                        <span class="badge" style="background-color: <?= htmlspecialchars($tag['color']) ?>;">
                            <?= htmlspecialchars($tag['name']) ?>
                        </span>
                    </td>
                    <td><code><?= htmlspecialchars($tag['color']) ?></code></td>
                    <td>
                        <a href="edit-tag.php?id=<?= (int)$tag['id'] ?>" class="btn btn-sm btn-primary">Edit</a>
                    </td>
                    <td>
                        <form method="post" action="delete-tag.php" onsubmit="return confirm('Are you sure you want to delete this tag?');" style="display:inline;">
                            <input type="hidden" name="id" value="<?= (int)$tag['id'] ?>">
                            <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>
