<?php

namespace App\Listeners;

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

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

    public function handle(SupplierDebtPaid $event)
    {
        // >>> WAJIB: Eager Load semua relasi yang digunakan <<<
        // Kita butuh relasi branch, supplier, dan user dari model Purchase
        $purchase = $event->purchase->load(['branch', 'supplier', 'user']); 
        
        $token = config('services.telegram.token');
        $chatId = config('services.telegram.chat_id');

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

        // 1. Susun Pesan
        $branchName = $purchase->branch ? $purchase->branch->name : 'Cabang';
        $supplierName = $purchase->supplier ? $purchase->supplier->name : 'Supplier';
        $kasirName = $purchase->user ? $purchase->user->name : 'Admin';
        
        // Ambil data pembayaran dari event
        $amount = $event->paymentAmount;
        $method = $event->paymentMethod;
        
        // Hitung sisa hutang *setelah* pembayaran ini (Aman di Queue)
        $totalPaid = \App\Models\DebtPayment::where('purchase_id', $purchase->id)->sum('amount');
        $sisaHutang = $purchase->grand_total - $totalPaid;
        
        // Cek status Lunas/Cicilan
        $statusIcon = $sisaHutang < 100 ? '🟢 LUNAS' : '🟡 CICILAN';

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

        $msg = "<b>💸 HUTANG SUPPLIER DIBAYAR ($statusIcon)</b>\n";
        $msg .= "Faktur: <code>{$purchase->invoice_number}</code>\n";
        $msg .= "Supplier: $supplierName\n";
        $msg .= "Bayar: <b>Rp $amountFmt</b> ($method)\n";
        $msg .= "Sisa Hutang: Rp $sisaFmt\n";
        $msg .= "Oleh: $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::error("Telegram Hutang Supplier Gagal: " . $response->body());
            }

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