<?php

declare(strict_types=1);

namespace App\Modules\Messaging;

/**
 * MessageDeliveryService — Generates WhatsApp Deep Links, sanitizes phone inputs,
 * and abstracts future messaging channel extensions (email, SMS, APIs).
 *
 * No SQL database queries, no HTML generation.
 *
 * @package Inveetaire
 * @ref     PILOT-006
 */
class MessageDeliveryService
{
    /**
     * Sanitize a phone number into international wa.me numeric string format.
     * Removes symbols, leading + sign, and maps Indonesian "08" to "628".
     *
     * @param string $phone
     * @return string Sanitized numeric phone string.
     */
    public function sanitizePhone(string $phone): string
    {
        $cleaned = preg_replace('/[^0-9]/', '', $phone);

        // Convert leading local "0" to Indonesian country code "62"
        if (strpos($cleaned, '0') === 0) {
            $cleaned = '62' . substr($cleaned, 1);
        }

        return $cleaned;
    }

    /**
     * Generate a WhatsApp wa.me deep link.
     *
     * @param string $phone
     * @param string $message Compiled personalized message body.
     * @return string Link format: https://wa.me/{phone}?text={urlencoded_message}
     */
    public function generateWhatsAppUrl(string $phone, string $message): string
    {
        $sanitizedPhone = $this->sanitizePhone($phone);
        $encodedMessage = rawurlencode($message);

        return "https://wa.me/{$sanitizedPhone}?text={$encodedMessage}";
    }
}
