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

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? '';
    if ($action === 'list_all') {
        $stmt = db()->query("SELECT id, name FROM channels WHERE type = 'voice' ORDER BY name ASC");
        echo json_encode(['success' => true, 'channels' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        exit;
    }
    
    $server_id = $_GET['server_id'] ?? 0;
    if (!$server_id) {
        echo json_encode([]);
        exit;
    }
    $stmt = db()->prepare("SELECT * FROM channels WHERE server_id = ?");
    $stmt->execute([$server_id]);
    echo json_encode($stmt->fetchAll());
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle JSON input
    $json = json_decode(file_get_contents('php://input'), true);
    if ($json) {
        $action = $json['action'] ?? '';
        if ($action === 'reorder') {
            $server_id = $json['server_id'] ?? 0;
            $orders = $json['orders'] ?? []; // Array of {id, position, category_id}
            $user_id = $_SESSION['user_id'];
            
            if (Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_CHANNELS)) {
                $stmt = db()->prepare("UPDATE channels SET position = ?, category_id = ? WHERE id = ? AND server_id = ?");
                foreach ($orders as $o) {
                    $stmt->execute([$o['position'], $o['category_id'] ?: null, $o['id'], $server_id]);
                }
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Permission denied']);
            }
            exit;
        }
    }

    $action = $_POST['action'] ?? 'create';
    $server_id = $_POST['server_id'] ?? 0;
    $user_id = $_SESSION['user_id'];

    if ($action === 'update') {
        $channel_id = $_POST['channel_id'] ?? 0;
        $name = $_POST['name'] ?? '';
        $type = $_POST['type'] ?? 'chat';
        $status = $_POST['status'] ?? null;
        if ($type === 'poll') $allow_file_sharing = 0;
        else $allow_file_sharing = isset($_POST['allow_file_sharing']) ? 1 : 0;
        $message_limit = !empty($_POST['message_limit']) ? (int)$_POST['message_limit'] : null;
        $icon = $_POST['icon'] ?? null;
        if ($icon === '') $icon = null;
        $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
        $rules_role_id = !empty($_POST['rules_role_id']) ? (int)$_POST['rules_role_id'] : null;
        $ai_moderation_enabled = isset($_POST['ai_moderation_enabled']) ? 1 : 0;

        // Check if user has permission to manage channels
        $stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
        $stmt->execute([$channel_id]);
        $chan = $stmt->fetch();
        
        if ($chan && Permissions::hasPermission($user_id, $chan['server_id'], Permissions::MANAGE_CHANNELS)) {
            if ($type === 'separator' && !$name) $name = 'separator';
            // Allow spaces, accents and mixed case
            $name = trim($name);
            // Explicitly exclude position from update to prevent jumping to bottom
            $stmt = db()->prepare("UPDATE channels SET name = ?, type = ?, status = ?, allow_file_sharing = ?, ai_moderation_enabled = ?, message_limit = ?, icon = ?, category_id = ?, rules_role_id = ? WHERE id = ?");
            $stmt->execute([$name, $type, $status, $allow_file_sharing, $ai_moderation_enabled, $message_limit, $icon, $category_id, $rules_role_id, $channel_id]);
            
            if ($message_limit !== null) {
                require_once 'db/config.php';
                enforceChannelLimit($channel_id);
            }
        }
        header('Location: index.php?server_id=' . $server_id . '&channel_id=' . $channel_id);
        exit;
    }

    if ($action === 'delete') {
        $channel_id = $_POST['channel_id'] ?? 0;
        $stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
        $stmt->execute([$channel_id]);
        $chan = $stmt->fetch();

        if ($chan && Permissions::hasPermission($user_id, $chan['server_id'], Permissions::MANAGE_CHANNELS)) {
            $stmt = db()->prepare("DELETE FROM channels WHERE id = ?");
            $stmt->execute([$channel_id]);
        }
        header('Location: index.php?server_id=' . ($chan['server_id'] ?? ''));
        exit;
    }

    $name = $_POST['name'] ?? '';
    $type = $_POST['type'] ?? 'text';
    
    // Check if user has permission to manage channels
    if (Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_CHANNELS) && ($name || $type === 'separator')) {
        try {
            if ($type === 'separator' && !$name) $name = 'separator';
            // Allow spaces, accents and mixed case
            $name = trim($name);
            if ($type === 'poll') $allow_file_sharing = 0;
            else $allow_file_sharing = isset($_POST['allow_file_sharing']) ? 1 : 0;
            $message_limit = !empty($_POST['message_limit']) ? (int)$_POST['message_limit'] : null;
            $icon = $_POST['icon'] ?? null;
            if ($icon === '') $icon = null;
            $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
            $rules_role_id = !empty($_POST['rules_role_id']) ? (int)$_POST['rules_role_id'] : null;
        $ai_moderation_enabled = isset($_POST['ai_moderation_enabled']) ? 1 : 0;
            
            // Get next position
            $stmtPos = db()->prepare("SELECT MAX(position) as max_pos FROM channels WHERE server_id = ?");
            $stmtPos->execute([$server_id]);
            $maxPos = $stmtPos->fetch();
            $nextPos = ($maxPos['max_pos'] ?? -1) + 1;

            $stmt = db()->prepare("INSERT INTO channels (server_id, name, type, allow_file_sharing, ai_moderation_enabled, message_limit, icon, category_id, position, rules_role_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$server_id, $name, $type, $allow_file_sharing, $ai_moderation_enabled, $message_limit, $icon, $category_id, $nextPos, $rules_role_id]);
            $channel_id = db()->lastInsertId();
            
            header('Location: index.php?server_id=' . $server_id . '&channel_id=' . $channel_id);
            exit;
        } catch (Exception $e) {
            die("Error creating channel: " . $e->getMessage());
        }
    }
}
header('Location: index.php');
