<?php

class SMSClient
{
    protected $apiBase;
    protected $apiKey;
    protected $sender;

    public function __construct()
    {
        $this->apiBase = SMS_API_BASE;
        $this->apiKey  = SMS_API_KEY;
        $this->sender  = SMS_SENDER;
    }

    /**
     * Normalize message for L2T API
     * Converts accented and special characters to plain GSM-compatible characters
     */
    protected function normalizeMessage($text)
    {
        $replacements = [
            '’' => "'", '‘' => "'", '“' => '"', '”' => '"',
            '('=>'[', ')'=>']', '&'=>'et', '%'=>'', '—'=>'-', '…'=>'...'
        ];

        // Replace defined characters
        $text = strtr($text, $replacements);

        // Keep safe French accented characters, remove other non-GSM
        $text = preg_replace('/[^A-Za-z0-9À-ÖØ-öø-ÿ \[\]\.\,\!\?\'"@\/-]/u', '', $text);

        return $text;
    }


    /**
     * Send SMS via L2T API
     */
    public function sendSMS($phone, $message)
    {
        if (empty($phone) || empty($message)) {
            return [
                'success' => false,
                'error'   => 'Phone or message empty'
            ];
        }

        // Normalize message and trim to max length
        $message = substr($this->normalizeMessage($message), 0, SMS_MAX_LENGTH);

        // Build query string
        $params = [
            'fct'    => 'sms',
            'key'    => $this->apiKey,
            'mobile' => $phone,
            'sms'    => $message,
            'sender' => $this->sender
        ];

        $url = $this->apiBase . '?' . http_build_query($params);

        // cURL request
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_CONNECTTIMEOUT => SMS_CURL_TIMEOUT,
            CURLOPT_TIMEOUT        => SMS_CURL_TIMEOUT,
        ]);

        $response  = curl_exec($ch);
        $errno     = curl_errno($ch);
        $err       = curl_error($ch);
        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        return [
            'success'    => ($errno === 0 && $httpCode === 200),
            'http_code'  => $httpCode,
            'payload'    => http_build_query($params),
            'response'   => $response,
            'curl_error' => $err
        ];
    }
}
