<?php
class MY_Controller extends CI_Controller{    
    public function __construct(){        
        parent::__construct();  
        $tiempoInicio = time();
        session_start();
        $_SESSION["tiempoInicio"] = $tiempoInicio;
        $_SESSION["tiempoConfirmacion"] = time();
    }
}


class Other_Controller extends CI_Controller {
    public function __construct(){        
        parent::__construct();
        $tiempoInicio = time();
        session_start();
        $_SESSION["tiempoInicio"] = $tiempoInicio;
        $_SESSION["tiempoConfirmacion"] = time();
    }

    public function setPauseStatus()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $pausa = $_POST["codigo"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=pause_code&value=" . $pausa;
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }

    }

    public function getStatusesSelect() {
        include_once RUTA_APP.'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            header('Content-type: application/json');
            include_once RUTA_APP.'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            $campana = $_SESSION["Campana"];

            if ($cliente !=-1) {
                $donde = "AND user_group = '$cliente'";
            }

            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde";
            $result = mysqli_query($con,$query);
            if ($row = mysqli_fetch_array($result)) {
                $query = "SELECT pause_code, pause_code_name FROM vicidial_pause_codes WHERE campaign_id = '$campana' ORDER BY pause_code";                
                $result = mysqli_query($con,$query);
                $donde = 0;
                $sal["Registros"] = array();
                $sal["Estado"] = "ok";
                while ($row = mysqli_fetch_array($result)) {
                    $sal["Registros"][$donde]["estado"] = $row["pause_code"];
                    $sal["Registros"][$donde]["nombre"] = $row["pause_code_name"];
                    $donde++;
                }
            }else{
                $sal["Estado"] = "error";
                $sal["Descripcion"] = "Usted no tiene los permisos necesarios para ver los estados de pausa en la campaña seleccionada";
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        }else{
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = "No tiene los permisos necesarios para esta accion";
            $this->output->set_output(json_encode($sal));
        }
    }

    public function getDispoSelect()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $con = getConnection();
            $query = "SELECT status,status_name,scheduled_callback FROM vicidial_statuses WHERE selectable = 'Y' UNION SELECT status,status_name,scheduled_callback FROM vicidial_campaign_statuses WHERE selectable = 'Y' AND campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = mysqli_query($con, $query);
            $sal = array();
            $sal["Registros"] = array();
            $cuenta = 0;
            while ($row = mysqli_fetch_assoc($result)) {
                $sal["Registros"][] = $row;
            }
            $query = "SELECT local_call_time FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = mysqli_query($con, $query);
            $row = mysqli_fetch_array($result);
            $sal["Horario"] = $row["local_call_time"];
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        }
    }
    public function getUrl()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $con = getConnection();
            $query = "SELECT web_form_address FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = mysqli_query($con, $query);
            $url = "";
            if ($row = mysqli_fetch_array($result)) {
                $url = $row["web_form_address"];
            }

            $strA = "--A--";
            $strB = "--B--";
            $sal = array();
            $x = file_get_contents(URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status");
            $array = ["status", "call_id", "lead_id", "campaign_id", "calls_today", "full_name", "user_group", "user_level", "pause_code", "real_time_sub_status", "phone_number", "vendor_lead_code", "session_id"];
            $actual = array();
            for ($i = 0; $i < sizeof($array); $i++) {
                $actual[$i] = "";
            }

            $j = 0;
            $urlNueva = "";
            $index = 0;
            if (substr($url, 0, 3) == "VAR") {
                $sal["esVariable"] = true;
                $index = 3;
            } else {
                $sal["esVariable"] = false;
                $urlNueva = $url;
            }
            for ($i = 0; $i < strlen($x); $i++) {
                $a = $x[$i];
                if ($a == "|") {
                    $j++;
                } else {
                    $actual[$j] .= $a;
                }
            }

            $query = "SELECT * FROM vicidial_list WHERE lead_id = '" . $actual[2] . "' LIMIT 1";
            $result = mysqli_query($con, $query);
            if ($row = mysqli_fetch_assoc($result)) {
                $array = array_values($array);
                $claves = array_keys($row);
                $claves = array_values($claves);
                $ts = array_merge($array, $claves);
                $array = $ts;
                $actual = array_values($actual);
                $row = array_values($row);
                $ts2 = array_merge($actual, $row);
                $actual = $ts2;

            }
            for ($i = 0; $i < count($array); $i++) {
                $actual[$i] = str_replace("\n", "", $actual[$i]);
            }
            $urlNueva = substr($url, 3);
            if ($sal["esVariable"]) {
                for ($i = 0; $i < count($array); $i++) {
                    $strxD = "--A--" . $array[$i] . "--B--";
                    $urlNueva = str_replace($strxD, $actual[$i], $urlNueva);
                }
            }
            //echo($actual[array_search("campaign_id",$array)]);
            /*while ($index < strlen($url) && $index > 1) {
            if (substr($url, $index, strlen($strA)) == $strA) {
            $index += strlen($strA);
            $vara = "";
            while (substr($url, $index, strlen($strB)) != $strB) {
            $vara .= $url[$index];
            $index += 1;
            }
            $urlNueva .= $actual[array_search($vara, $array)];
            $index += strlen($strB);
            } else {
            $urlNueva .= $url[$index];
            $index += 1;
            }
            }*/
            $sal["Estado"] = "ok";
            $sal["url"] = $urlNueva;
            $this->output->set_output(json_encode($sal));
        }
    }
    public function espera()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $val = $_POST["Val"];
            if ($val == 1) {
                $val = "PARK_CUSTOMER";
            } else {
                $val = "GRAB_CUSTOMER";
            }
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=park_call&value=$val";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }

    }
    public function getUrl2()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $con = getConnection();
            $query = "SELECT web_form_address_two FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = mysqli_query($con, $query);
            $url = "";
            if ($row = mysqli_fetch_array($result)) {
                $url = $row["web_form_address_two"];
            }

            $strA = "--A--";
            $strB = "--B--";
            $x = file_get_contents(URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status");

            $array = ["status", "call_id", "lead_id", "campaign_id", "calls_today", "full_name", "user_group", "user_level", "pause_code", "real_time_sub_status", "phone_number", "vendor_lead_code", "session_id"];
            $actual = array();
            for ($i = 0; $i < sizeof($array); $i++) {
                $actual[$i] = "";
            }

            $j = 0;
            $urlNueva = "";
            $index = 0;
            $sal = array();
            if (substr($url, 0, 3) == "VAR") {
                $index = 3;
                $sal["esVariable"] = true;
            } else {
                $urlNueva = $url;
                $sal["esVariable"] = false;
            }
            for ($i = 0; $i < strlen($x); $i++) {
                $a = $x[$i];
                if ($a == "|") {
                    $j++;
                } else {
                    $actual[$j] .= $a;
                }
            }
            $sal["array"] = $array;
            $sal["actual"] = $actual;
            $query = "SELECT * FROM vicidial_list WHERE lead_id = '" . $actual[2] . "' LIMIT 1";
            $result = mysqli_query($con, $query);
            if ($row = mysqli_fetch_assoc($result)) {
                $array = array_values($array);
                $claves = array_keys($row);
                $claves = array_values($claves);
                $ts = array_merge($array, $claves);
                $array = $ts;
                $actual = array_values($actual);
                $row = array_values($row);
                $ts2 = array_merge($actual, $row);
                $actual = $ts2;

            }
            for ($i = 0; $i < count($array); $i++) {
                $actual[$i] = str_replace("\n", "", $actual[$i]);
            }
            $urlNueva = substr($url, 3);
            if ($sal["esVariable"]) {
                for ($i = 0; $i < count($array); $i++) {
                    $strxD = "--A--" . $array[$i] . "--B--";
                    $urlNueva = str_replace($strxD, $actual[$i], $urlNueva);
                }
            }

            $sal["Estado"] = "ok";
            $sal["url"] = $urlNueva;
            $this->output->set_output(json_encode($sal));
        }
    }
    public function logout()
    {
        if (!empty($_SESSION["Usuario"])) {
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=logout&value=LOGOUT";
            echo (file_get_contents($url));
        }
        if (!empty($_SESSION["Usuario"])) {
            session_destroy();
        }
        header('Location: ' . MODULOS . 'login');
    }
    public function index()
    {
        if (!empty($_SESSION["Usuario"])) {
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=logout&value=LOGOUT";
            file_get_contents($url);
            $this->load->view('homeAgente/head');
            $this->load->view('homeAgente/top_nav_agent');
            $this->load->view('homeAgente/vw_home');
            $this->load->view('homeAgente/foot');
        } else {
            $this->logout();

        }
    }
    public function llamadaInicial()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=call_agent&value=CALL";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function sendDTMF()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $dtmf = $_POST["dtmf"];
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=send_dtmf&value=$dtmf";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function pause()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_pause&value=PAUSE";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function play()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_pause&value=RESUME";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
                $sal["URL"] = $url;
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function manualDial()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = "";
            if (isset($_POST["MAN"])) {
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_dial&value=MANUALNEXT&phone_code=52&search=YES&preview=NO&focus=NO";
            } else {
                $telefono = $_POST["numero"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_dial&value=$telefono&phone_code=52&search=YES&preview=NO&focus=NO";
            }

            $text = file_get_contents($url);
            $sal = array();
            $sal["url"] = $url;
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function localCloserTransfer()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $tipo=1;
            if(isset($_POST["tipo"]))
            {
                $tipo=$_POST["tipo"];
            }
            
            $url = "";
            if ($tipo==1) {
                $value=$_POST["valor"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=LOCAL_CLOSER&ingroup_choices=$value";
            } elseif($tipo==2){
                $value=$_POST["valor"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=LOCAL_CLOSER&ingroup_choices=AGENTDIRECT&phone_number=$value";
            }else{
                
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=LOCAL_CLOSER&ingroup_choices=DEFAULTINGROUP";
            }

            $text = file_get_contents($url);
            $sal = array();
            $sal["url"] = $url;
            $sal["text"]=$text;
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function rate()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = $_SESSION["Campana"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $valor = urlencode($_POST["valor"]);
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_status&value=$valor";
            if ($_POST["tieneCallBack"] == 1) {
                $callback_datetime = urlencode($_POST["callback"]);
                $callback_comments = urlencode($_POST["comentarios"]);
                $callback_type = urlencode($_POST["tipo"]);
                $url .= "&callback_type=$callback_type&callback_datetime=$callback_datetime&callback_comments=$callback_comments";
            }
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
                $con = getConnection();
                $result = mysqli_query($con, "SELECT * FROM vicidial_callbacks WHERE STRCMP('" . date("Y-m-d G:i:s") . "',callback_time)>=0 AND user='$usuario' AND recipient='USERONLY' AND campaign_id='$campana' AND callback_id NOT IN (SELECT callback_id FROM vicidial_callbacks_showed WHERE vicidial_callbacks_showed.callback_id=vicidial_callbacks.callback_id) ORDER BY callback_time ASC LIMIT 1");
                $sal["URL"] = "SELECT * FROM vicidial_callbacks WHERE STRCMP('" . date("Y-m-d G:i:s") . "',callback_time)>=0 AND user='$usuario' AND recipient='USERONLY' AND campaign_id='$campana' AND callback_id NOT IN (SELECT callback_id FROM vicidial_callbacks_showed WHERE vicidial_callbacks_showed.callback_id=vicidial_callbacks.callback_id) ORDER BY callback_time ASC LIMIT 1";
                if (sv_mysqli_num_rows($result)) {
                    $sal["Callback"] = mysqli_fetch_array($result);
                    $result = mysqli_query($con, "SELECT phone_number FROM vicidial_list WHERE lead_id='" . $sal["Callback"]["lead_id"] . "'");
                    $row = mysqli_fetch_array($result);
                    $sal["Callback"]["numero"] = $row["phone_number"];
                    mysqli_query($con, "INSERT INTO vicidial_callbacks_showed(callback_id) VALUES('" . $sal["Callback"]["callback_id"] . "')");
                    $sal["conCall"] = true;
                } else {
                    $sal["conCall"] = false;
                }
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function agentesParaTransferir()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana=$_SESSION["Campana"];
            $cliente=$_SESSION["Cliente"];
            $con=getConnection();
            $query="SELECT V.user FROM vicidial_live_agents AS V,vicidial_users AS U WHERE V.user!='$usuario' AND V.user=U.user AND U.user_group LIKE '%$cliente%'";
            $sal = array();
            $sal["Registros"]=array();
            $result=mysqli_query($con,$query);
            while($row=mysqli_fetch_assoc($result))
            {
                $sal["Registros"][]=$row["user"];
            }
            $sal["Estado"]="ok";
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }

    }
    
    public function cuelga()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_hangup&value=1";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    //Esto fue pedido porque los agentes de GDJ son unos inutiles y pidieron esto
    public function ayudaSoyUnInutil()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con=getConnection();
            $query="INSERT INTO ayuda(usuario) VALUES('$usuario')";
            if(mysqli_query($con,$query))
            {
                $sal["Estado"]="ok";
            }
            else{
                $sal["Estado"]="error";
                $sal["Descripcion"]=mysqli_error($con);
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        }
    }
    /*public function status(){
    if(!empty($_SESSION["Usuario"])){

    $usuario = $_SESSION["Usuario"];
    $apiUser = USER_API;
    $apiPass = PASS_API;
    $url = URL_DIALVOX."/agc/api.php?source=cli&user=".$apiUser."&pass=".$apiPass."&agent_user=".$usuario."&function=external_hangup&value=1&phone_code=55&search=YES&preview=NO&focus=YES";
    echo(file_get_contents($url));
    }
    }*/
    public function dejaGrabar()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=recording&value=STOP&phone_code=55&search=YES&preview=NO&focus=NO";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function graba()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=recording&value=START&phone_code=55&search=YES&preview=NO&focus=NO";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getStatus()
    {
        require_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status";
            $sal = array();
            $text = file_get_contents($url);
            $keys = ["Estado", "IdLlamada", "Registro", "Campana", "Llamadas", "Nombre", "GrupoUsuario", "NivelUsuario", "EstadoPausa", "SubEstado", "NumeroTelefonico", "VendorLead", "Sesion"];
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $keys = ["Descripcion", "otro"];
            } else {
                $sal["Estado"] = "ok";
            }
            $actual = [];
            for ($i = 0; $i < sizeof($keys); $i++) {
                $actual[$i] = "";
            }

            $j = 0;
            for ($i = 0; $i < strlen($text); $i++) {
                $a = $text[$i];
                if ($a == "|") {
                    $sal[$keys[$j]] = $actual[$j];
                    $j++;
                } else {
                    $actual[$j] .= $a;
                }
            }

            if ($sal["Estado"] == "ok") {
                $query = "SELECT comments, TIMESTAMPDIFF(SECOND,vicidial_live_agents.last_state_change,NOW()) as dif,(SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) as nomCampa,(SELECT active FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) AS campActiva FROM vicidial_live_agents WHERE user = '$usuario' LIMIT 1";
                $result = mysqli_query($con, $query);
                $row = mysqli_fetch_array($result);
                $sal["Tiempo"] = $row["dif"];
                $sal["Campana"] = $row["nomCampa"];
                $sal["campActiva"] = $row["campActiva"];
                if ($row["comments"] === "INBOUND") {
                    $sal["tipoLlamada"] = "Inbound";
                } else {
                    $sal["tipoLlamada"] = "Outbound ";

                }
                $query = "SELECT count(*) AS CUENTA from vicidial_auto_calls where callerid='" . $sal["call_id"] . "'";
                $rslt = mysqli_query($con, $query);
                $row = mysqli_fetch_array($rslt);
                $AcalleridCOUNT = $row["CUENTA"];
                if ($AcalleridCOUNT < 1 && $sal["status"] == "INCALL") {
                    $sal["Cuelga"] = false;
                } else {
                    $sal["Cuelga"] = false;
                }
            }
            $sal[$keys[$j]] = $actual[$j];
            $this->output->set_output(json_encode($sal));
        }
    }
    public function makeLOG()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $file=fopen($_SESSION["Usuario"]."-".date("d-m-Y-H-i-s").".csv","w");
            $sal=array();
            $sal["Estado"] = "ok";
            if($file===FALSE)
            {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = "No se pudo guardar el log";

            }
            else
            {
                fputcsv($file,explode(",","TiempoDispo,ventanas,allow_beep,Manual,btnActual,time_beep,time_repeat,salio,otraFlag,puedoPoner,flag,flagStatus,banderitaCRM,vuelveCheck,aPasado,dialvoxCRM,Usuario,statusCalificacion,cronometro,TiempoTot,statusPausa,enGrabacion,enLlamada,puedoEnviarDTMF,otraFlag,enEspera,enTransferido,aTransferir,banderaCRM,banderaCRM2,status,real_time_sub_status,URL1,URL2,Fecha y Hora"));
                $tamano=count($_POST["logs"]);
                for($i=0;$i<$tamano;$i++)
                {
                    $sal["POST"]=$_POST;
                    if($i==0)
                    {
                        array_push($_POST["logs"][$i],$_POST["texto"]);
                    }
                    fputcsv($file,$_POST["logs"][$i]);
                }
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
            if($file!==FALSE)
            {
                fclose($file);
            }
        }

    }
    public function transferir()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $codigos = array(
                "EXPULSAR" => "HANGUP_XFER",
                "A_CIEGAS" => "BLIND_TRANSFER",
                "NORMAL" => "DIAL_WITH_CUSTOMER",
                "ESPERA" => "PARK_CUSTOMER_DIAL",
                "ABANDONAR" => "LEAVE_3WAY_CALL"
            );
            $value = $_POST["tipo"];
            $value = $codigos[$value];
            $url = "";
            if (isset($_POST["numero"])) {
                $phone_number = $_POST["numero"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=$value&phone_number=$phone_number";
            } else {
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=$value";
            }

            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
                
            }
            $sal["text"]=$text;
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function saveCallback(){
        $response = array(
            "Estado" => "error",
            "Mensaje" => "No has iniciado sesion"
        );
        if (!empty($_SESSION["Usuario"])) 
        {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';
            $user = $_SESSION["Usuario"];
            $group = $_SESSION["Grupo"];
            $campaign = $_SESSION["Campana"];

            $con = getConnection();

            $callback_time = date("Y-m-d H:i:s", strtotime($_POST["callback_time"]));
            $comments = limpia($_POST["comments"]);
            $recipient = limpia($_POST["recipient"]);
            $lead_id = limpia($_POST["lead_id"]);
            
            if ($recipient === "ANYONE") 
            {
                $user = "";
            }

            $query = "SELECT list_id FROM vicidial_list WHERE lead_id=$lead_id";
            $result = mysqli_query($con, $query);
            $row = mysqli_fetch_assoc($result);
            $list_id = $row["list_id"];

            $query = "INSERT INTO vicidial_callbacks (lead_id,list_id,campaign_id,status,entry_time,callback_time,user,recipient,comments,user_group) VALUES ($lead_id, $list_id, $campaign,'INACTIVE', current_timestamp(),'$callback_time','$user','$recipient','$comments','$group')";

            $result = mysqli_query($con, $query);

            if ($result === FALSE) 
            {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } 
            else 
            {
                $response = array(
                    "Estado" => "ok",
                    "Mensaje" => "Callback registrado correctamente"
                );
                $response["CallbackId"] = (string) mysqli_insert_id($con);
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    public function deleteCallback(){
        $response = array(
            "Estado" => "error",
            "Mensaje" => "No has iniciado sesion"
        );
        if (!empty($_SESSION["Usuario"])) 
        {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';

            $con = getConnection();

            $callback_id = $_POST["id"];

            $query = "DELETE FROM vicidial_callbacks WHERE callback_id=$callback_id";

            $result = mysqli_query($con, $query);

            if ($result === FALSE) 
            {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } 
            else 
            {
                $response["Estado"] = "ok";
                $response["Mensaje"] = "Callback eliminado correctamente";
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    public function assignCallback(){
        $response = array(
            "Estado" => "error",
            "Mensaje" => "No has iniciado sesion"
        );
        if (!empty($_SESSION["Usuario"])) 
        {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';
            $user = $_SESSION["Usuario"];

            $con = getConnection();
            $query = "SELECT callback_id,comments,lead_id,callback_time,(SELECT phone_number FROM vicidial_list WHERE lead_id=vicidial_callbacks.lead_id) as phone_number FROM vicidial_callbacks WHERE user='' AND status='INACTIVE' LIMIT 1";

            $result = mysqli_query($con, $query);

            if ($result === FALSE) 
            {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } 
            else if (sv_mysqli_num_rows($result) === 0) 
            {
                $response["Estado"] = "ok";
                $response["Mensaje"] = "No hay callbacks por asignar";
                $response["CallbackId"] = "none";
            } 
            else 
            {
                $row = mysqli_fetch_assoc($result);
                $CallbackId = (string) $row["callback_id"];
                $CallbackComments = $row["comments"];
                $CallbackPhoneNumber = $row["phone_number"];
                $CallbackLead = $row["lead_id"];
                $CallbackTime = $row["callback_time"];

                $query = "UPDATE vicidial_callbacks SET user='$user' WHERE callback_id=$CallbackId";
                $result = mysqli_query($con, $query);

                if ($result === FALSE) 
                {
                    $response["Mensaje"] = mysqli_error($con);
                    $response["Query"] = $query;
                } 
                else 
                {
                    $response = array(
                        "Estado" => "ok",
                        "CallbackId" => $CallbackId,
                        "CallbackComments" => $CallbackComments,
                        "CallbackPhoneNumber" => $CallbackPhoneNumber,
                        "CallbackLead" => $CallbackLead,
                        "CallbackTime" => $CallbackTime,
                        "Mensaje" => "Callback asignado correctamente"
                    );
                }
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    public function getCallbacks(){
        $response = array(
            "Estado" => "error",
            "Mensaje" => "No has iniciado sesion"
        );
        if (!empty($_SESSION["Usuario"])) 
        {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';
            $user = $_SESSION["Usuario"];

            $con = getConnection();
            $query = "SELECT callback_id,comments,lead_id,callback_time,(SELECT phone_number FROM vicidial_list WHERE lead_id=vicidial_callbacks.lead_id) as phone_number FROM vicidial_callbacks WHERE user='$user' AND status='INACTIVE' LIMIT 1";

            $result = mysqli_query($con, $query);

            if ($result === FALSE) 
            {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } 
            else if (sv_mysqli_num_rows($result) === 0) 
            {
                $response["Estado"] = "ok";
                $response["Mensaje"] = "No hay callbacks por asignar";
                $response["Callbacks"] = array();
            } 
            else
            {
                $response["Estado"] = "ok";
                $response["Callbacks"] = array();
                $array_count = 0;
                while($row = mysqli_fetch_assoc($result))
                {
                    $response["Callbacks"][] = array();
                    $response["Callbacks"][$array_count]["Id"] = (string) $row["callback_id"];
                    $response["Callbacks"][$array_count]["Comments"] = $row["comments"];
                    $response["Callbacks"][$array_count]["PhoneNumber"] = $row["phone_number"];
                    $response["Callbacks"][$array_count]["Lead"] = $row["lead_id"];
                    $response["Callbacks"][$array_count]["Time"] = $row["callback_time"];
                    $array_count++;
                }
                $response["Mensaje"] = "Callbacks obtenidos exitosamente";
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    public function campanas() {
        require_once RUTA_APP . 'Conexion.php';
        $con = getConnection();
        $user = limpia($_POST['user']);
        $pass = limpia($_POST['pass']);
        $query = "SELECT user_group FROM vicidial_users  WHERE BINARY user = '$user' AND BINARY pass = '$pass' AND active = 'Y' LIMIT 1";
        $result = mysqli_query($con, $query);
        $salida = array();
        if ($row = mysqli_fetch_assoc($result)) {
            $salida["Estado"] = "Ok";
            $grupo = $row["user_group"];
            $salida["Campanas"] = array();
            $cliente = "";
            $a = strpos($grupo, "_");
            $salida["Tipo"] = GRUPO_AGENTES;
            if (strpos($grupo, GRUPO_ADMINS) !== false) {
                $salida["Tipo"] = GRUPO_ADMINS;
            }

            if (strpos($grupo, GRUPO_AGENTES) !== false) {
                $salida["Tipo"] = GRUPO_AGENTES;
            }

            if (strpos($grupo, GRUPO_SUPERVISORES) !== false) {
                $salida["Tipo"] = GRUPO_ADMINS;
            }

            if ($a === false) {
                $cliente = -1;
            } else {
                $cliente = "";
                for ($i = $a - 1; $i >= 0; $i--) {
                    $cliente .= $grupo[$i];
                }
                $cliente = strrev($cliente);
            }
            $and = "";
            if ($cliente != -1) {
                //$and = "AND (user_group = '".$cliente."_".GRUPO_ADMINS."' OR user_group = '---ALL---')";
                $and = "AND user_group = '" . $cliente . "'";
            }
            $query = "SELECT campaign_id, campaign_name FROM vicidial_campaigns WHERE active = 'Y' $and";
            $result = mysqli_query($con, $query);
            $i = 0;
            while ($row = mysqli_fetch_array($result)) {
                $salida["Campanas"][$i]["id"] = $row["campaign_id"];
                $salida["Campanas"][$i]["nombre"] = $row["campaign_name"];
                $i++;
            }
            $query = "SELECT dialplan_number FROM phones WHERE BINARY extension = '$user' AND BINARY pass = '$pass'";
            $result = mysqli_query($con, $query);
            if ($row = mysqli_fetch_array($result)) {
                $salida["Nueva"] = true;
            } else {
                $salida["Nueva"] = false;
            }
        } else {
            $salida["Estado"] = "Error";
        }
        sv_mysqli_close($con);
        header('Content-type: application/json');
        //ob_clean();
        //print(json_encode($salida));
        $this->output->set_output(json_encode($salida));
    }


}


?>