#!/usr/bin/perl

use strict;
use warnings;
use POSIX;
use JSON;
use WWW::Curl::Easy;


   my $sndCode = sendSms( "10.0.66.104", "1144255139", "Hola Ale", 23, "admin:pepito20", 66 );
   print( $sndCode );


sub sendSms {

	my $ip = $_[0];
	my $number = $_[1];
	my $text = $_[2];
	my $port = $_[3];
	my $auth = $_[4];
	my $id = $_[5];

	my $url = sprintf( "%s/api/send_sms", $ip ); 
	my $postfields = { port => [$port],
							 text => $text,
				          request_status_report => 1,
				          param => [{number=>$number,user_id=>int($id)}]
						  };

#    {"text":"num","port":[23],"request_status_report":true,"param":[{"number":"321","user_id":123}]}
#    {"request_status_report":1,"text":"Hola Ale","port":23,"param":{"number":"1144255139","user_id":66}}

   my $jsonEncoded = encode_json( $postfields );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   printf ("%s\n", $retcode );
   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
      printf ("%s\n", $response_code );
     	if( $response_code == 200 ) {
         printf ("%s\n", $response_body );
        	my $resultSend = decode_json($response_body);
         printf ("%s\n", $resultSend );
			return $resultSend;
     	}
   }
	return "";
}
