<?php

declare(strict_types=1);

require_once __DIR__ . "/../vendor/autoload.php";
require_once __DIR__ . "/../config/africastalking.php";

use AfricasTalking\SDK\AfricasTalking;

class OTPService
{
    public static function sendOTP(string $phone, string $otp): array
    {
        try {

            // Hindura number ibe international format
            $phone = preg_replace('/\D/', '', $phone);

            if (strpos($phone, "250") !== 0) {
                $phone = "250" . ltrim($phone, "0");
            }

            $phone = "+" . $phone;

            $AT = new AfricasTalking(
                AT_USERNAME,
                AT_API_KEY
            );

            $sms = $AT->sms();

            $message = "Your SmartPrint verification code is: {$otp}. It expires in 10 minutes.";

            $result = $sms->send([
                "to" => $phone,
                "message" => $message
            ]);

            return [
                "success" => true,
                "response" => $result
            ];

        } catch (Exception $e) {

            return [
                "success" => false,
                "message" => $e->getMessage()
            ];

        }
    }
}