<?php
require_once __DIR__ . '/session_check.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/../src/TelegramSender.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['chat_id'])) {
        header('Location: ../sent_messages.php?error=missing_data');
        exit();
    }

    $sentMessageId = $_POST['sent_message_id'];
    $telegramMessageIdsJson = $_POST['platform_message_id'];
    $chatId = $_POST['chat_id'];

    $telegramMessageIds = json_decode($telegramMessageIdsJson, 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($telegramMessageIds)) {
        $telegramMessageIds = [$telegramMessageIdsJson];
    }

    $telegramSender = new TelegramSender(TELEGRAM_BOT_TOKEN);
    $allDeleted = true;
    $error_messages = [];

    try {
        foreach ($telegramMessageIds as $messageId) {
            // Skip if the ID is empty or invalid
            if (empty($messageId) || !is_numeric($messageId)) {
                error_log("Skipping invalid Telegram message ID: " . var_export($messageId, true));
                continue;
            }

            try {
                $telegramSender->deleteMessage($chatId, $messageId);
                usleep(300000); // 300ms pause to avoid rate limits
            } catch (Exception $e) {
                $allDeleted = false;
                $error_messages[] = "Failed to delete message ID {$messageId}: " . $e->getMessage();
                error_log(end($error_messages)); // Log the last error
            }
        }

        if ($allDeleted) {
            // If all messages were deleted successfully, remove the record from DB
            $stmt = $pdo->prepare("DELETE FROM sent_messages WHERE id = ?");
            $stmt->execute([$sentMessageId]);
            header('Location: ../sent_messages.php?success=deleted&platform=Telegram');
        } else {
            // If some deletions failed, redirect with an error message
            $errorMessage = implode('; ', $error_messages);
            header('Location: ../sent_messages.php?error=delete_failed&platform=Telegram&message=' . urlencode($errorMessage));
        }
        exit();

    } catch (Exception $e) {
        // Catch any other unexpected errors during the process
        $errorMessage = "An unexpected error occurred: " . $e->getMessage();
        error_log($errorMessage);
        header('Location: ../sent_messages.php?error=unexpected_error&platform=Telegram&message=' . urlencode($errorMessage));
        exit();
    }
} // Closing brace for "if ($action === 'delete_message')"

// Fallback redirect if action is not 'delete_message'
header('Location: ../sent_messages.php');
exit();