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

use AutoMarketerAI\ModuleInterface;

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

final class SmsTwilio implements ModuleInterface
{
    public function get_id(): string          { return 'sms-twilio'; }
    public function get_name(): string        { return 'Twilio'; }
    public function get_description(): string { return 'Twilio sends your text messages. Trusted by thousands of businesses worldwide, it\'s simple to set up and charges only for what you send - no monthly fees.'; }
    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_twilio_account_sid');
        delete_option('amai_twilio_auth_token');
        delete_option('amai_twilio_from_number');
    }

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

    public function is_ready(): bool
    {
        return $this->account_sid() !== ''
            && $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
    {
        $sid   = $this->account_sid();
        $token = $this->auth_token();
        $from  = $this->from_number();

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

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

        $url      = 'https://api.twilio.com/2010-04-01/Accounts/' . $sid . '/Messages.json';
        $response = wp_remote_post($url, [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode($sid . ':' . $token),
                'Content-Type'  => 'application/x-www-form-urlencoded',
            ],
            'body'    => [
                'From' => $from,
                'To'   => $to,
                'Body' => $body,
            ],
            'timeout' => 15,
        ]);

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

        return (int) wp_remote_retrieve_response_code($response) === 201;
    }

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

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

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