<?php

namespace Modules\MedNotify\Services\Channels;

use App\Utils\NotificationUtil;

/**
 * SMS channel — reuses the ERP's own SMS pathway (Util::sendSms, inherited by
 * NotificationUtil), driven by the business sms_settings, exactly like
 * NotificationUtil::autoSendNotification. Nexmo / Twilio / generic HTTP gateway
 * all resolve inside sendSms(); we never re-implement any transport.
 */
class SmsChannel implements ChannelContract
{
    public function send(array $message, array $recipient, array $context): array
    {
        try {
            $mobile = $recipient['mobile'] ?? null;
            if (empty($mobile)) {
                return ['status' => 'skipped', 'error' => 'no mobile number'];
            }

            $business = $context['business'] ?? null;
            $smsSettings = $business ? $business->sms_settings : [];
            if (empty($smsSettings)) {
                return ['status' => 'skipped', 'error' => 'sms not configured'];
            }

            $data = [
                'sms_settings'  => $smsSettings,
                'mobile_number' => $mobile,
                'sms_body'      => $message['body'] ?? '',
            ];

            (new NotificationUtil())->sendSms($data);

            return ['status' => 'sent', 'error' => null];
        } catch (\Throwable $e) {
            \Log::warning('MedNotify SmsChannel failed: ' . $e->getMessage());

            return ['status' => 'failed', 'error' => $e->getMessage()];
        }
    }
}
