<?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') {
    $channel_id = $_POST['channel_id'] ?? 0;
    $content = $_POST['content'] ?? '';

    // 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)) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }

    try {
        // Get max position
        $stmt = db()->prepare("SELECT MAX(position) FROM channel_rules WHERE channel_id = ?");
        $stmt->execute([$channel_id]);
        $pos = (int)$stmt->fetchColumn() + 1;

        $stmt = db()->prepare("INSERT INTO channel_rules (channel_id, content, position) VALUES (?, ?, ?)");
        $stmt->execute([$channel_id, $content, $pos]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $id = $_GET['id'] ?? 0;
    
    $stmt = db()->prepare("SELECT c.server_id FROM channels c JOIN channel_rules r ON c.id = r.channel_id WHERE r.id = ?");
    $stmt->execute([$id]);
    $res = $stmt->fetch();

    if ($res && Permissions::hasPermission($user_id, $res['server_id'], Permissions::MANAGE_CHANNELS)) {
        $stmt = db()->prepare("DELETE FROM channel_rules WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (isset($data['order'])) {
        // Bulk reorder
        foreach ($data['order'] as $index => $id) {
            // Basic permission check (optional but recommended: verify all rules belong to same server user can manage)
            if ($index === 0) {
                 $stmt = db()->prepare("SELECT c.server_id FROM channels c JOIN channel_rules r ON c.id = r.channel_id WHERE r.id = ?");
                 $stmt->execute([$id]);
                 $res = $stmt->fetch();
                 if (!$res || !Permissions::hasPermission($user_id, $res['server_id'], Permissions::MANAGE_CHANNELS)) {
                     echo json_encode(['success' => false, 'error' => 'Unauthorized']);
                     exit;
                 }
            }
            $stmt = db()->prepare("UPDATE channel_rules SET position = ? WHERE id = ?");
            $stmt->execute([$index + 1, $id]);
        }
        echo json_encode(['success' => true]);
        exit;
    }

    $id = $data['id'] ?? 0;
    $dir = $data['dir'] ?? 'up';

    // Check permission
    $stmt = db()->prepare("SELECT c.server_id, r.channel_id, r.position FROM channels c JOIN channel_rules r ON c.id = r.channel_id WHERE r.id = ?");
    $stmt->execute([$id]);
    $current = $stmt->fetch();

    if ($current && Permissions::hasPermission($user_id, $current['server_id'], Permissions::MANAGE_CHANNELS)) {
        $channel_id = $current['channel_id'];
        $pos = $current['position'];
        
        if ($dir === 'up') {
            $stmt = db()->prepare("SELECT id, position FROM channel_rules WHERE channel_id = ? AND position < ? ORDER BY position DESC LIMIT 1");
        } else {
            $stmt = db()->prepare("SELECT id, position FROM channel_rules WHERE channel_id = ? AND position > ? ORDER BY position ASC LIMIT 1");
        }
        $stmt->execute([$channel_id, $pos]);
        $other = $stmt->fetch();

        if ($other) {
            db()->prepare("UPDATE channel_rules SET position = ? WHERE id = ?")->execute([$other['position'], $id]);
            db()->prepare("UPDATE channel_rules SET position = ? WHERE id = ?")->execute([$pos, $other['id']]);
        }
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Rule not found']);
    }
    exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $data['id'] ?? 0;
    $content = $data['content'] ?? '';

    $stmt = db()->prepare("SELECT c.server_id FROM channels c JOIN channel_rules r ON c.id = r.channel_id WHERE r.id = ?");
    $stmt->execute([$id]);
    $res = $stmt->fetch();

    if ($res && Permissions::hasPermission($user_id, $res['server_id'], Permissions::MANAGE_CHANNELS)) {
        $stmt = db()->prepare("UPDATE channel_rules SET content = ? WHERE id = ?");
        $stmt->execute([$content, $id]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    }
    exit;
}
