<?php
class SmsService
{
    private $account, $apiKey, $token, $url, $sc;

    public function __construct()
    {
        $paths = [__DIR__.'/../../env_loader.php', __DIR__.'/../env_loader.php'];
        foreach ($paths as $p) { if (file_exists($p)) { require_once $p; break; } }
        $this->account = env('SMS_ACCOUNT');
        $this->apiKey  = env('SMS_API_KEY');
        $this->token   = env('SMS_TOKEN');
        $this->url     = env('SMS_URL', 'https://api101.hablame.co/api/sms/v2.1/send/');
        $this->sc      = env('SMS_SC', '899991');
    }

    public function enviar($telefono, $mensaje)
    {
        if (!$this->account || !$this->apiKey) {
            return ['success' => false, 'response' => 'Credenciales no configuradas'];
        }
        $telefono = preg_replace('/[^0-9]/', '', $telefono);
        if (strlen($telefono) === 10 && $telefono[0] === '3') $telefono = '57' . $telefono;

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->url, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 20,
            CURLOPT_POSTFIELDS => [
                'account'=>$this->account, 'apiKey'=>$this->apiKey, 'token'=>$this->token,
                'toNumber'=>$telefono, 'sms'=>$mensaje, 'flash'=>'0', 'isPriority'=>1,
                'sc'=>$this->sc, 'request_dlvr_rcpt'=>0,
            ],
        ]);
        $resp = curl_exec($ch); $err = curl_error($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($err) { error_log('[SMS] '.$err); return ['success'=>false,'response'=>$err]; }
        return ['success' => ($code >= 200 && $code < 300), 'response' => $resp];
    }
}
