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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $channel_id = $_POST['channel_id'] ?? 0;
    $title = $_POST['title'] ?? '';
    $user_id = $_SESSION['user_id'];

    if (!$channel_id || !$title) {
        echo json_encode(['success' => false, 'error' => 'Missing data']);
        exit;
    }

    require_once 'includes/permissions.php';
    if (!Permissions::canSendInChannel($user_id, $channel_id)) {
        echo json_encode(['success' => false, 'error' => 'You do not have permission to create threads in this channel.']);
        exit;
    }

    $tag_ids = $_POST['tag_ids'] ?? [];
    if (is_string($tag_ids)) {
        $tag_ids = array_filter(explode(',', $tag_ids));
    }

    try {
        db()->beginTransaction();
        $stmt = db()->prepare("INSERT INTO forum_threads (channel_id, user_id, title) VALUES (?, ?, ?)");
        $stmt->execute([$channel_id, $user_id, $title]);
        $thread_id = db()->lastInsertId();

        if (!empty($tag_ids)) {
            $stmtTag = db()->prepare("INSERT INTO thread_tags (thread_id, tag_id) VALUES (?, ?)");
            foreach ($tag_ids as $tag_id) {
                if ($tag_id) $stmtTag->execute([$thread_id, $tag_id]);
            }
        }
        db()->commit();
        echo json_encode(['success' => true, 'thread_id' => $thread_id]);
    } catch (Exception $e) {
        db()->rollBack();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'PATCH' || (isset($_GET['action']) && $_GET['action'] === 'solve')) {
    $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    $thread_id = $data['thread_id'] ?? 0;
    $message_id = $data['message_id'] ?? null; // null to unsolve
    $user_id = $_SESSION['user_id'];

    if (!$thread_id) {
        echo json_encode(['success' => false, 'error' => 'Missing thread_id']);
        exit;
    }

    // Verify permission (thread owner or admin)
    $stmt = db()->prepare("SELECT t.*, c.server_id FROM forum_threads t JOIN channels c ON t.channel_id = c.id WHERE t.id = ?");
    $stmt->execute([$thread_id]);
    $thread = $stmt->fetch();

    if (!$thread) {
        echo json_encode(['success' => false, 'error' => 'Thread not found']);
        exit;
    }

    $stmtServer = db()->prepare("SELECT owner_id FROM servers WHERE id = ?");
    $stmtServer->execute([$thread['server_id']]);
    $server = $stmtServer->fetch();

    if ($thread['user_id'] != $user_id && $server['owner_id'] != $user_id) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }

    try {
        $stmt = db()->prepare("UPDATE forum_threads SET solution_message_id = ? WHERE id = ?");
        $stmt->execute([$message_id, $thread_id]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
