<?php

namespace App\Services\Sms;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class BeemSmsService
{
    protected string $apiKey;
    protected string $secret;
    protected string $sender;

    public function __construct()
    {
        $settings = DB::table('settings')
            ->whereIn('key', [
                'beem_api_key',
                'beem_secret_key',
                'beem_sender_name',
            ])
            ->pluck('value', 'key');

        $this->apiKey = $settings['beem_api_key']     ?? '';
        $this->secret = $settings['beem_secret_key']  ?? '';
        $this->sender = $settings['beem_sender_name'] ?? '';
    }

    /**
     * Send SMS via Beem.
     */
    public function send(string $phone, string $message): void
    {
        if (! $this->apiKey || ! $this->secret || ! $this->sender) {
            // Credentials not configured – just skip silently
            return;
        }

        Http::withHeaders([
            'Authorization' => 'Basic ' . base64_encode($this->apiKey . ':' . $this->secret),
            'Content-Type'  => 'application/json',
        ])->post('https://apisms.beem.africa/v1/send', [
            'source_addr' => $this->sender,
            'encoding'    => 0,
            'schedule_time' => '',
            'message'     => $message,
            'recipients'  => [
                [
                    'recipient_id' => 1,
                    'dest_addr'    => $phone,
                ],
            ],
        ])->throw(); // will log in Laravel if fails
    }
}
