<?php

namespace Modules\User\Services;

use Illuminate\Support\Facades\Http;
use Exception;

class TaqnyatSmsService
{
    protected $apiUrl;
    protected $apiKey;
    protected $sender;

    public function __construct()
    {
        $this->apiUrl = env('TAQNYAT_API_URL', 'https://api.taqnyat.sa');
        $this->apiKey = env('TAQNYAT_API_KEY');
        $this->sender = env('TAQNYAT_SENDER');
    }

    public function sendSms(string $phone, string $message)
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type'  => 'application/json',
            ])->post("{$this->apiUrl}/v1/messages", [
                'recipients' => [$phone],
                'body'       => $message,
                'sender'     => $this->sender,
            ]);

            if ($response->failed()) {
                return [
                    'success' => false,
                    'message' => 'SMS sending failed',
                    'error'   => $response->json(),
                ];
            }

            return [
                'success' => true,
                'message' => 'SMS sent successfully',
                'response' => $response->json(),
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Exception occurred',
                'error'   => $e->getMessage(),
            ];
        }
    }
}
