<?php

namespace App\Services;

class SendWhatsappMessageService
{
    protected $service_api_key;
    protected $service_api_url;

    public function __construct()
    {
        $this->service_api_key = env('VITE_EVOLUTION_API_KEY');
        $this->service_api_url = env('VITE_EVOLUTION_API_URL');
    }
    public function sendMessage(string $to, string $message, string $mediaUrl = null): string
    {
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $this->service_api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => "{\n  \"number\": \"$to\",\n  \"text\": \"$message\",\n  \"delay\": 100\n}",
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "apikey: $this->service_api_key"
            ],
            CURLOPT_SSL_VERIFYPEER => false, 
            CURLOPT_SSL_VERIFYHOST => false 
        ]);


        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            throw new \Exception('CURL Error: ' . $err);
        }

        return $response;
    }
}
