<?php
namespace Core;

class Notification {
    /**
     * Envia ou edita notificação por WhatsApp ou Telegram
     * @return array|null Retorna a key da mensagem do WhatsApp se for um envio inicial
     */
    public static function send(string $message, ?array $messageKey = null): ?array {
        $pdo = \getDBConnection();
        $newKey = null;
        
        // 1. WHATSAPP
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM global_settings WHERE setting_key = ?");
            $stmt->execute(['whatsapp_config']);
            $wa = json_decode($stmt->fetchColumn() ?: '{}', true);
            
            if ($wa && ($wa['active'] ?? false)) {
                $newKey = self::sendWhatsApp($wa, $message, $messageKey);
            }
        } catch (\Exception $e) {
            \error_log("Notification Error (WhatsApp): " . $e->getMessage());
        }
        
        // 2. TELEGRAM (Apenas envia novo por enquanto)
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM global_settings WHERE setting_key = ?");
            $stmt->execute(['telegram_config']);
            $tg = json_decode($stmt->fetchColumn() ?: '{}', true);
            
            if ($tg && ($tg['active'] ?? false) && !empty($tg['bot_token'])) {
                self::sendTelegram($tg, $message);
            }
        } catch (\Exception $e) {
            \error_log("Notification Error (Telegram): " . $e->getMessage());
        }

        return $newKey;
    }

    /**
     * Envia via API de WhatsApp Customizada (com suporte a Edição)
     */
    private static function sendWhatsApp(array $config, string $message, ?array $messageKey = null): ?array {
        $baseUrl = "http://191.252.214.221:3008/api/";
        $endpoint = $messageKey ? "edit" : "send";
        $url = $baseUrl . $endpoint;

        $payload = [
            'instanceId' => $config['instance_id'] ?? '',
            'jid' => $config['admin_number'] ?? '',
            'text' => $message
        ];

        if ($messageKey) {
            $payload['messageKey'] = $messageKey;
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: text/plain;charset=UTF-8',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        curl_close($ch);

        if (!$messageKey && $response) {
            $data = json_decode($response, true);
            return $data['key'] ?? null;
        }

        return null;
    }

    /**
     * Envia via API de Telegram
     */
    private static function sendTelegram(array $config, string $message): void {
        $token = $config['bot_token'];
        $chatId = $config['chat_id'];
        $url = "https://api.telegram.org/bot{$token}/sendMessage";
        
        $payload = [
            'chat_id' => $chatId,
            'text' => $message,
            'parse_mode' => 'HTML'
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_exec($ch);
        curl_close($ch);
    }
}
