<?php
// app/Libraries/WhatsappService.php
namespace App\Libraries;

/**
 * Service untuk menangani pengiriman pesan via WhatsApp Gateway.
 */
class WhatsappService
{
    protected string $apiUrl;
    protected string $apiKey;
    protected string $senderId;
    protected \CodeIgniter\HTTP\CURLRequest $client;

    public function __construct()
    {
        $this->apiUrl   = getenv('whatsapp.apiUrl');
        $this->apiKey   = getenv('whatsapp.apiKey');
        $this->senderId = getenv('whatsapp.senderId');

        $this->client = \Config\Services::curlrequest(['timeout' => 15]);
    }

    /**
     * Mengirim pesan berisi link verifikasi.
     */
    public function sendVerificationLink(string $recipientNumber, string $verificationLink): bool
    {
        // Render view 'whatsapp/verification_link.php' menjadi string
        $message = view('whatsapp/verification_link', [
            'verificationLink' => $verificationLink
        ]);

        return $this->send($recipientNumber, $message);
    }

    /**
     * Fungsi utama untuk mengirim pesan via API.
     */
    private function send(string $to, string $message): bool
    {
        if (empty($this->apiUrl) || empty($this->apiKey)) {
            log_message('error', 'WhatsApp API URL or API Key is not configured.');
            log_message('info', "[WhatsappService] MOCK SEND to {$to}: {$message}");
            return true;
        }

        $payload = ['to' => $to, 'message' => $message];

        try {
            $response = $this->client->post($this->apiUrl, [
                'headers' => ['Authorization' => 'Bearer ' . $this->apiKey, 'Content-Type'  => 'application/json'],
                'json' => $payload,
                'http_errors' => false
            ]);
            
            if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
                return true;
            }

            log_message('error', 'WhatsApp API Error: ' . $response->getBody());
            return false;

        } catch (\Exception $e) {
            log_message('error', 'CURLRequest to WhatsApp API failed: ' . $e->getMessage());
            return false;
        }
    }
}