<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: includes/class-sms-provider.php
// Description: Static SMS provider dispatcher - routes send() calls to the active sms-* module - NUCLEAR+++
// Last Edited: 2026-05-11
// ==================================================
namespace AutoMarketerAI;

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

final class SmsProvider
{
    // ------------------------------------------------------------------
    // Return true if an SMS provider module is active and configured
    // ------------------------------------------------------------------

    public static function is_ready(): bool
    {
        $provider = self::get_active_provider();
        return $provider !== null && $provider->is_ready();
    }

    // ------------------------------------------------------------------
    // Send an SMS via the active provider
    // Returns true on success, false on failure or no provider
    // ------------------------------------------------------------------

    public static function send(string $to, string $body): bool
    {
        $provider = self::get_active_provider();
        if ($provider === null) {
            return false;
        }
        return $provider->send($to, $body);
    }

    // ------------------------------------------------------------------
    // Find and instantiate the first active sms-* module
    // ------------------------------------------------------------------

    private static function get_active_provider(): ?object
    {
        $active_modules = (array) get_option('amai_active_modules', []);
        $sms_ids        = array_filter(
            $active_modules,
            static fn($id) => is_string($id) && str_starts_with($id, 'sms-')
        );

        foreach ($sms_ids as $id) {
            $file = AMAI_PLUGIN_DIR . 'modules/' . $id . '.php';
            if (!is_file($file)) {
                continue;
            }
            require_once $file;
            // sms-twilio -> SmsTwilio, sms-vonage -> SmsVonage, etc.
            $suffix = ucfirst(str_replace('-', '', substr($id, 4)));
            $class  = '\\AutoMarketerAI\\Modules\\Sms' . $suffix;
            if (class_exists($class)) {
                return new $class();
            }
        }

        return null;
    }
}