<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppService
{
    /**
     * Send OTP message via WhatsApp API.
     *
     * @param string $to WhatsApp number
     * @param string $message Message content
     * @return bool
     */
    public function sendMessage(string $to, string $message): bool
    {
        $gatewayType = env('WA_GATEWAY_TYPE', 'botwa'); // Default to botwa
        $apiKey = env('WA_API_KEY');
        $apiUrl = env('WA_API_URL');
        $accountId = env('WA_ACCOUNT_ID', 'default');

        Log::info("Mengirim WhatsApp OTP ke {$to} (Gateway: {$gatewayType})");

        if (!$apiKey || !$apiUrl) {
            Log::error("Konfigurasi API WhatsApp belum diatur di file .env");
            return false;
        }

        try {
            if ($gatewayType === 'botwa') {
                $response = Http::withHeaders([
                    'x-api-token' => $apiKey,
                    'Accept' => 'application/json'
                ])->post($apiUrl, [
                    'to' => $to,
                    'message' => $message,
                    'accountId' => $accountId,
                ]);
            } else {
                $response = Http::withHeaders([
                    'Authorization' => $apiKey
                ])->post($apiUrl, [
                    'target' => $to,
                    'message' => $message,
                    'countryCode' => '62',
                ]);
            }

            if ($response->successful()) {
                Log::info("Pesan WhatsApp berhasil dikirim ke {$to} via {$gatewayType}");
                return true;
            } else {
                Log::error("Gagal mengirim WhatsApp via {$gatewayType}. Status: {$response->status()}, Response: " . $response->body());
                return false;
            }
        } catch (\Exception $e) {
            Log::error("Kesalahan jaringan saat mengirim WhatsApp via {$gatewayType}: " . $e->getMessage());
            return false;
        }
    }
}
