<?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'] === 'POST') {
    $json = json_decode(file_get_contents('php://input'), true);
    $action = $_POST['action'] ?? ($json['action'] ?? '');
    
    if ($action === 'create') {
        $channel_id = $_POST['channel_id'] ?? 0;
        $server_id = $_POST['server_id'] ?? 0;
        $icon = $_POST['icon'] ?? '';
        $title = $_POST['title'] ?? '';
        $role_id = $_POST['role_id'] ?? 0;
        
        if (Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_CHANNELS)) {
            $stmt = db()->prepare("INSERT INTO channel_autoroles (channel_id, icon, title, role_id) VALUES (?, ?, ?, ?)");
            $stmt->execute([$channel_id, $icon, $title, $role_id]);
        }
        header('Location: index.php?server_id=' . $server_id . '&channel_id=' . $channel_id);
        exit;
    }

    if ($action === 'update') {
        $id = $_POST['id'] ?? 0;
        $channel_id = $_POST['channel_id'] ?? 0;
        $server_id = $_POST['server_id'] ?? 0;
        $icon = $_POST['icon'] ?? '';
        $title = $_POST['title'] ?? '';
        $role_id = $_POST['role_id'] ?? 0;
        
        if (Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_CHANNELS)) {
            $stmt = db()->prepare("UPDATE channel_autoroles SET icon = ?, title = ?, role_id = ? WHERE id = ?");
            $stmt->execute([$icon, $title, $role_id, $id]);
        }
        header('Location: index.php?server_id=' . $server_id . '&channel_id=' . $channel_id);
        exit;
    }
    
    if ($action === 'delete') {
        $id = $_POST['id'] ?? 0;
        $channel_id = $_POST['channel_id'] ?? 0;
        $server_id = $_POST['server_id'] ?? 0;
        
        if (Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_CHANNELS)) {
            $stmt = db()->prepare("DELETE FROM channel_autoroles WHERE id = ?");
            $stmt->execute([$id]);
        }
        header('Location: index.php?server_id=' . $server_id . '&channel_id=' . $channel_id);
        exit;
    }
    
    if ($action === 'toggle') {
        // This will be called via AJAX
        $role_id = $json['role_id'] ?? 0;
        
        if (!$role_id) {
            echo json_encode(['success' => false, 'error' => 'Invalid role']);
            exit;
        }
        
        // Find the server for this role
        $stmt = db()->prepare("SELECT server_id FROM roles WHERE id = ?");
        $stmt->execute([$role_id]);
        $role = $stmt->fetch();
        
        if (!$role) {
            echo json_encode(['success' => false, 'error' => 'Role not found']);
            exit;
        }
        
        // Check if user is member of server
        $stmt = db()->prepare("SELECT 1 FROM server_members WHERE server_id = ? AND user_id = ?");
        $stmt->execute([$role['server_id'], $user_id]);
        if (!$stmt->fetch()) {
            echo json_encode(['success' => false, 'error' => 'Not a member of this server']);
            exit;
        }
        
        // Toggle role
        $stmt = db()->prepare("SELECT 1 FROM user_roles WHERE user_id = ? AND role_id = ?");
        $stmt->execute([$user_id, $role_id]);
        $has_role = $stmt->fetch();
        
        if ($has_role) {
            $stmt = db()->prepare("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?");
            $stmt->execute([$user_id, $role_id]);
            $added = false;
        } else {
            $stmt = db()->prepare("INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)");
            $stmt->execute([$user_id, $role_id]);
            $added = true;
        }
        
        echo json_encode(['success' => true, 'added' => $added]);
        exit;
    }
}
