<?php

namespace App\Libraries\NotificationChannels;

use GuzzleHttp\Client;

/**
 * WhatsApp Business API adapter. Feature-flagged off by default via the
 * 'notification.whatsapp_enabled' setting (seeded to '0' in MasterSeeder)
 * since it requires a separate Meta Business API approval per merchant —
 * see 05-saas-architecture.md §9.
 */
class WhatsAppChannel implements NotificationChannelInterface
{
    private ?Client $http;
    private string $phoneNumberId;
    private string $accessToken;

    public function __construct()
    {
        $this->phoneNumberId = env('whatsapp.phoneNumberId') ?? '';
        $this->accessToken   = env('whatsapp.accessToken') ?? '';
        $this->http = ($this->phoneNumberId && $this->accessToken) ? new Client() : null;
    }

    public function send(string $recipient, ?string $subject, string $body): bool
    {
        if (! $this->isEnabled()) {
            log_message('info', 'WhatsApp channel disabled or unconfigured — message not sent.');
            return false;
        }

        try {
            $response = $this->http->post("https://graph.facebook.com/v19.0/{$this->phoneNumberId}/messages", [
                'headers' => ['Authorization' => "Bearer {$this->accessToken}"],
                'json'    => [
                    'messaging_product' => 'whatsapp',
                    'to'                => $recipient,
                    'type'              => 'text',
                    'text'              => ['body' => $body],
                ],
            ]);
            return $response->getStatusCode() < 300;
        } catch (\Throwable $e) {
            log_message('error', 'WhatsApp send failed: ' . $e->getMessage());
            return false;
        }
    }

    private function isEnabled(): bool
    {
        if (! $this->http) {
            return false;
        }
        $setting = \Config\Database::connect()->table('settings')
            ->where('group', 'notification')->where('key', 'whatsapp_enabled')
            ->get()->getRow();
        return ($setting->value ?? '0') === '1';
    }
}
