<?php

namespace App\Services;

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

class NotifyLKService
{
    protected $userId;
    protected $apiKey;
    protected $senderId;

    public function __construct()
    {
        $this->userId = '27506'; // Configuration should ideally be in .env but using direct for now as requested
        $this->apiKey = '6LKxgZ9KXrHpyyKYqwkd';
        $this->senderId = null; // Use default if null
    }

    public function sendSMS($to, $message)
    {
        // Format mobile number: Ensure it starts with 94, remove leading 0 if present
        $to = $this->formatMobile($to);

        if (!$to) {
            Log::warning("NotifyLK: Invalid mobile number.");
            return false;
        }

        try {
            $response = Http::get('https://app.notify.lk/api/v1/send', [
                'user_id' => $this->userId,
                'api_key' => $this->apiKey,
                'sender_id' => $this->senderId ?? 'NotifyDEMO', // Or your sendername
                'to' => $to,
                'message' => $message
            ]);

            if ($response->successful()) {
                Log::info("NotifyLK: SMS sent to {$to}. Response: " . $response->body());
                return true;
            } else {
                Log::error("NotifyLK: Failed to send SMS to {$to}. Response: " . $response->body());
                return false;
            }
        } catch (\Exception $e) {
            Log::error("NotifyLK: Exception sending SMS to {$to}: " . $e->getMessage());
            return false;
        }
    }

    private function formatMobile($number)
    {
        // Remove non-numeric
        $number = preg_replace('/\D/', '', $number);
        
        // Check length
        if (strlen($number) === 9) { // e.g. 771234567
            return '94' . $number;
        } elseif (strlen($number) === 10 && str_starts_with($number, '0')) { // e.g. 0771234567
            return '94' . substr($number, 1);
        } elseif (strlen($number) === 11 && str_starts_with($number, '94')) { // e.g. 94771234567
            return $number;
        }
        
        return null; // Invalid
    }
}
