<?php
//__NM____NM__FUNCTION__NM__//
	class WhatsAppAPI {
    private $base_url;

    public function __construct($base_url) {
        $this->base_url = $base_url;
    }
  
    private function sendRequest($url, $payload = null, $method = 'POST') {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); // Tiempo de espera de 5 segundos
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        }
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($http_code == 200) {
            $result = json_decode($response, true);
            if (is_array($result) && isset($result['status'])) {
                return $result;
            } else {
                throw new Exception("Failed: " . $result['response']);
            }
        } elseif ($curl_error) {
            if (strpos($curl_error, 'timed out') !== false) {
                throw new Exception("El servidor no está iniciado o está fuera de línea.");
            } elseif (strpos($curl_error, 'Failed to connect') !== false) {
                throw new Exception("Error: No se pudo conectar al servidor en " . $url);
            } else {
                throw new Exception("Error: $curl_error");
            }
        } else {
            throw new Exception("Error: $http_code, Response: $response");
        }
    }
	
    private function sendRequest_old($url, $payload) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
		curl_setopt($ch, CURLOPT_TIMEOUT,7);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code == 200) {
            $result = json_decode($response, true);
            if (is_array($result) && isset($result['status'])) {
                return $result;
            } else {
                throw new Exception("Failed: " . $result['response']);
            }
        } else {
            throw new Exception("Error: $http_code, Response: $response");
        }
    }

    public function sendMessage($from_number, $to_number, $message, $message_type, $file_name = null, $file_path = null) {
        $url = $this->base_url . "/send-message";
        $payload = array(
            "fromNumber" => $from_number,
            "number" => $to_number,
            "message" => $message,
            "type" => $message_type,
            "fileName" => $file_name,
            "base64File" => null
        );

        if ($file_path) {
            $file_content = file_get_contents($file_path);
            $encoded_file = base64_encode($file_content);
            $payload["base64File"] = $encoded_file;
        }

        return $this->sendRequest($url, $payload);
    }

    public function getGroups($from_number) {
        $url = $this->base_url . "/groups";
        $payload = array("fromNumber" => $from_number);
        return $this->sendRequest($url, $payload);
    }

    public function manageNumberGroup($group_id, $number, $action_type, $from_number) {
        $url = $this->base_url . "/numbergroup";
        $payload = array(
            "groupId" => $group_id,
            "number" => $number,
            "type" => $action_type,
            "fromNumber" => $from_number
        );
        return $this->sendRequest($url, $payload);
    }

    public function validateNumber($number, $from_number) {
        $url = $this->base_url . "/validate";
        $payload = array(
            "number" => $number,
            "fromNumber" => $from_number
        );
        return $this->sendRequest($url, $payload);
    }

    public function createConnection($number, $type) {
        $url = $this->base_url . "/create-connection";
        $payload = array("number" => $number, "type" => $type);
        return $this->sendRequest($url, $payload);
    }    

    public function logout($number) {
        $url = $this->base_url . "/logout";
        $payload = array("number" => $number);
        return $this->sendRequest($url, $payload);
    }
}
?>