<?php
require_once 'connect.php';

try {
    $conn = getDatabaseConnection();

    $blog_id = isset($_GET['blog_id']) ? (int) $_GET['blog_id'] : null;

    if (!$blog_id || $blog_id <= 0) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Valid blog ID is required',
            'error' => 'Invalid or missing blog_id parameter',
        ]);
        exit();
    }

    $query = "SELECT t.id, t.name, t.slug 
              FROM tags t
              INNER JOIN blog_tags bt ON t.id = bt.tag_id
              WHERE bt.blog_id = :blog_id
              ORDER BY t.name ASC";

    $stmt = $conn->prepare($query);
    $stmt->bindParam(':blog_id', $blog_id, PDO::PARAM_INT);
    $stmt->execute();

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

    $tags = array_map(function ($tag) {
        return [
            'id' => (int) $tag['id'],
            'name' => $tag['name'],
            'slug' => $tag['slug'],
        ];
    }, $tags);

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'data' => $tags,
        'count' => count($tags),
        'blog_id' => $blog_id,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch blog tags',
        'error' => $e->getMessage(),
        'blog_id' => $blog_id ?? null,
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request',
        'error' => $e->getMessage(),
    ]);
}
?>