<?php

namespace App\Listeners;

use App\Events\SaleCreated;
use Illuminate\Contracts\Queue\ShouldQueue; 
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SendTelegramNotification implements ShouldQueue 
{
    use InteractsWithQueue; 

    public function handle(SaleCreated $event)
    {
        // Eager Load data relasi agar ringan
        $sale = $event->sale->load(['user', 'branch', 'items']); 
        
        $token = config('services.telegram.token');
        $chatId = config('services.telegram.chat_id');

        // Cek token, jika kosong berhenti (biar gak error)
        if (empty($token) || empty($chatId)) {
            return; 
        }

        // Ambil Data
        $user = $sale->user; 
        $branch = $sale->branch;
        $items = $sale->items; 

        // --- UPDATE LOGIKA STATUS & IKON ---
        // Ambil metode bayar dan status, ubah ke huruf kecil semua biar aman
        $method = strtolower($sale->payment_method ?? ''); // cash, transfer, qris, credit
        $status = strtolower($sale->payment_status ?? ''); // paid, pending

        $methodIcon = '❓'; // Default

        // 1. Prioritas Cek Hutang
        if ($status == 'pending' || $method == 'credit') {
            $methodIcon = '🔴 HUTANG';
        } 
        // 2. Cek Transfer
        elseif ($method == 'transfer') {
            $methodIcon = '🏦 TRANSFER';
        } 
        // 3. Cek QRIS
        elseif ($method == 'qris') {
            $methodIcon = '📱 QRIS';
        } 
        // 4. Cek Tunai
        elseif ($method == 'cash') {
            $methodIcon = '💵 TUNAI';
        } 
        // 5. Lain-lain (Fallback)
        else {
            $methodIcon = '✅ LUNAS';
        }
        // ----------------------------------------
        
        $branchName = $branch ? $branch->name : 'Pusat';
        $kasirName = $user ? $user->name : 'Sistem';
        $custName = $sale->customer_name ?? 'Umum';
        $totalFmt = number_format($sale->grand_total, 0, ',', '.');

        // Susun Pesan (HTML Format)
        $msg = "<b>{$methodIcon} - {$branchName}</b>\n";
        $msg .= "No: <code>{$sale->invoice_number}</code>\n";
        $msg .= "Kasir: {$kasirName}\n";
        $msg .= "Cust: {$custName}\n";
        $msg .= "Total: <b>Rp {$totalFmt}</b>\n";
        $msg .= "------------------\n";

        // List Barang (Maksimal 5 baris biar chat tidak kepanjangan)
        if ($items) {
            foreach ($items->take(5) as $item) {
                $unit = $item->unit ?? 'pcs';
                // Tampilkan qty, jika koma (misal 1.5) tampilkan desimal, jika bulat (1.0) tampilkan bulat
                $qtyVal = (float)$item->quantity;
                $qtyDisplay = ($qtyVal == (int)$qtyVal) ? (int)$qtyVal : $qtyVal;
                
                $msg .= "- {$item->product_name} ({$qtyDisplay} {$unit})\n";
            }
            // Jika barang lebih dari 5, kasih info tambahan
            if ($items->count() > 5) {
                $msg .= "... dan " . ($items->count() - 5) . " item lainnya.";
            }
        }

        // Kirim ke API Telegram
        try {
            Http::post("https://api.telegram.org/bot{$token}/sendMessage", [
                'chat_id' => $chatId,
                'text' => $msg,
                'parse_mode' => 'HTML', 
            ]);
        } catch (\Exception $e) {
            Log::error("Telegram Error: " . $e->getMessage());
        }
    }
}