<?php
declare(strict_types=1);
namespace App\Services;

use App\Repositories\SettingRepository;

final class WhatsAppService {
    public function __construct(private ?SettingRepository $settings = null) {
        $this->settings ??= new SettingRepository();
    }

    public function isConfigured(): bool {
        return $this->settings->get('ultra_instance_id') !== '' && $this->settings->get('ultra_token') !== '';
    }

    public function renderTemplate(string $template, array $vars): string {
        $map = [];
        foreach ($vars as $k => $v) $map['{' . $k . '}'] = (string)$v;
        return strtr($template, $map);
    }

    public function send(string $phone, string $message): array {
        $phone = normalize_phone($phone);
        if ($phone === '') {
            return ['ok' => false, 'status' => 'invalid_phone', 'response' => 'Phone empty'];
        }
        if (!$this->isConfigured()) {
            return ['ok' => false, 'status' => 'not_configured', 'response' => 'UltraMsg settings missing'];
        }
        $instance = trim($this->settings->get('ultra_instance_id'));
        $token = trim($this->settings->get('ultra_token'));
        $url = 'https://api.ultramsg.com/' . rawurlencode($instance) . '/messages/chat';
        $payload = http_build_query([
            'token' => $token,
            'to' => $phone,
            'body' => $message,
        ]);
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_TIMEOUT => 20,
        ]);
        $response = (string)curl_exec($ch);
        $error = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($error !== '') {
            return ['ok' => false, 'status' => 'curl_error', 'response' => $error];
        }
        return ['ok' => $code >= 200 && $code < 300, 'status' => (string)$code, 'response' => $response];
    }
}
