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

$user_id = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true) ?? $_POST;

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $channel_id = $_GET['channel_id'] ?? 0;
    
    // Get server_id for this channel
    $stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
    $stmt->execute([$channel_id]);
    $channel = $stmt->fetch();
    $server_id = $channel['server_id'] ?? 0;

    // Ensure @everyone role exists for this server
    $stmt = db()->prepare("SELECT id FROM roles WHERE server_id = ? AND (LOWER(name) = '@everyone' OR LOWER(name) = 'everyone') LIMIT 1");
    $stmt->execute([$server_id]);
    $everyone = $stmt->fetch();
    if (!$everyone && $server_id) {
        $stmt = db()->prepare("INSERT INTO roles (server_id, name, color, permissions, position) VALUES (?, '@everyone', '#99aab5', 0, 0)");
        $stmt->execute([$server_id]);
        $everyone_role_id = db()->lastInsertId();
    } else {
        $everyone_role_id = $everyone['id'] ?? 0;
    }

    // Fetch permissions for this channel
    $stmt = db()->prepare("
        SELECT cp.*, r.name as role_name, r.color as role_color 
        FROM channel_permissions cp 
        JOIN roles r ON cp.role_id = r.id 
        WHERE cp.channel_id = ?
    ");
    $stmt->execute([$channel_id]);
    $permissions = $stmt->fetchAll();

    // Check if @everyone is in permissions, if not add it manually to show up by default
    $has_everyone = false;
    foreach($permissions as $p) {
        if ($p['role_id'] == $everyone_role_id) {
            $has_everyone = true;
            break;
        }
    }

    if (!$has_everyone && $everyone_role_id > 0) {
        $stmt = db()->prepare("SELECT name, color FROM roles WHERE id = ?");
        $stmt->execute([$everyone_role_id]);
        $r = $stmt->fetch();
        if ($r) {
            array_unshift($permissions, [
                'channel_id' => (int)$channel_id,
                'role_id' => (int)$everyone_role_id,
                'allow_permissions' => 0,
                'deny_permissions' => 0,
                'role_name' => $r['name'],
                'role_color' => $r['color']
            ]);
        }
    }

    echo json_encode(['success' => true, 'permissions' => $permissions]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $channel_id = $data['channel_id'] ?? 0;
    $role_id = $data['role_id'] ?? 0;
    $allow = $data['allow'] ?? 0;
    $deny = $data['deny'] ?? 0;

    // Check permissions: Owner or MANAGE_CHANNELS or ADMINISTRATOR
    require_once 'includes/permissions.php';
    $stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
    $stmt->execute([$channel_id]);
    $ch = $stmt->fetch();
    $server_id = $ch['server_id'] ?? 0;

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

    $is_owner = ($server && $server['owner_id'] == $user_id);
    $can_manage = Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_CHANNELS) || 
                  Permissions::hasPermission($user_id, $server_id, Permissions::ADMINISTRATOR);

    if ($is_owner || $can_manage) {
        $stmt = db()->prepare("
            INSERT INTO channel_permissions (channel_id, role_id, allow_permissions, deny_permissions) 
            VALUES (?, ?, ?, ?) 
            ON DUPLICATE KEY UPDATE allow_permissions = VALUES(allow_permissions), deny_permissions = VALUES(deny_permissions)
        ");
        $stmt->execute([$channel_id, $role_id, $allow, $deny]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $channel_id = $data['channel_id'] ?? 0;
    $role_id = $data['role_id'] ?? 0;

    // Check permissions
    require_once 'includes/permissions.php';
    $stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
    $stmt->execute([$channel_id]);
    $ch = $stmt->fetch();
    $server_id = $ch['server_id'] ?? 0;

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

    $is_owner = ($server && $server['owner_id'] == $user_id);
    $can_manage = Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_CHANNELS) || 
                  Permissions::hasPermission($user_id, $server_id, Permissions::ADMINISTRATOR);

    if ($is_owner || $can_manage) {
        $stmt = db()->prepare("DELETE FROM channel_permissions WHERE channel_id = ? AND role_id = ?");
        $stmt->execute([$channel_id, $role_id]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    }
    exit;
}
