<?php
require_once __DIR__ . "/db/config.php";
require_once __DIR__ . "/includes/permissions.php";
session_start();
header("Content-Type: application/json");

if (!isset($_SESSION["user_id"])) {
    echo json_encode(["success" => false, "error" => "Unauthorized"]);
    exit;
}

$channel_id = $_POST["channel_id"] ?? null;
if (!$channel_id) {
    echo json_encode(["success" => false, "error" => "Missing channel ID"]);
    exit;
}

// Get server_id for this channel
$stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
$stmt->execute([$channel_id]);
$channel = $stmt->fetch();

if (!$channel) {
    echo json_encode(["success" => false, "error" => "Channel not found"]);
    exit;
}

$server_id = $channel["server_id"];

// Check if user is owner or admin (minimal check for now)
$stmt = db()->prepare("SELECT owner_id FROM servers WHERE id = ?");
$stmt->execute([$server_id]);
$server = $stmt->fetch();

if (!Permissions::hasPermission($_SESSION["user_id"], $server_id, Permissions::MANAGE_CHANNELS)) {
    echo json_encode(["success" => false, "error" => "Only moderators or admins can clear history"]);
    exit;
}

try {
    $stmt = db()->prepare("DELETE FROM messages WHERE channel_id = ?");
    $stmt->execute([$channel_id]);
    echo json_encode(["success" => true]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
