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

// Check for execution (no session needed, just token)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['token'])) {
    require_once 'db/config.php';
    $token = $_GET['token'] ?? '';
    $data = json_decode(file_get_contents('php://input'), true);
    $content = $data['content'] ?? '';
    
    $stmt = db()->prepare("SELECT * FROM webhooks WHERE token = ?");
    $stmt->execute([$token]);
    $webhook = $stmt->fetch();
    
    if (!$webhook) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Invalid token']);
        exit;
    }
    
    if (empty($content)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Empty content']);
        exit;
    }
    
    try {
        $stmt = db()->prepare("INSERT INTO messages (channel_id, user_id, content) VALUES (?, ?, ?)");
        $stmt->execute([$webhook['channel_id'], 1, $content]); // 1 is system/bot user
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Manage webhooks (session needed)
requireLogin();
$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $server_id = $_GET['server_id'] ?? 0;
    $stmt = db()->prepare("
        SELECT w.*, c.name as channel_name 
        FROM webhooks w 
        JOIN channels c ON w.channel_id = c.id 
        WHERE c.server_id = ?
    ");
    $stmt->execute([$server_id]);
    $webhooks = $stmt->fetchAll();
    echo json_encode(['success' => true, 'webhooks' => $webhooks]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $channel_id = $data['channel_id'] ?? 0;
    $name = $data['name'] ?? 'New Webhook';
    $token = bin2hex(random_bytes(16));

    try {
        $stmt = db()->prepare("INSERT INTO webhooks (channel_id, name, token) VALUES (?, ?, ?)");
        $stmt->execute([$channel_id, $name, $token]);
        echo json_encode(['success' => true, 'webhook' => ['id' => db()->lastInsertId(), 'token' => $token]]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $data['id'] ?? 0;
    try {
        $stmt = db()->prepare("DELETE FROM webhooks WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
