<?php

namespace App\Services;

use App\Models\Communication;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;

class SmsService
{
    protected string $url;
    protected ?string $apiKey;
    protected ?string $username;
    protected ?string $senderId;

    public function __construct()
    {
        $this->url = config('services.hostpinnacle.url', 'https://sms.hostpinnacle.co.ke/api/single');
        $this->apiKey = config('services.hostpinnacle.api_key');
        $this->username = config('services.hostpinnacle.username');
        $this->senderId = config('services.hostpinnacle.sender_id');
    }

    /**
     * Send an SMS to the specified phone number.
     */
    public function send(string $phone, string $message, ?int $applicationId = null, ?int $sentById = null): array
    {
        // Fallback to logged-in user if not provided
        $sentById = $sentById ?? (Auth::check() ? Auth::id() : null);

        // Normalize phone number to format expected by API (usually 254...)
        $normalizedPhone = $this->normalizeForSms($phone);

        Log::info("SMS sending to {$normalizedPhone}: {$message}");

        $status = 'sent';
        $responseDetails = [];

        // Check if credentials exist, otherwise simulate
        if ($this->apiKey && $this->username && $this->senderId) {
            try {
                $response = Http::post($this->url, [
                    'username' => $this->username,
                    'apikey' => $this->apiKey,
                    'sender' => $this->senderId,
                    'mobile' => $normalizedPhone,
                    'message' => $message,
                ]);

                if ($response->successful()) {
                    $responseDetails = $response->json() ?? [];
                    $status = 'delivered';
                } else {
                    $status = 'failed';
                    $responseDetails = ['error' => $response->body()];
                    Log::error("Hostpinnacle SMS API failed: " . $response->body());
                }
            } catch (\Exception $e) {
                $status = 'failed';
                $responseDetails = ['error' => $e->getMessage()];
                Log::error("Hostpinnacle SMS exception: " . $e->getMessage());
            }
        } else {
            // Simulated Success when API credentials are not set
            $responseDetails = ['info' => 'Simulated SMS send. Configure services.hostpinnacle in config/services.php for live API.'];
            $status = 'delivered';
        }

        // Log to DB
        if ($applicationId) {
            Communication::create([
                'application_id' => $applicationId,
                'channel' => 'sms',
                'direction' => 'outbound',
                'message' => $message,
                'sent_by' => $sentById,
                'status' => $status,
                'sent_at' => Carbon::now(),
            ]);
        }

        return [
            'success' => $status === 'delivered',
            'status' => $status,
            'details' => $responseDetails,
        ];
    }

    /**
     * Ensure phone is in format e.g. 2547XXXXXXXX
     */
    protected function normalizeForSms(string $phone): string
    {
        $phone = preg_replace('/[^0-9]/', '', $phone);
        
        if (str_starts_with($phone, '0') && strlen($phone) === 10) {
            return '254' . substr($phone, 1);
        }
        
        if (str_starts_with($phone, '7') && strlen($phone) === 9) {
            return '254' . $phone;
        }

        return $phone;
    }
}
