<?php

namespace App\Helpers;

use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class TelegramHelper
{
public static function sendOtp(Order $order): void
{
    try {

        $user = User::find($order->user_id);

        if (!$user) {
            Log::warning("Telegram user not found");
            return;
        }

        if (!$user->telegram_id) {
            Log::warning("Telegram ID kosong user #{$user->id}");
            return;
        }

$res = Http::timeout(10)
    ->acceptJson()
    ->post(
        "https://api.telegram.org/bot".env('TELEGRAM_BOT_TOKEN')."/sendMessage",
        [
            'chat_id' => $user->telegram_id,

            'text' =>
"━━━━━━━━━━━━━━━
✅ OTP Masuk
━━━━━━━━━━━━━━━
🆔 Order ID : {$order->id}
📱 Layanan : {$order->layanan_nama}
☎️ Nomor : {$order->number}
🔑 OTP : {$order->otp}
━━━━━━━━━━━━━━━",

            'reply_markup' => json_encode([
                'inline_keyboard' => [

                    [
                        [
                            'text' => '📋 Salin Nomor',
                            'copy_text' => [
                                'text' => $order->number
                            ]
                        ]
                    ],

                    [
                        [
                            'text' => '🔑 Copy OTP',
                            'copy_text' => [
                                'text' => $order->otp
                            ]
                        ]
                    ]

                ]
            ])
        ]
    );

    } catch (\Throwable $e) {

        Log::error("Telegram send error: ".$e->getMessage());
    }
}
public static function sendOrderExpired(Order $order): void
{
    try {

        $user = User::find($order->user_id);

        if (!$user || !$user->telegram_id) {
            return;
        }

        Http::post(
            "https://api.telegram.org/bot".env('TELEGRAM_BOT_TOKEN')."/sendMessage",
            [
                'chat_id' => $user->telegram_id,

                'text' =>
"ℹ️ Order INfo
━━━━━━━━━━━━━━━
🆔 Order: {$order->id}
📱 Layanan: {$order->layanan_nama}
☎️ Nomor: {$order->number}
📌 Status: FAILED (kadaluarsa)
━━━━━━━━━━━━━━━
Masa tunggu OTP telah habis,saldo telah dikembalikan."
            ]
        );

    } catch (\Throwable $e) {

        Log::error(
            "Telegram expired notification error: ".
            $e->getMessage()
        );
    }
}
}