<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http; // Added for Guzzle HTTP client
use App\Services\TaqnyatSmsService; // Ensure this is the correct namespace for TaqnyatSmsService

class SmsService
{
    protected $apiKey;
    protected $senderId;
    protected $baseUrl;
    private TaqnyatSmsService $service;

    public function __construct()
    {
        $this->apiKey = config('services.taqnyat.api_key');
        $this->senderId = config('services.taqnyat.sender_id', 'Mutamad');
        $this->service = new TaqnyatSmsService($this->apiKey);
    }

    /**
     * Send an SMS message.
     *
     * @param string $to The recipient's phone number.
     * @param string $message The message content.
     * @return bool True if the SMS was sent successfully, false otherwise.
     */
    public function send(string $to, string $message): bool
    {
        if (empty($this->apiKey)) {
            Log::error('MSEGAT SMS Service is not configured. Please set SMS_TAQNYAT_API_KEY in your .env file.');
            return false;
        }

        try {
            Log::info("Sending SMS to {$to}: {$message}");
            // Log::info("Sending SMS to {$to}: {$message} - {$this->service->senders()} - {$this->service->balance()}");
            $response = $this->service->sendMsg($message, [$to], $this->senderId);
            Log::info('MSEGAT SMS API Response:', ['response' => $response]);
            $jsonResponse = json_decode($response, true);
            Log::info('MSEGAT SMS API Response:', $jsonResponse);

            // Log the full response for debugging

            // Check MSEGAT specific response codes for success
            // Refer to MSEGAT API documentation for exact success codes
            // Example: '1' for success, '100' for success (older versions)
            if (isset($jsonResponse) && $jsonResponse['statusCode'] == 201 && $jsonResponse['accepted'] != "[]") {
                Log::info("SMS sent successfully to {$to}. Message: '{$message}'");
                return true;
            } else {
                Log::error("Failed to send SMS to {$to}. Message: '{$message}'. MSEGAT Response: " . json_encode(value: $response));
                return false;
            }
        } catch (\Exception $e) {
            Log::error("Exception when sending SMS to {$to}: " . $e->getMessage());
            return false;
        }
    }
}
