<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: modules/sms-plivo.php
// Description: Plivo 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 SmsPlivo implements ModuleInterface
{
    public function get_id(): string          { return 'sms-plivo'; }
    public function get_name(): string        { return 'Plivo'; }
    public function get_description(): string { return 'Affordable SMS delivery with straightforward pricing and solid deliverability. No monthly fees - pay only for what you send.'; }
    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_plivo_auth_id');
        delete_option('amai_plivo_auth_token');
        delete_option('amai_plivo_from_number');
    }

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

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

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

    public function send(string $to, string $body): bool
    {
        $auth_id = $this->auth_id();
        $token   = $this->auth_token();
        $from    = $this->from_number();

        if ($auth_id === '' || $token === '' || $from === '' || $to === '' || $body === '') {
            return false;
        }

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

        $url      = 'https://api.plivo.com/v1/Account/' . $auth_id . '/Message/';
        $payload  = ['src' => $from, 'dst' => $to, 'text' => $body];
        $response = wp_remote_post($url, [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode($auth_id . ':' . $token),
                'Content-Type'  => 'application/json',
            ],
            'body'    => (string) json_encode($payload),
            'timeout' => 15,
        ]);

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

        $code = (int) wp_remote_retrieve_response_code($response);
        return $code >= 200 && $code < 300;
    }

    // ------------------------------------------------------------------
    // 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 auth_id(): string
    {
        return (string) get_option('amai_plivo_auth_id', '');
    }

    private function auth_token(): string
    {
        return (string) get_option('amai_plivo_auth_token', '');
    }

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