<?php if (!defined('BASEPATH')) exit('No direct script access allowed');


class Nvoip {
    private $user = "30107001";
    private $tokken = "8d3a5e2edcb449d31347829f72d3c90c1d1de";
    //private $url = "https://private-anon-ce2529ca25-nvoip.apiary-mock.com/v1/calls";
    private $url = "https://api.nvoip.com.br/v1/calls";
    
    function __construct() 
    {
        $this->CI =& get_instance();
    }
    
    function ligar($origem = NULL, $destino = NULL){

        if($origem == NULL || $destino == NULL){
            return FALSE;
        }
        
        $post = ['caller' => $origem, 'called' => $destino];
        $chamada = $this->curl($this->url,$post);
        
        if($chamada['state'] == 'received' || $chamada['state'] == 'success'){
            return $this->status($chamada['callId']);
        }else{
            return NULL;
        }
    }
    
    function status($callID){
        if($callID != NULL){
            return $this->curl($this->url.'/'.$callID,[]);
        }
        return FALSE;
    }
    
    function desligar($callID){
        if($callID != NULL){
            $post = ['callId' => $callID];
            return $this->curl($this->url.'/endcall',$post);
        }
        return FALSE;
    }
    
    function curl($curlUrl, $post_vars){
        $headers = Array();
        $headers[] = "Content-Type: application/json";
        $headers[] = "token_auth: ".$this->tokken;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $curlUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_vars));
        /*curl_setopt($ch, CURLOPT_POSTFIELDS, "{
          \"caller\": \"30107001\",
          \"called\": \"61993017989\"
        }");*/
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $result = curl_exec($ch);
        
        $output = json_decode($result, true);
                	
        return $output;
    }
    
    /*public function curl(){
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, "https://api.nvoip.com.br/v1/calls");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        
        curl_setopt($ch, CURLOPT_POST, TRUE);
        
        curl_setopt($ch, CURLOPT_POSTFIELDS, "{
          \"caller\": \"30107001\",
          \"called\": \"61993017989\"
        }");
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          "Content-Type: application/json",
          "token_auth: 8d3a5e2edcb449d31347829f72d3c90c1d1de"
        ));
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        var_dump($response);
    }*/
}