<?php

namespace Instinctor\Core;

/**
 * One-way transactional SMS through the platform relay (Telnyx).
 * Shared by bookings + form inquiries + any other owner notification.
 * Standalone sites authenticate by site_url; the platform sends from its
 * shared number. Consent-gated (auto-true on standalone).
 */
class Sms
{
    /** Send an SMS. Returns true on relay success, false otherwise (never throws). */
    public static function send(string $to, string $message): bool
    {
        if (!PlatformConsent::granted()) {
            return false;
        }
        $to = self::normalize($to);
        if ($to === '') {
            return false;
        }
        $siteUrl = function_exists('home_url') ? home_url() : (defined('INSTINCTOR_STANDALONE_URL') ? INSTINCTOR_STANDALONE_URL : '');
        $response = wp_remote_post('https://platform.instinctor.com/api/relay/sms', [
            'body' => [
                'site_url'    => $siteUrl,
                'license_key' => (string) Config::get('instinctor_license_key', ''),
                'to'          => $to,
                'message'     => $message,
                'channel'     => 'sms',
            ],
            'timeout' => 15,
        ]);
        if (is_wp_error($response)) {
            // phpcs:disable WordPress.PHP.DevelopmentFunctions -- server-side error capture / one-time migration logging, not debug output.
            error_log('[Sms] relay error: ' . $response->get_error_message());
            // phpcs:enable WordPress.PHP.DevelopmentFunctions
            return false;
        }
        $code = wp_remote_retrieve_response_code($response);
        if ($code < 200 || $code >= 300) {
            // phpcs:disable WordPress.PHP.DevelopmentFunctions -- server-side error capture / one-time migration logging, not debug output.
            error_log('[Sms] relay HTTP ' . $code . ': ' . substr((string) wp_remote_retrieve_body($response), 0, 300));
            // phpcs:enable WordPress.PHP.DevelopmentFunctions
            return false;
        }
        return true;
    }

    /** Coerce any entered phone format to E.164 (+1...). Returns '' if implausible. */
    public static function normalize(string $raw): string
    {
        $raw     = trim($raw);
        $hasPlus = str_starts_with($raw, '+');
        $digits  = preg_replace('/\D+/', '', $raw);
        if ($hasPlus) {
            return strlen($digits) >= 8 ? '+' . $digits : '';
        }
        if (strlen($digits) === 10) {
            return '+1' . $digits;
        }
        if (strlen($digits) === 11 && $digits[0] === '1') {
            return '+' . $digits;
        }
        return strlen($digits) >= 8 ? '+' . $digits : '';
    }
}
