<?php
header('Content-Type: application/json');
require_once 'auth/session.php';
require_once 'includes/permissions.php';
requireLogin();

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $channel_id = $_GET['channel_id'] ?? 0;
    if (!$channel_id) {
        echo json_encode(['success' => false, 'error' => 'Missing channel_id']);
        exit;
    }
    $stmt = db()->prepare("SELECT * FROM forum_tags WHERE channel_id = ?");
    $stmt->execute([$channel_id]);
    echo json_encode(['success' => true, 'tags' => $stmt->fetchAll()]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    if (!$data) $data = $_POST;
    
    $action = $data['action'] ?? 'create';
    $channel_id = $data['channel_id'] ?? 0;

    // Check permissions
    $stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
    $stmt->execute([$channel_id]);
    $chan = $stmt->fetch();
    if (!$chan || !Permissions::canDoInChannel($user_id, $channel_id, Permissions::MANAGE_TAGS)) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }

    if ($action === 'create') {
        $name = $data['name'] ?? '';
        $color = $data['color'] ?? '#7289da';
        if (!$name) {
            echo json_encode(['success' => false, 'error' => 'Missing name']);
            exit;
        }
        $stmt = db()->prepare("INSERT INTO forum_tags (channel_id, name, color) VALUES (?, ?, ?)");
        $stmt->execute([$channel_id, $name, $color]);
        echo json_encode(['success' => true, 'tag_id' => db()->lastInsertId()]);
    } elseif ($action === 'delete') {
        $tag_id = $data['tag_id'] ?? 0;
        $stmt = db()->prepare("DELETE FROM forum_tags WHERE id = ? AND channel_id = ?");
        $stmt->execute([$tag_id, $channel_id]);
        echo json_encode(['success' => true]);
    }
    exit;
}
