<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class BulkSmsIraqService
{
    protected string $baseUrl;
    protected string $apiKey;
    protected string $senderId;

    public function __construct()
    {
        $this->baseUrl = config('services.bulksms_iraq.gateway_url', 'https://gateway.standingtech.com/api/v4/sms/send');
        $this->apiKey = config('services.bulksms_iraq.api_key', '');
        $this->senderId = config('services.bulksms_iraq.sender_id', 'aman');
    }

    /**
     * إرسال OTP عبر واتساب إلى رقم الهاتف.
     * الرقم يُرسل بصيغة دولية مثل 9647501234567
     */
    public function sendOtpWhatsApp(string $recipient, string $code): array
    {
        $phone = $this->normalizePhone($recipient);

        $http = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->apiKey,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ]);

        // على Windows المحلي قد يحدث خطأ SSL - تعطيل التحقق للتطوير فقط
        if (!config('services.bulksms_iraq.verify_ssl', true)) {
            $http = $http->withOptions(['verify' => false]);
        }

        $response = $http->post($this->baseUrl, [
            'recipient' => $phone,
            'sender_id' => $this->senderId,
            'type' => 'whatsapp',
            'message' => $code,
            'lang' => 'en',
        ]);

        $body = $response->json() ?? [];
        Log::info('BulkSMS Iraq send OTP', [
            'recipient' => $phone,
            'status' => $response->status(),
            'body' => $body,
        ]);

        if (!$response->successful()) {
            $message = $this->extractErrorMessage(is_array($body) ? $body : []);
            return ['success' => false, 'message' => $message, 'code' => $body['code'] ?? null];
        }

        return ['success' => true, 'message' => 'تم الإرسال'];
    }

    /** استخراج رسالة خطأ نصية من استجابة BulkSMS (قد تكون message كائناً متداخلاً). */
    protected function extractErrorMessage(array $body): string
    {
        $msg = $body['message'] ?? $body['error'] ?? null;
        if (is_string($msg)) {
            return $msg;
        }
        if (is_array($msg) && isset($msg['message']) && is_string($msg['message'])) {
            return $msg['message'];
        }
        if (is_array($msg) && !empty($msg)) {
            return (string) reset($msg);
        }
        return 'فشل إرسال الرسالة';
    }

    protected function normalizePhone(string $phone): string
    {
        $phone = preg_replace('/\D/', '', $phone);
        if (strlen($phone) === 10 && (str_starts_with($phone, '07') || str_starts_with($phone, '01'))) {
            return '964' . substr($phone, 1);
        }
        if (strlen($phone) === 11 && str_starts_with($phone, '964')) {
            return $phone;
        }
        if (!str_starts_with($phone, '964')) {
            $phone = '964' . ltrim($phone, '0');
        }
        return $phone;
    }
}
