<?php
require_once __DIR__ . '/../../includes/session_check.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../DiscordSender.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['action'])) {
    header('Location: ../sent_messages.php');
    exit();
}

$action = $_POST['action'];

if ($action === 'delete_message') {
        if (!isset($_POST['sent_message_id'], $_POST['platform_message_id'], $_POST['channel_id'])) {
        header('Location: ../sent_messages.php?error=missing_data');
        exit();
    }

    $sentMessageId = $_POST['sent_message_id'];
        $discordMessageIdsJson = $_POST['platform_message_id'];
    $channelId = $_POST['channel_id']; // The channel where the message was sent

    $discordMessageIds = json_decode($discordMessageIdsJson, true);

    // If decoding fails or the result is not an array, treat it as a single ID
    if (json_last_error() !== JSON_ERROR_NONE || !is_array($discordMessageIds)) {
        $discordMessageIds = [$discordMessageIdsJson];
    }

    $discordSender = new DiscordSender(DISCORD_BOT_TOKEN);

    try {
        // 1. Attempt to delete from Discord
        $all_deleted = true;
        foreach ($discordMessageIds as $discordMessageId) {
            // Skip if the ID is empty or invalid
            if (empty($discordMessageId) || !is_numeric($discordMessageId)) {
                error_log("Skipping invalid message chunk ID: " . var_export($discordMessageId, true));
                continue;
            }
            try {
                error_log("Attempting to delete message chunk ID: {$discordMessageId} in channel {$channelId}");
                $discordSender->deleteMessage($channelId, $discordMessageId);
                usleep(500000); // Wait 500ms to avoid rate limiting
            } catch (Exception $e) {
                error_log("Failed to delete message chunk {$discordMessageId}: " . $e->getMessage());
                $all_deleted = false; // Mark that at least one failed
            }
        }

        // 2. If all chunks were deleted (or if there was only one), delete from our database
        if ($all_deleted) {
            $stmt = $pdo->prepare("DELETE FROM sent_messages WHERE id = ?");
            $stmt->execute([$sentMessageId]);
            header('Location: ../sent_messages.php?success=deleted&platform=Discord');
        } else {
            // If some failed, we don't delete the entry, so it can be retried.
            // We could also add more sophisticated logic here, like storing partial success.
            header('Location: ../sent_messages.php?error=delete_failed_partial&platform=Discord');
        }
        exit();

    } catch (Exception $e) {
        error_log("Discord message deletion failed: " . $e->getMessage());
        header('Location: ../sent_messages.php?error=delete_failed&platform=Discord&message=' . urlencode($e->getMessage()));
        exit();
    }
}

// Fallback redirect
header('Location: ../sent_messages.php');
?>