<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: modules/sms-vonage.php
// Description: Vonage SMS provider module - NUCLEAR+++
// Last Edited: 2026-05-14
// ==================================================
namespace AutoMarketerAI\Modules;

use AutoMarketerAI\ModuleInterface;

if (!defined('ABSPATH')) {
    exit('No direct script access allowed.');
}

final class SmsVonage implements ModuleInterface
{
    public function get_id(): string          { return 'sms-vonage'; }
    public function get_name(): string        { return 'Vonage'; }
    public function get_description(): string { return 'Enterprise-grade SMS with global reach and full Canadian support. Ideal for growing businesses that need reliable delivery at scale.'; }
    public function get_category(): string    { return 'SMS'; }
    public function get_logo_url(): string          { return ''; }
    public function get_model_count(): int          { return 0; }
    public function get_available_models(): array    { return []; }
    public function get_single_model_notice(): string { return ''; }
    public function get_api_key_prefix(): string      { return ''; }
    public function validate_api_key(string $key): bool { return true; }
    public function generate_raw(string $prompt, string $api_key, string $model): string { return ''; }
    public function is_free_allowed(): bool   { return false; }
    public function register(): void          {}
    public function activate(): void          {}
    public function deactivate(): void
    {
        delete_option('amai_vonage_api_key');
        delete_option('amai_vonage_api_secret');
        delete_option('amai_vonage_from_number');
    }

    // ------------------------------------------------------------------
    // Check whether this provider is configured and ready to send
    // ------------------------------------------------------------------

    public function is_ready(): bool
    {
        return $this->api_key() !== ''
            && $this->api_secret() !== ''
            && $this->from_number() !== '';
    }

    // ------------------------------------------------------------------
    // Send a single SMS message
    // Returns true on success, false on failure
    // ------------------------------------------------------------------

    public function send(string $to, string $body): bool
    {
        $key    = $this->api_key();
        $secret = $this->api_secret();
        $from   = $this->from_number();

        if ($key === '' || $secret === '' || $from === '' || $to === '' || $body === '') {
            return false;
        }

        $to = $this->normalize_phone($to);
        if ($to === '') {
            return false;
        }

        // Vonage expects E.164 without leading +
        $to = ltrim($to, '+');

        $payload  = [
            'api_key'    => $key,
            'api_secret' => $secret,
            'from'       => $from,
            'to'         => $to,
            'text'       => $body,
        ];
        $response = wp_remote_post('https://rest.nexmo.com/sms/json', [
            'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
            'body'    => $payload,
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        if ($code < 200 || $code >= 300) {
            return false;
        }

        $body_raw = wp_remote_retrieve_body($response);
        $data     = json_decode($body_raw, true);
        if (!is_array($data) || empty($data['messages'][0]['status'])) {
            return false;
        }

        return (string) $data['messages'][0]['status'] === '0';
    }

    // ------------------------------------------------------------------
    // Normalize phone number to E.164 format
    // ------------------------------------------------------------------

    private function normalize_phone(string $phone): string
    {
        $phone = trim($phone);
        if ($phone === '') {
            return '';
        }

        if (str_starts_with($phone, '+')) {
            $digits = '+' . preg_replace('/\D/', '', substr($phone, 1));
            return strlen($digits) >= 8 ? $digits : '';
        }

        $digits = preg_replace('/\D/', '', $phone);
        if (strlen($digits) === 10) {
            return '+1' . $digits;
        }
        if (strlen($digits) === 11 && str_starts_with($digits, '1')) {
            return '+' . $digits;
        }

        return '';
    }

    // ------------------------------------------------------------------
    // Credential accessors
    // ------------------------------------------------------------------

    private function api_key(): string
    {
        return (string) get_option('amai_vonage_api_key', '');
    }

    private function api_secret(): string
    {
        return (string) get_option('amai_vonage_api_secret', '');
    }

    private function from_number(): string
    {
        return (string) get_option('amai_vonage_from_number', '');
    }
}