<?php

namespace App\Listeners;

use App\Events\DebtPaid;
use Illuminate\Contracts\Queue\ShouldQueue; // WAJIB: Agar berjalan asinkron
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SendDebtNotification implements ShouldQueue // Implementasi Queue
{
    use InteractsWithQueue; 

    public function handle(DebtPaid $event)
    {
        // >>> WAJIB: Eager Load semua relasi yang digunakan <<<
        // Kita butuh data nota asal (sale), customer, branch, dan user (kasir)
        $payment = $event->payment->load(['sale.customer', 'branch', 'user']); 
        $sale = $payment->sale; // Ambil data nota asalnya
        
        // Baca dari Config yang sudah dijamin tersedia
        $token = config('services.telegram.token');
        $chatId = config('services.telegram.chat_id');

        if (empty($token) || empty($chatId)) return;

        // 1. Susun Pesan
        $branchName = $payment->branch ? $payment->branch->name : 'Cabang';
        $kasirName = $payment->user ? $payment->user->name : 'Admin';
        
        // Ambil customer dari relasi Sale
        $custName = $sale->customer ? $sale->customer->name : ($sale->customer_name ?? 'Umum');
        
        // Hitung sisa hutang *setelah* pembayaran ini (Berjalan di Queue, aman)
        $totalBayarSejauhIni = \App\Models\DebtPayment::where('sale_id', $sale->id)->sum('amount');
        $sisaHutang = $sale->grand_total - $totalBayarSejauhIni;

        $amountFmt = number_format($payment->amount, 0, ',', '.');
        $sisaFmt = number_format($sisaHutang, 0, ',', '.');

        // Tentukan ikon status
        $statusIcon = $sisaHutang < 100 ? '🟢 LUNAS' : '🟡 CICILAN';

        $msg = "<b>💰 TERIMA PELUNASAN ($statusIcon)</b>\n";
        $msg .= "Nota Asal: <code>{$sale->invoice_number}</code>\n";
        $msg .= "Cust: $custName\n";
        $msg .= "Bayar: <b>Rp $amountFmt</b> ({$payment->payment_method})\n";
        $msg .= "Sisa Piutang: Rp $sisaFmt\n";
        $msg .= "Kasir: $kasirName - $branchName\n";
        $msg .= "------------------\n";

        // 2. Kirim ke Telegram
        try {
            $response = Http::post("https://api.telegram.org/bot{$token}/sendMessage", [
                'chat_id' => $chatId,
                'text' => $msg,
                'parse_mode' => 'HTML',
            ]);
            
            if ($response->successful()) {
                Log::info("Telegram Berhasil Terkirim: Pelunasan " . $sale->invoice_number);
            } else {
                Log::error("Telegram Ditolak Server: " . $response->body());
            }

        } catch (\Exception $e) {
            Log::error("Telegram Gagal Koneksi: " . $e->getMessage());
        }
    }
}