<?php

namespace App\Services;

use App\Models\GeneralSetting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SmsService
{
    private string $apiUrl = 'https://bulksmsbd.net/api/smsapi';
    private string $apiKey;
    private string $senderId;
    private ?string $lastError = null;

    public function __construct()
    {
        $settings = GeneralSetting::getContent();

        $this->apiKey = (string) ($settings['sms']['bulksmsbd_api_key'] ?? config('services.bulksmsbd.api_key', ''));
        $this->senderId = (string) ($settings['sms']['bulksmsbd_sender_id'] ?? config('services.bulksmsbd.sender_id', 'GPS'));
    }

    public function send(string $phone, string $message): bool
    {
        $this->lastError = null;

        if (app()->environment('local') && empty($this->apiKey)) {
            Log::info("[SmsService] DEMO mode - To: {$phone} | Msg: {$message}");
            return true;
        }

        try {
            $providerPhone = ltrim(trim($phone), '+');
            $response = Http::post($this->apiUrl, [
                'api_key' => $this->apiKey,
                'type' => 'text',
                'number' => $providerPhone,
                'senderid' => $this->senderId,
                'message' => $message,
            ]);

            $body = $response->json();
            $rawBody = trim((string) $response->body());
            $status = $response->status();

            Log::info('[SmsService] Response', [
                'status' => $status,
                'phone' => $providerPhone,
                'json' => $body,
                'raw' => $rawBody,
            ]);

            $accepted = isset($body['response_code']) && (int) $body['response_code'] === 202;
            if (! $accepted) {
                $this->lastError = $body['error_message']
                    ?? $body['message']
                    ?? ($rawBody !== '' ? $rawBody : "Provider rejected request (HTTP {$status}).");

                Log::warning('[SmsService] Provider rejected', [
                    'status' => $status,
                    'error' => $this->lastError,
                ]);
            }

            return $accepted;
        } catch (\Throwable $e) {
            $this->lastError = $e->getMessage();
            Log::error('[SmsService] Failed: ' . $this->lastError);
            return false;
        }
    }

    public function sendOtp(string $phone, string $otp): bool
    {
        $message = "Your GPS Migration verification code is: {$otp}. Valid for 5 minutes. Do not share this code.";
        return $this->send($phone, $message);
    }

    public static function generateOtp(): string
    {
        return str_pad((string) random_int(1000, 9999), 4, '0', STR_PAD_LEFT);
    }

    public function getLastError(): ?string
    {
        return $this->lastError;
    }
}
