<?php

class DiscordSender
{
    private const API_BASE_URL = 'https://discord.com/api/v10';
    private string $token;

    public function __construct(string $token)
    {
        $this->token = $token;
    }

    public function sendMessage(string $channelId, string $htmlContent) {
        $converter = new HtmlToDiscordMarkdownConverter();
        $markdown = $converter->convert($htmlContent);

        $sentMessageIds = [];
        
        // Simple implementation: send the whole markdown.
        // The original had complex logic to split text and images.
        // This is a simplification to get it working first.
        try {
            $response = $this->sendApiRequest("/channels/{$channelId}/messages", ['content' => $markdown]);
            if (isset($response['id'])) {
                $sentMessageIds[] = $response['id'];
            }
        } catch (Exception $e) {
            error_log("DiscordSender Error: " . $e->getMessage());
            return false;
        }

        return $sentMessageIds;
    }

    public function sendRawMessage(string $channelId, string $content): ?array
    {
        try {
            return $this->sendApiRequest("/channels/{$channelId}/messages", ['content' => $content]);
        } catch (Exception $e) {
            error_log("DiscordSender Error: " . $e->getMessage());
            return null;
        }
    }

    private function sendApiRequest(string $endpoint, array $payload, string $method = 'POST') {
        $url = self::API_BASE_URL . $endpoint;
        
        $ch = curl_init($url);
        $headers = [
            'Authorization: Bot ' . $this->token,
            'User-Agent: BotDiscord (https://github.com/nickpons/bot, 1.0)'
        ];

        if ($method === 'POST') {
            $headers[] = 'Content-Type: application/json';
            $postData = json_encode($payload);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $responseData = json_decode($response, true);
        
        if ($httpCode >= 400) {
            throw new Exception("Discord API error ({$httpCode}): " . ($responseData['message'] ?? 'Unknown error'));
        }
        
        return $responseData;
    }
}
