<?php
namespace App\Services;

use AfricasTalking\SDK\AfricasTalking;

class SmsService
{
    private $sms;

    public function __construct()
    {
        $username = $_ENV['AT_USERNAME'] ?? 'sandbox';
        $apiKey = $_ENV['AT_API_KEY'] ?? '';
        $AT = new AfricasTalking($username, $apiKey);
        $this->sms = $AT->sms();
    }

    public function send($to, $message, $from = null)
    {
        try {
            $options = [
                'to' => $to,
                'message' => $message,
            ];
            if ($from) {
                $options['from'] = $from;
            } else {
                $options['from'] = $_ENV['AT_SENDER_ID'] ?? '';
            }
            $result = $this->sms->send($options);
            return $result;
        } catch (\Exception $e) {
            error_log("SMS sending failed: " . $e->getMessage());
            return false;
        }
    }
}