<?php

declare(strict_types=1);

namespace PpPhp\Core;

class SMS
{
    private static array $config = [];
    private static string $provider = '';
    private static array $availableDrivers = [];

    // ── Initialisation ────────────────────────────────────────────────

    public static function init(): void
    {
        if (!empty(self::$availableDrivers)) return;
        self::scanCustomDrivers();
    }

    /**
     * Scan plugins/SmsDrivers/ for any class implementing SmsDriver.
     * Each file is loaded once; the key is the lowercased file name.
     */
    private static function scanCustomDrivers(): void
    {
        $dir = constant('BASE_PATH') . '/plugins/SmsDrivers/';
        if (!is_dir($dir)) return;

        foreach (scandir($dir) as $file) {
            if ($file === '.' || $file === '..') continue;
            if (!str_ends_with($file, '.php')) continue;

            $className = 'PpPhp\\Plugins\\SmsDrivers\\' . substr($file, 0, -4);
            if (class_exists($className)) {
                $driver = new $className();
                if ($driver instanceof SmsDriver) {
                    $key = strtolower(substr($file, 0, -4));
                    self::$availableDrivers[$key] = $driver;
                }
            }
        }
    }

    // ── Configuration ─────────────────────────────────────────────────

    public static function SetConfig(array $config): void
    {
        self::$config = array_merge(self::$config, $config);
        self::$provider = $config['provider'] ?? self::$provider;
    }

    public static function GetDrivers(): array
    {
        self::init();
        return self::$availableDrivers;
    }

    // ── Send ──────────────────────────────────────────────────────────

    public static function Send(string $to, string $message): array
    {
        self::init();
        $provider = self::$provider ?: (self::$config['provider'] ?? '');

        if (empty($provider)) {
            return ['success' => false, 'error' => 'No SMS provider selected.'];
        }

        $driver = self::$availableDrivers[$provider] ?? null;
        if (!$driver) {
            return ['success' => false, 'error' => "Driver not found for provider '{$provider}'."];
        }

        return $driver->send(self::normaliseNumber($to), $message, self::$config);
    }

    private static function normaliseNumber(string $number): string
    {
        $number = trim($number);
        if (str_starts_with($number, '+')) return $number;
        return '+' . ltrim($number, '0');
    }

    public static function RegisterCustomProvider(string $key, SmsDriver $driver): void
    {
        self::init();
        self::$availableDrivers[$key] = $driver;
    }
}
