<?php
header('Content-Type: application/json');
require_once 'auth/session.php';
require_once 'includes/permissions.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;
    }

    if (!Permissions::canDoInChannel($user_id, $channel_id, Permissions::CREATE_THREAD)) {
        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' || $_SERVER['REQUEST_METHOD'] === 'DELETE' || (isset($_GET['action']) && in_array($_GET['action'], ['solve', 'pin', 'unpin', 'lock', 'unlock', 'delete', 'update_tags']))) {
    $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    $thread_id = $data['thread_id'] ?? $_GET['thread_id'] ?? 0;
    $message_id = $data['message_id'] ?? null;
    $action = $_GET['action'] ?? $data['action'] ?? 'solve';
    
    if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
        $action = 'delete';
    }
    
    $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();

    $is_admin = Permissions::hasPermission($user_id, $thread['server_id'], Permissions::ADMINISTRATOR) || 
                Permissions::hasPermission($user_id, $thread['server_id'], Permissions::MANAGE_SERVER) || 
                Permissions::hasPermission($user_id, $thread['server_id'], Permissions::MANAGE_MESSAGES) || 
                $server['owner_id'] == $user_id;

    try {
        if ($action === 'solve') {
            if ($thread['user_id'] != $user_id && !$is_admin) {
                echo json_encode(['success' => false, 'error' => 'Unauthorized']); exit;
            }
            $stmt = db()->prepare("UPDATE forum_threads SET solution_message_id = ? WHERE id = ?");
            $stmt->execute([$message_id, $thread_id]);
        } elseif ($action === 'pin') {
            if (!Permissions::canDoInChannel($user_id, $thread['channel_id'], Permissions::PIN_THREADS)) {
                echo json_encode(['success' => false, 'error' => 'You do not have permission to pin threads.']); exit;
            }
            $stmt = db()->prepare("UPDATE forum_threads SET is_pinned = 1 WHERE id = ?");
            $stmt->execute([$thread_id]);
        } elseif ($action === 'unpin') {
            if (!Permissions::canDoInChannel($user_id, $thread['channel_id'], Permissions::PIN_THREADS)) {
                echo json_encode(['success' => false, 'error' => 'You do not have permission to unpin threads.']); exit;
            }
            $stmt = db()->prepare("UPDATE forum_threads SET is_pinned = 0 WHERE id = ?");
            $stmt->execute([$thread_id]);
        } elseif ($action === 'lock') {
            if (!Permissions::canDoInChannel($user_id, $thread['channel_id'], Permissions::LOCK_THREADS)) {
                echo json_encode(['success' => false, 'error' => 'You do not have permission to lock threads.']); exit;
            }
            $stmt = db()->prepare("UPDATE forum_threads SET is_locked = 1 WHERE id = ?");
            $stmt->execute([$thread_id]);
        } elseif ($action === 'unlock') {
            if (!Permissions::canDoInChannel($user_id, $thread['channel_id'], Permissions::LOCK_THREADS)) {
                echo json_encode(['success' => false, 'error' => 'You do not have permission to unlock threads.']); exit;
            }
            $stmt = db()->prepare("UPDATE forum_threads SET is_locked = 0 WHERE id = ?");
            $stmt->execute([$thread_id]);
        } elseif ($action === 'delete') {
            if ($thread['user_id'] != $user_id && !$is_admin) {
                echo json_encode(['success' => false, 'error' => 'Unauthorized']); exit;
            }
            db()->beginTransaction();
            // Delete associated tags
            $stmt = db()->prepare("DELETE FROM thread_tags WHERE thread_id = ?");
            $stmt->execute([$thread_id]);
            // Delete associated messages
            $stmt = db()->prepare("DELETE FROM messages WHERE thread_id = ?");
            $stmt->execute([$thread_id]);
            // Delete thread
            $stmt = db()->prepare("DELETE FROM forum_threads WHERE id = ?");
            $stmt->execute([$thread_id]);
            db()->commit();
        } elseif ($action === 'update_tags') {
            if ($thread['user_id'] != $user_id && !$is_admin) {
                echo json_encode(['success' => false, 'error' => 'Unauthorized']); exit;
            }
            $tag_ids = $data['tag_ids'] ?? [];
            db()->beginTransaction();
            $stmt = db()->prepare("DELETE FROM thread_tags WHERE thread_id = ?");
            $stmt->execute([$thread_id]);
            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]);
    } catch (Exception $e) {
        if (db()->inTransaction()) db()->rollBack();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}