<?php

namespace App\Libraries\NotificationChannels;

use GuzzleHttp\Client;

/**
 * Gateway-agnostic SMS sender. Configured against any Twilio-compatible
 * REST API (Twilio itself, or a local Pakistani SMS gateway that mirrors
 * the same request shape) via sms.* env settings — swap providers without
 * touching NotificationService.
 */
class SmsChannel implements NotificationChannelInterface
{
    private ?Client $http;
    private string $apiUrl;
    private string $apiKey;
    private string $senderId;

    public function __construct()
    {
        $this->apiUrl   = env('sms.apiUrl') ?? '';
        $this->apiKey   = env('sms.apiKey') ?? '';
        $this->senderId = env('sms.senderId') ?? 'JobPortal';
        $this->http     = $this->apiUrl ? new Client() : null;
    }

    public function send(string $recipient, ?string $subject, string $body): bool
    {
        if (! $this->http) {
            log_message('warning', 'SMS channel not configured (sms.apiUrl missing) — message not sent.');
            return false;
        }

        try {
            $response = $this->http->post($this->apiUrl, [
                'headers' => ['Authorization' => "Bearer {$this->apiKey}"],
                'json'    => ['to' => $recipient, 'from' => $this->senderId, 'body' => $body],
            ]);
            return $response->getStatusCode() < 300;
        } catch (\Throwable $e) {
            log_message('error', 'SMS send failed: ' . $e->getMessage());
            return false;
        }
    }
}
