<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../security/auth_guard.php';
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../core/Response.php';

$db = Database::getInstance();

$context = $_GET['context'] ?? 'backend';

/**
 * Fetch tags with blog count (many-to-many)
 */
$sql = "
    SELECT 
        t.id,
        t.name,
        t.slug,
        t.status,
        t.created_at,
        COUNT(btm.blog_id) AS blog_count
    FROM blog_tags t
    LEFT JOIN blog_tag_map btm 
        ON btm.tag_id = t.id
";

if ($context === 'frontend') {
    $sql .= " WHERE t.status = 'Active'";
}

$sql .= "
    GROUP BY t.id
    ORDER BY t.name ASC
";

$stmt = $db->query($sql);
$tags = $stmt->fetchAll(PDO::FETCH_ASSOC);

Response::success('Blog tags fetched successfully', $tags);
