<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\Setting;

class WhatsAppNotificationService
{
    /**
     * Kirim notifikasi WA ke ADMIN menggunakan Fonnte API
     * Daftar gratis di: https://fonnte.com
     * Isi FONNTE_TOKEN di .env dengan token dari dashboard Fonnte.
     */
    public static function notifyAdmin(array $transactionData): bool
    {
        // Ambil dari DB (Prioritas) atau fallback ke config (.env)
        $adminPhone = Setting::where('key', 'wa_admin_phone')->first()?->value ?? config('services.whatsapp.admin_phone');
        $token      = Setting::where('key', 'fonnte_token')->first()?->value ?? config('services.whatsapp.fonnte_token');

        if (!$adminPhone || !$token || $token === 'YOUR_FONNTE_TOKEN_HERE') {
            // Belum dikonfigurasi – hanya log, tidak error
            Log::info('[WA-ADMIN] Notifikasi WA belum dikonfigurasi, skip.', $transactionData);
            return false;
        }

        $rp = fn($v) => 'Rp ' . number_format($v, 0, ',', '.');

        $pesan = "╔══════════════════╗\n";
        $pesan .= "║   TRANSAKSI BARU  ║\n";
        $pesan .= "╚══════════════════╝\n\n";
        $pesan .= "Order ID : {$transactionData['order_id']}\n";
        $pesan .= "Pelanggan: " . ($transactionData['customer_name'] ?? 'Guest') . "\n";
        $pesan .= "Game     : {$transactionData['game']}\n";
        $pesan .= "Nickname : {$transactionData['nickname']}\n";
        $pesan .= "Item     : {$transactionData['product']}\n";
        $pesan .= "Metode   : {$transactionData['payment_method']}\n";
        $pesan .= "Total    : " . $rp($transactionData['price']) . "\n";
        $pesan .= "Status   : *{$transactionData['status']}* \n";
        $pesan .= "\nKunjungi Admin Panel:\n";
        $pesan .= config('app.url') . "/admin\n";

        try {
            $response = Http::withHeaders([
                'Authorization' => $token,
            ])->timeout(5)
              ->post('https://api.fonnte.com/send', [
                'target'  => $adminPhone,
                'message' => $pesan,
                'countryCode' => '62',
            ]);

            if ($response->successful() && isset($response->json()['status']) && $response->json()['status'] === true) {
                Log::info('[WA-ADMIN] Notifikasi WA berhasil terkirim ke admin.', ['order_id' => $transactionData['order_id']]);
                return true;
            }

            Log::warning('[WA-ADMIN] Fonnte API gagal.', ['body' => $response->body()]);
            return false;
        } catch (\Exception $e) {
            Log::error('[WA-ADMIN] Exception saat kirim WA: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Kirim konfirmasi WA ke CUSTOMER setelah transaksi sukses
     */
    public static function notifyCustomer(array $transactionData): bool
    {
        $customerPhone = $transactionData['customer_whatsapp'];
        $token         = Setting::where('key', 'fonnte_token')->first()?->value ?? config('services.whatsapp.fonnte_token');

        if (!$customerPhone || !$token || $token === 'YOUR_FONNTE_TOKEN_HERE') {
            Log::info('[WA-CUSTOMER] Notifikasi WA customer belum dikonfigurasi, skip.');
            return false;
        }

        $rp = fn($v) => 'Rp ' . number_format($v, 0, ',', '.');
        $invoiceUrl = config('app.url') . "/invoice/{$transactionData['order_id']}";

        $pesan = "Halo *{$transactionData['customer_name']}*!\n\n";
        $pesan .= "Terima kasih telah berbelanja di *WYZSTORE*.\n";
        $pesan .= "Transaksi Top Up Anda *BERHASIL*!\n\n";
        $pesan .= "Detail Pesanan:\n";
        $pesan .= "- Order ID: {$transactionData['order_id']}\n";
        $pesan .= "- Game: {$transactionData['game']}\n";
        $pesan .= "- Item: {$transactionData['product']}\n";
        $pesan .= "- Total: " . $rp($transactionData['price']) . "\n\n";
        $pesan .= "Lihat & Download Invoice Anda di sini:\n";
        $pesan .= "{$invoiceUrl}\n\n";
        $pesan .= "Item sudah masuk ke akun Anda! Silakan cek game Anda sekarang.";

        try {
            $response = Http::withHeaders([
                'Authorization' => $token,
            ])->timeout(5)
              ->post('https://api.fonnte.com/send', [
                'target'      => $customerPhone,
                'message'     => $pesan,
                'countryCode' => '62',
            ]);

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('[WA-CUSTOMER] Exception: ' . $e->getMessage());
            return false;
        }
    }
}
