<?php

require_once "BASEPATH.php";

class Usuarios extends MY_Controller
{
    public function trata(&$out, $arreglo, &$lastLinePrinted)
    {
        $llaves = array_keys($arreglo);
        //fputcsv($out,array_values($llaves));
        $llavesNoArreglos = array();
        for ($i = 0; $i < count($llaves); $i++) {
            if (!is_array($arreglo[$llaves[$i]])) {
                //$this->trata($out,$arreglo[$llaves[$i]]);
                $llavesNoArreglos[] = $llaves[$i];
            }
        }
        $temp = array();
        for ($i = 0; $i < count($llaves); $i++) {
            if (!is_array($arreglo[$llaves[$i]])) {
                $temp[] = $arreglo[$llaves[$i]];
            }
        }
        if (count($temp) > 0) {
            if ($llavesNoArreglos != $lastLinePrinted) {
                fputcsv($out, array_values($llavesNoArreglos));
                $lastLinePrinted = $llavesNoArreglos;
            }
            fputcsv($out, array_values($temp));
        }
        for ($i = 0; $i < count($llaves); $i++) {
            if (is_array($arreglo[$llaves[$i]])) {
                $temp2 = array();
                $temp2[0] = $llaves[$i];
                if (!is_numeric($temp2[0])) {
                    fputcsv($out, array_values($temp2));
                }

                $this->trata($out, $arreglo[$llaves[$i]], $lastLinePrinted);
            }
        }
    }
    public function ejectAgent()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $usuario = $_SESSION["Usuario"];
            $user = limpia($_POST["usuario"]);
            $sal = array();
            $con = getConnection();
            $cadena = '';
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $cadena = "AND user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "')";
            }
            $query = "SELECT user from vicidial_users where user='$user' $cadena limit 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $now_date_epoch = date('U');
                $inactive_epoch = ($now_date_epoch - 60);
                $stmt = "SELECT user,campaign_id,UNIX_TIMESTAMP(last_update_time) from vicidial_live_agents where user='$user'";
                $rslt = sv_mysqli_query($con, $stmt);
                $vla_ct = sv_mysqli_num_rows($rslt);
                if ($vla_ct > 0) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $VLA_user = $row[0];
                    $VLA_campaign_id = $row[1];
                    $VLA_update_time = $row[2];
                    if ($VLA_update_time > $inactive_epoch) {
                        $lead_active = 0;
                        $stmt = "SELECT agent_log_id,user,server_ip,event_time,lead_id,campaign_id,pause_epoch,pause_sec,wait_epoch,wait_sec,talk_epoch,talk_sec,dispo_epoch,dispo_sec,status,user_group,comments,sub_status,dead_epoch,dead_sec from vicidial_agent_log where user='$VLA_user' order by agent_log_id desc LIMIT 1;";
                        $rslt = sv_mysqli_query($con, $stmt);
                        $val_ct = sv_mysqli_num_rows($rslt);
                        if ($val_ct > 0) {
                            $row = sv_mysqli_fetch_array($rslt);
                            $VAL_agent_log_id = $row[0];
                            $VAL_user = $row[1];
                            $VAL_server_ip = $row[2];
                            $VAL_event_time = $row[3];
                            $VAL_lead_id = $row[4];
                            $VAL_campaign_id = $row[5];
                            $VAL_pause_epoch = $row[6];
                            $VAL_pause_sec = $row[7];
                            $VAL_wait_epoch = $row[8];
                            $VAL_wait_sec = $row[9];
                            $VAL_talk_epoch = $row[10];
                            $VAL_talk_sec = $row[11];
                            $VAL_dispo_epoch = $row[12];
                            $VAL_dispo_sec = $row[13];
                            $VAL_status = $row[14];
                            $VAL_user_group = $row[15];
                            $VAL_comments = $row[16];
                            $VAL_sub_status = $row[17];
                            $VAL_dead_epoch = $row[18];
                            $VAL_dead_sec = $row[19];
                            if (($VAL_wait_epoch < 1) or (($VAL_status == 'PAUSE') and ($VAL_dispo_epoch < 1))) {
                                $VAL_pause_sec = (($now_date_epoch - $VAL_pause_epoch) + $VAL_pause_sec);
                                $stmt = "UPDATE vicidial_agent_log SET wait_epoch='$now_date_epoch', pause_sec='$VAL_pause_sec' where agent_log_id='$VAL_agent_log_id'";
                            } else {
                                if ($VAL_talk_epoch < 1) {
                                    $VAL_wait_sec = (($now_date_epoch - $VAL_wait_epoch) + $VAL_wait_sec);
                                    $stmt = "UPDATE vicidial_agent_log SET talk_epoch='$now_date_epoch', wait_sec='$VAL_wait_sec' where agent_log_id='$VAL_agent_log_id';";
                                } else {
                                    $lead_active++;
                                    $status_update_SQL = '';
                                    if (((strlen($VAL_status) < 1) or ($VAL_status == 'NULL')) and ($VAL_lead_id > 0)) {
                                        $status_update_SQL = ", status='PU'";
                                        $stmt = "UPDATE vicidial_list SET status='PU' where lead_id='$VAL_lead_id';";
                                        $rslt = sv_mysqli_query($con, $stmt);
                                    }
                                    if ($VAL_dispo_epoch < 1) {
                                        $VAL_talk_sec = ($now_date_epoch - $VAL_talk_epoch);
                                        $stmt = "UPDATE vicidial_agent_log SET dispo_epoch='$now_date_epoch', talk_sec='$VAL_talk_sec'$status_update_SQL where agent_log_id='$VAL_agent_log_id';";
                                    } else {
                                        if ($VAL_dispo_sec < 1) {
                                            $VAL_dispo_sec = ($now_date_epoch - $VAL_dispo_epoch);
                                            $stmt = "UPDATE vicidial_agent_log SET dispo_sec='$VAL_dispo_sec' where agent_log_id='$VAL_agent_log_id';";
                                        }
                                    }
                                }
                            }
                            $rslt = sv_mysqli_query($con, $stmt);
                        }
                    }
                    $stmt = "DELETE from vicidial_live_agents where user='$user'";
                    $rslt = sv_mysqli_query($con, $stmt);
                    if (strlen($VAL_user_group) < 1) {
                        $stmt = "SELECT user_group FROM vicidial_users where user='$VLA_user';";
                        $rslt = sv_mysqli_query($con, $stmt);
                        $val_ct = sv_mysqli_num_rows($rslt);
                        if ($val_ct > 0) {
                            $row = sv_mysqli_fetch_array($rslt);
                            $VAL_user_group = $row[0];
                        }
                    }
                    $stmt = "INSERT INTO vicidial_user_log (user,event,campaign_id,event_date,event_epoch,user_group) values('$VLA_user','LOGOUT','$VLA_campaign_id',NOW(),'$now_date_epoch','$VAL_user_group');";
                    $rslt = sv_mysqli_query($con, $stmt);
                    $stmt = "SELECT enable_queuemetrics_logging,queuemetrics_server_ip,queuemetrics_dbname,queuemetrics_login,queuemetrics_pass,queuemetrics_log_id,queuemetrics_loginout,queuemetrics_addmember_enabled,queuemetrics_pe_phone_append FROM system_settings;";
                    $rslt = sv_mysqli_query($con, $stmt);
                    $qm_conf_ct = sv_mysqli_num_rows($rslt);
                    if ($qm_conf_ct > 0) {
                        $row = sv_mysqli_fetch_array($rslt);
                        $enable_queuemetrics_logging = $row[0];
                        $queuemetrics_server_ip = $row[1];
                        $queuemetrics_dbname = $row[2];
                        $queuemetrics_login = $row[3];
                        $queuemetrics_pass = $row[4];
                        $queuemetrics_log_id = $row[5];
                        $queuemetrics_loginout = $row[6];
                        $queuemetrics_addmember_enabled = $row[7];
                        $queuemetrics_pe_phone_append = $row[8];
                    }
                    if ($enable_queuemetrics_logging > 0) {
                        $QM_LOGOFF = 'AGENTLOGOFF';
                        if ($queuemetrics_loginout == 'CALLBACK') {
                            $QM_LOGOFF = 'AGENTCALLBACKLOGOFF';
                        }
                        $agents = '@agents';
                        $agent_logged_in = '';
                        $time_logged_in = '0';
                        if ($queuemetrics_loginout == 'NONE') {
                            $stmt = "INSERT INTO queue_log SET partition='P01',time_id='$now_date_epoch',call_id='NONE',queue='NONE',agent='Agent/" . $user . "',verb='PAUSEREASON',serverid='$queuemetrics_log_id',data1='LOGOFF';";
                            $rslt = sv_mysqli_query($con, $stmt);
                            $affected_rows = mysqli_affected_rows($linkB);
                        }
                        $stmtB = "SELECT agent,time_id,data1 FROM queue_log where agent='Agent/" . mysqli_real_escape_string($link, $user) . "' and verb IN('AGENTLOGIN','AGENTCALLBACKLOGIN') and time_id > $check_time order by time_id desc limit 1;";
                        $rsltB = sv_mysqli_query($con, $stmtB);
                        $qml_ct = sv_mysqli_num_rows($rsltB);
                        if ($qml_ct > 0) {
                            $row = sv_mysqli_fetch_array($rsltB);
                            $agent_logged_in = $row[0];
                            $time_logged_in = $row[1];
                            $RAWtime_logged_in = $row[1];
                            $phone_logged_in = $row[2];
                        }
                        $time_logged_in = ($now_date_epoch - $time_logged_in);
                        if ($time_logged_in > 1000000) {
                            $time_logged_in = 1;
                        }

                        if ($queuemetrics_addmember_enabled > 0) {
                            $queuemetrics_phone_environment = '';
                            $stmt = "SELECT queuemetrics_phone_environment FROM vicidial_campaigns where campaign_id='$VLA_campaign_id';";
                            $rslt = sv_mysqli_query($con, $stmt);
                            $cqpe_ct = sv_mysqli_num_rows($rslt);
                            if ($cqpe_ct > 0) {
                                $row = sv_mysqli_fetch_array($rslt);
                                $queuemetrics_phone_environment = $row[0];
                            }
                            $stmt = "SELECT distinct queue FROM queue_log where time_id >= $RAWtime_logged_in and agent='$agent_logged_in' and verb IN('ADDMEMBER','ADDMEMBER2') and queue != '$VLA_campaign_id' order by time_id desc;";
                            $rslt = sv_mysqli_query($con, $stmt);
                            $amq_conf_ct = sv_mysqli_num_rows($rslt);
                            $i = 0;
                            while ($i < $amq_conf_ct) {
                                $row = sv_mysqli_fetch_array($rslt);
                                $AMqueue[$i] = $row[0];
                                $i++;
                            }
                            $AMqueue[$i] = $VLA_campaign_id;
                            $i++;
                            $amq_conf_ct++;
                            $i = 0;
                            while ($i < $amq_conf_ct) {
                                $pe_append = '';
                                if (($queuemetrics_pe_phone_append > 0) and (strlen($queuemetrics_phone_environment) > 0)) {
                                    $qm_extension = explode('/', $phone_logged_in);
                                    $pe_append = "-$qm_extension[1]";
                                }
                                $stmt = "INSERT INTO queue_log SET partition='P01',time_id='$now_date_epoch',call_id='NONE',queue='$AMqueue[$i]',agent='$agent_logged_in',verb='REMOVEMEMBER',data1='$phone_logged_in',serverid='$queuemetrics_log_id',data4='$queuemetrics_phone_environment$pe_append';";
                                $rslt = sv_mysqli_query($con, $stmt);
                                $affected_rows = mysqli_affected_rows($linkB);
                                $i++;
                            }
                        }
                        if ($queuemetrics_loginout != 'NONE') {
                            $stmtB = "INSERT INTO queue_log SET partition='P01',time_id='$now_date_epoch',call_id='NONE',queue='NONE',agent='$agent_logged_in',verb='$QM_LOGOFF',serverid='$queuemetrics_log_id',data1='$phone_logged_in',data2='$time_logged_in';";
                            $rslt = sv_mysqli_query($con, $stmtB);
                        }
                    }
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_logueadoUsuarios");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosUsuariosEject");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function changeUserStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $user = limpia($_POST["usuario"]);
            $cadena = '';
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $cadena = "AND user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "')";
            }
            $query = "SELECT user from vicidial_users where user='$user' $cadena limit 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                if ($user == $usuario) {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_permisosUsuariosDisableSelf");
                } else {
                    $result = sv_mysqli_query($con, "SELECT active FROM vicidial_users WHERE user = '$user' LIMIT 1");
                    $row = sv_mysqli_fetch_array($result);
                    $nuevo = 'Y';
                    if ($row[0] == 'Y') {
                        $nuevo = 'N';
                    }
                    sv_mysqli_query($con, "UPDATE vicidial_users SET active = '$nuevo' WHERE user = '$user' LIMIT 1");
                    $sal["Estado"] = "ok";
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getInfoAgents()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sal = array();
            $campana = strtoupper(limpia($_POST["campana"]));
            $con = getConnection();
            $and = "";
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $and = "AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id AND user_group = '$cliente')";
            }
            $query = "SELECT status FROM vicidial_live_agents WHERE campaign_id = '$campana' $and AND campaign_id!='Robot'";
            $sal["queryShida"] = $query;
            $sal["agents_waiting"] = $sal["agents_paused"] = $sal["agents_in_dead_calls"] = $sal["agents_in_dispo"] = $sal["agents_in_calls"] = 0;
            $result = sv_mysqli_query($con, $query);
            $sal["nose"] = mysqli_error($con);
            while ($row = sv_mysqli_fetch_array($result)) {
                if ($row["status"] == "PAUSE") {
                    $sal["agents_paused"]++;
                }

                if ($row["status"] == "INCALL") {
                    $sal["agents_in_calls"]++;
                }

                if ($row["status"] == "DISPO") {
                    $sal["agents_in_dispo"]++;
                }

                if ($row["status"] == "READY") {
                    $sal["agents_waiting"]++;
                }

                if ($row["status"] == "DEAD") {
                    $sal["agents_in_dead_calls"]++;
                }
            }
            $query = "SELECT COUNT(auto_call_id) AS CUENTA,CONCAT(IF(HOUR(CURTIME())<10,CONCAT('0',HOUR(CURTIME())),HOUR(CURTIME())),':',IF(MINUTE(CURTIME())<10,CONCAT('0',MINUTE(CURTIME())),MINUTE(CURTIME()))) AS HORA FROM vicidial_auto_calls WHERE campaign_id = '$campana'";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $sal["llamadas_activas"] = $row["CUENTA"];
            $sal["hora"] = $row["HORA"];
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getUsers()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $pagina = $_POST["pagina"] - 1;
            $registros = 10;
            $skip = $pagina * $registros;
            $where = "";
            $textoBusqueda = "";
            if (isset($_POST["texto"])) {
                $textoBusqueda = limpia($_POST["texto"]);
            }
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $where = "user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "') AND";
            }
            $query = "SELECT user,full_name,user_group,user_level,active,pass,phone_login,phone_pass,closer_campaigns FROM vicidial_users WHERE $where (full_name LIKE '%$textoBusqueda%' OR user LIKE '%$textoBusqueda%') ORDER BY full_name LIMIT $skip,$registros";
            $con = getConnection();
            $result = sv_mysqli_query($con, $query);
            $salida = array();
            $cual = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $salida["usuarios"][$cual]["user"] = $row["user"];
                $salida["usuarios"][$cual]["active"] = $row["active"];
                $salida["usuarios"][$cual]["full_name"] = $row["full_name"];
                $salida["usuarios"][$cual]["user_group"] = $row["user_group"];
                $salida["usuarios"][$cual]["pass"] = $row["pass"];
                $salida["usuarios"][$cual]["closer_campaigns"] = $row["closer_campaigns"];
                $salida["usuarios"][$cual]["ranks"] = array();
                $query = "SELECT group_id,group_rank FROM vicidial_inbound_group_agents WHERE user = '" . $row["user"] . "'";
                $result2 = sv_mysqli_query($con, $query);
                while ($rowXD = sv_mysqli_fetch_array($result2)) {
                    $salida["usuarios"][$cual]["ranks"][] = $rowXD;
                }

                $result1 = sv_mysqli_query($con, $query);

                $query = "SELECT G.Grupo,G.id,A.idusuario_wa,A.allow_wa FROM dialvox_grupos AS G INNER JOIN dialvox_grupos_agentes AS A ON G.id = A.Grupo WHERE A.Usuario = '" . $row["user"] . "' LIMIT 1";
                $result1 = sv_mysqli_query($con, $query);
                $salida["usuarios"][$cual]["Grupo"] = array();
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $salida["usuarios"][$cual]["Grupo"]["Nombre"] = $row1["Grupo"];
                    $salida["usuarios"][$cual]["Grupo"]["id"] = $row1["id"];
                    if (NEED_WA && $_SESSION["allow_waCli"]) {
                        $salida["usuarios"][$cual]["Grupo"]["idUsuario_wa"] = $row1["idusuario_wa"];
                        $salida["usuarios"][$cual]["Grupo"]["allow_wa"] = $row1["allow_wa"];
                    }
                } else {
                    $salida["usuarios"][$cual]["Grupo"]["Nombre"] = "Ninguno";
                    $salida["usuarios"][$cual]["Grupo"]["id"] = -1;
                    if (NEED_WA && $_SESSION["allow_waCli"]) {
                        $salida["usuarios"][$cual]["Grupo"]["idUsuario_wa"] = "";
                        $salida["usuarios"][$cual]["Grupo"]["allow_wa"] = false;
                    }
                }
                $objeto["extension"] = $row["phone_login"];
                $objeto["password"] = $row["phone_pass"];
                $salida["usuarios"][$cual]["extension"] = $objeto;
                $salida["usuarios"][$cual]["extension"]["Nuevo"] = $row["phone_pass"] == $row["pass"] && $row["phone_login"] == $row["user"];
                $cliente = "";
                $grupo = $row["user_group"];
                $a = strpos($grupo, "_");
                for ($i = $a - 1; $i >= 0; $i--) {
                    $cliente .= $grupo[$i];
                }
                $cliente = strrev($cliente);
                $salida["usuarios"][$cual]["cliente"] = $cliente;
                $salida["usuarios"][$cual++]["user_level"] = $row["user_level"];
            }
            $query = "SELECT COUNT(user) AS Cuenta FROM vicidial_users WHERE $where (full_name LIKE '%$textoBusqueda%' OR user LIKE '%$textoBusqueda%')";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $salida["Cuenta"] = $row["Cuenta"];
            $salida["Estado"] = "ok";
            sv_mysqli_close($con);
            $this->output->set_output(json_encode($salida));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getUserSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $where = "";
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $where = "WHERE user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "')";
            }
            $query = "SELECT user,full_name FROM vicidial_users $where ORDER BY full_name";
            $con = getConnection();
            $result = sv_mysqli_query($con, $query);
            $salida = array();
            $cual = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $salida["usuarios"][$cual]["user"] = $row["user"];
                $salida["usuarios"][$cual++]["full_name"] = $row["full_name"];
            }
            $salida["Estado"] = "ok";
            sv_mysqli_close($con);
            $this->output->set_output(json_encode($salida));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }

    public function getAgentSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $where = "";
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $where = "WHERE user_group IN ('" . $cliente . "_" . GRUPO_AGENTES . "')";
            }
            $query = "SELECT user,full_name FROM vicidial_users $where ORDER BY full_name";
            $con = getConnection();
            $result = sv_mysqli_query($con, $query);
            $salida = array();
            $cual = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $salida["usuarios"][$cual]["user"] = $row["user"];
                $salida["usuarios"][$cual++]["full_name"] = $row["full_name"];
            }
            $salida["Estado"] = "ok";
            sv_mysqli_close($con);
            $this->output->set_output(json_encode($salida));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }

    public function getGroups()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $query = "SELECT user_group,group_name FROM vicidial_user_groups";
            $con = getConnection();
            $result = sv_mysqli_query($con, $query);
            $salida = array();
            $cual = 0;
            $salida["Estado"] = "ok";
            while ($row = sv_mysqli_fetch_array($result)) {
                $salida["grupos"][$cual]["id"] = $row["user_group"];
                $salida["grupos"][$cual]["nombre"] = $row["group_name"];
            }
            sv_mysqli_close($con);
            $this->output->set_output(json_encode($salida));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function deleteUser()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $salida = array();
            $user = limpia($_POST["usuario"]);
            $LOGadmin_viewable_groupsSQL = '';
            $usuario = $_SESSION["Usuario"];
            $cadena = '';
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $cadena = "AND user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "')";
            }
            $stmt = "SELECT user from vicidial_users where user='$user' $cadena limit 1";
            $result = sv_mysqli_query($con, $stmt);
            if ($row = sv_mysqli_fetch_array($result)) {
                if ($usuario == $user) {
                    $salida["Estado"] = "error";
                    $salida["Descripcion"] = $this->lang->line("desc_permisosUsuariosEditSelf");
                } else {
                    $stmtA = "DELETE from vicidial_users where user='$user' limit 1";
                    sv_mysqli_query($con, $stmtA);
                    $stmt = "DELETE from vicidial_campaign_agents where user='$user'";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_inbound_group_agents where user='$user'";
                    sv_mysqli_query($con, $stmt);
                    $SQL_log = "$stmtA|";
                    $SQL_log = preg_replace('/;/', '', $SQL_log);
                    $SQL_log = addslashes($SQL_log);
                    $ip = $_SERVER["REMOTE_ADDR"];
                    $stmt = "INSERT INTO vicidial_admin_log set event_date=NOW(), user='$usuario', ip_address='$ip', event_section='USERS', event_type='DELETE', record_id='$user', event_code='ADMIN DELETE USER', event_sql=\"$SQL_log\", event_notes=''";
                    sv_mysqli_query($con, $stmt);
                    sv_mysqli_query($con, "DELETE FROM phones WHERE extension = '$user'");
                    sv_mysqli_query($con, "DELETE FROM phones_alias WHERE alias_id = '$user'");
                    $query = "SELECT idusuario_wa FROM dialvox_grupos_agentes WHERE Usuario = '$user'";
                    $result = sv_mysqli_query($con, $query);
                    $row4 = sv_mysqli_fetch_array($result);
                    if ($row4 && $row4["idusuario_wa"] !== "") {
                        $url = (RUTA_WA . "/Usuario/delete");
                        $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "id" => $row4["idusuario_wa"]);
                        $options = array(
                            'http' => array(
                                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                'method' => 'POST',
                                'content' => http_build_query($data),
                            ),
                        );
                        $context = stream_context_create($options);
                        file_get_contents($url, false, $context);
                    }
                    $query = "DELETE FROM dialvox_grupos_agentes WHERE Usuario = '$user'";
                    sv_mysqli_query($con, $query);
                    $salida["Estado"] = "ok";
                }
            } else {
                $salida["Estado"] = "error";
                $salida["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            }
            sv_mysqli_close($con);
            $this->output->set_output(json_encode($salida));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function updateUser()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $con = getConnection();
            $salida = array();
            $user = limpia($_POST["usuario"]);
            $LOGadmin_viewable_groupsSQL = '';
            $usuario = $_SESSION["Usuario"];
            $cadena = '';
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $cadena = "AND user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "')";
            }
            $stmt = "SELECT user,user_level from vicidial_users where user='$user' $cadena limit 1";
            $result = sv_mysqli_query($con, $stmt);
            if ($row = sv_mysqli_fetch_array($result)) {
                if (1 != 1) {
                    $salida["Estado"] = "error";
                    $salida["Descripcion"] = $this->lang->line("desc_permisosUsuariosEditSelf");
                } else {
                    $pass = limpia($_POST["pass"]);
                    $phone_login = $user;
                    $phone_pass = $pass;
                    $user_group = limpia($_POST["user_group"]);
                    $full_name = limpia($_POST["full_name"]);
                    $user_level = $row[1];
                    $delete_users = 0;
                    $delete_user_groups = 0;
                    $delete_lists = 0;
                    $delete_campaigns = 0;
                    $delete_ingroups = 0;
                    $delete_remote_agents = 0;
                    $load_leads = 0;
                    $campaign_detail = 0;
                    $ast_admin_access = 0;
                    $ast_delete_phones = 0;
                    $delete_scripts = 0;
                    $modify_leads = 0;
                    $hotkeys_active = 0;
                    $change_agent_campaign = 0;
                    $agent_choose_ingroups = 1;
                    $closer_campaigns = '';
                    $scheduled_callbacks = 1;
                    $agentonly_callbacks = 0;
                    $agentcall_manual = 0;
                    $vicidial_recording = 1;
                    $vicidial_transfers = 1;
                    $delete_filters = 0;
                    $alter_agent_interface_options = 0;
                    $closer_default_blended = 0;
                    $delete_call_times = 0;
                    $modify_call_times = 0;
                    $modify_users = 0;
                    $modify_campaigns = 0;
                    $modify_lists = 0;
                    $modify_scripts = 0;
                    $modify_filters = 0;
                    $modify_ingroups = 0;
                    $modify_usergroups = 0;
                    $modify_remoteagents = 0;
                    $modify_servers = 0;
                    $view_reports = 0;
                    $vicidial_recording_override = 'DISABLED';
                    $alter_custdata_override = 'NOT_ACTIVE';
                    $qc_enabled = 0;
                    $qc_user_level = 1;
                    $qc_pass = 0;
                    $qc_finish = 0;
                    $qc_commit = 0;
                    $add_timeclock_log = 0;
                    $modify_timeclock_log = 0;
                    $delete_timeclock_log = 0;
                    $alter_custphone_override = 'NOT_ACTIVE';
                    $vdc_agent_api_access = 0;
                    $modify_inbound_dids = 0;
                    $delete_inbound_dids = 0;
                    $alert_enabled = 0;
                    $download_lists = 0;
                    $agent_shift_enforcement_override = 'DISABLED';
                    $manager_shift_enforcement_override = 0;
                    $shift_override_flag = 0;
                    $export_reports = 0;
                    $delete_from_dnc = 0;
                    $email = '';
                    $user_code = '';
                    $territory = '';
                    $allow_alerts = 0;
                    $agent_choose_territories = 1;
                    $custom_one = '';
                    $custom_two = '';
                    $custom_three = '';
                    $custom_four = '';
                    $custom_five = '';
                    $voicemail_id = '';
                    $agent_call_log_view_override = 'DISABLED';
                    $callcard_admin = 0;
                    $agent_choose_blended = 1;
                    $realtime_block_user_info = 0;
                    $custom_fields_modify = 0;
                    $force_change_password = 'N';
                    $agent_lead_search_override = 'NOT_ACTIVE';
                    $modify_shifts = 0;
                    $modify_phones = 0;
                    $modify_carriers = 0;
                    $modify_labels = 0;
                    $modify_statuses = 0;
                    $modify_voicemail = 0;
                    $modify_audiostore = 0;
                    $modify_moh = 0;
                    $modify_tts = 0;
                    $preset_contact_search = 'NOT_ACTIVE';
                    $modify_contacts = 0;
                    $modify_same_user_level = 1;
                    $admin_hide_lead_data = 0;
                    $admin_hide_phone_data = 0;
                    $agentcall_email = 0;
                    $modify_email_accounts = 0;
                    $alter_admin_interface_options = 1;
                    $max_inbound_calls = 0;
                    $modify_custom_dialplans = 0;
                    $wrapup_seconds_override = -1;
                    $modify_languages = 0;
                    $selected_language = 'default English';
                    $user_choose_language = 0;
                    $ignore_group_on_search = 0;
                    $api_list_restrict = 0;
                    $api_allowed_functions = 'ALL_FUNCTIONS';
                    $lead_filter_id = 'NONE';
                    $admin_cf_show_hidden = 0;
                    $agentcall_chat = 0;
                    $user_hide_realtime = 0;
                    $access_recordings = 0;
                    $modify_colors = 0;
                    $user_nickname = '';
                    $user_new_lead_limit = '-1';
                    $api_only_user = 0;
                    $modify_auto_reports = 0;
                    $modify_ip_lists = 0;
                    $ignore_ip_list = 0;
                    $ready_max_logout = -1;
                    $export_gdpr_leads = 0;
                    $pause_code_approval = 0;
                    $max_hopper_calls = 0;
                    $max_hopper_calls_hour = 0;
                    switch ($user_group) {
                        case GRUPO_AGENTES:
                            $user_level = 2;
                            break;
                        case GRUPO_ADMINS:
                            $user_level = 9;
                            break;
                        case GRUPO_SUPERVISORES:
                            $user_level = 8;
                            break;
                    }
                    $cliente = limpia($_POST["cliente"]);
                    if ($cliente) {
                        $user_group = $cliente . "_" . $user_group;
                    }

                    if ($user_level >= 0) {
                        $agent_choose_ingroups = 1;
                        $agent_choose_blended = 1;
                        $hotkeys_active = 0;
                        $scheduled_callbacks = 1;
                        $agentonly_callbacks = 1;
                        $agentcall_chat = 1;
                        $agentcall_manual = 1;
                        $vicidial_recording = 1;
                        $vicidial_transfers = 1;
                        $closer_default_blended = 1;
                        $user_choose_language = 1;
                        $vicidial_recording_override = "DISABLED";
                        /**
                        Valores Posibles:
                        DISABLED
                        NEVER
                        ONDEMAND
                        ALLCALS
                        ALLFORCE
                         */
                        $alter_custdata_override = "NOT_ACTIVE";
                        /**
                        Valores Posibles:
                        NOT_ACTIVE
                        ALLOW_ALTER
                         */
                        $alter_custphone_override = "NOT_ACTIVE";
                        /**
                        Valores Posibles:
                        NOT_ACTIVE
                        ALLOW_ALTER
                         */
                        $agent_shift_enforcement_override = "DISABLED";
                        /**
                        Valores Posibles:
                        OFF
                        START
                        ALL
                        DISABLED
                         */
                        $agent_call_log_view_override = "DISABLED";
                        /**
                        Y
                        N
                        DISABLED
                         */
                        $agent_lead_search_override = "NOT_ACTIVE";
                        /**
                        Valores Posibles:
                        NOT_ACTIVE
                        DISABLED
                        ENABLED
                        LIVE_CALL_INBOUND
                        LIVE_CALL_INBOUND_AND_MANUAL
                         */
                        $allow_alerts = 0;
                        /**
                        Valores Posibles:
                        1
                        0
                         */
                        $preset_contact_search = "NOT_ACTIVE";
                        /**
                        Valores Posibles:
                        NOT_ACTIVE
                        DISABLED
                         */
                        $max_inbound_calls = 0;
                        $max_hopper_calls = 0;
                        $max_hopper_calls_hour = 0;
                        $wrapup_seconds_override = -1;
                        $ready_max_logout = -1;
                    }
                    if ($user_level >= 8) {
                        $realtime_block_user_info = 0;
                        $admin_hide_lead_data = 0;
                        $admin_hide_phone_data = 0;
                        $ignore_group_on_search = 0;
                        $view_reports = 1;
                        $change_agent_campaign = 1;
                        $alter_agent_interface_options = 0;
                        $modify_users = 0;
                        $delete_users = 0;
                        $modify_usergroups = 0;
                        $delete_user_groups = 0;
                        $modify_lists = 0;
                        $delete_lists = 0;
                        $load_leads = 0;
                        $modify_leads = 0;
                        $export_gdpr_leads = 0;
                        $download_lists = 0;
                        $export_reports = 1;
                        $delete_from_dnc = 0;
                        $custom_fields_modify = 0;
                        $delete_campaigns = 0;
                        $modify_ingroups = 0;
                        $delete_ingroups = 0;
                        $modify_inbound_dids = 0;
                        $delete_inbound_dids = 0;
                        $modify_custom_dialplans = 0;
                        $modify_remoteagents = 0;
                        $delete_remote_agents = 0;
                        $modify_scripts = 0;
                        $delete_scripts = 0;
                        $modify_filters = 0;
                        $delete_filters = 0;
                        $ast_admin_access = 0;
                        $ast_delete_phones = 0;
                        $modify_call_times = 0;
                        $delete_call_times = 0;
                        $modify_servers = 0;
                        $modify_shifts = 0;
                        $modify_phones = 0;
                        $modify_carriers = 0;
                        $modify_labels = 0;
                        $modify_colors = 0;
                        $modify_languages = 0;
                        $modify_statuses = 0;
                        $modify_voicemail = 0;
                        $modify_audiostore = 0;
                        $modify_moh = 0;
                        $modify_tts = 0;
                        $modify_contacts = 0;
                        $callcard_admin = 0;
                        $add_timeclock_log = 0;
                        $modify_timeclock_log = 0;
                        $delete_timeclock_log = 0;
                        $manager_shift_enforcement_override = 0;
                        $pause_code_approval = 0;
                        $vdc_agent_api_access = 0;
                        $api_list_restrict = 0;
                        $api_allowed_functions = 'ALL_FUNCTIONS';
                        $api_only_user = 0;
                        $modify_same_user_level = 1;
                        $alter_admin_interface_options = 1;
                    }
                    if ($user_level >= 9) {
                        $realtime_block_user_info = 0;
                        $admin_hide_lead_data = 0;
                        $admin_hide_phone_data = 0;
                        $ignore_group_on_search = 0;
                        $view_reports = 1;
                        $change_agent_campaign = 1;
                        $alter_agent_interface_options = 1;
                        $modify_users = 1;
                        $delete_users = 1;
                        $modify_usergroups = 1;
                        $delete_user_groups = 1;
                        $modify_lists = 1;
                        $delete_lists = 1;
                        $load_leads = 1;
                        $modify_leads = 1;
                        $export_gdpr_leads = 0;
                        $download_lists = 1;
                        $export_reports = 1;
                        $delete_from_dnc = 1;
                        $custom_fields_modify = 1;
                        $delete_campaigns = 1;
                        $modify_ingroups = 1;
                        $delete_ingroups = 1;
                        $modify_inbound_dids = 1;
                        $delete_inbound_dids = 1;
                        $modify_custom_dialplans = 1;
                        $modify_remoteagents = 1;
                        $delete_remote_agents = 1;
                        $modify_scripts = 1;
                        $delete_scripts = 1;
                        $modify_filters = 1;
                        $delete_filters = 1;
                        $ast_admin_access = 1;
                        $ast_delete_phones = 1;
                        $modify_call_times = 1;
                        $delete_call_times = 1;
                        $modify_servers = 1;
                        $modify_shifts = 1;
                        $modify_phones = 1;
                        $modify_carriers = 1;
                        $modify_labels = 1;
                        $modify_colors = 1;
                        $modify_languages = 1;
                        $modify_statuses = 1;
                        $modify_voicemail = 1;
                        $modify_audiostore = 1;
                        $modify_moh = 1;
                        $modify_tts = 1;
                        $modify_contacts = 1;
                        $callcard_admin = 1;
                        $add_timeclock_log = 1;
                        $modify_timeclock_log = 1;
                        $delete_timeclock_log = 1;
                        $manager_shift_enforcement_override = 1;
                        $pause_code_approval = 1;
                        $vdc_agent_api_access = 0;
                        $api_list_restrict = 0;
                        $api_allowed_functions = 'ALL_FUNCTIONS';
                        $api_only_user = 0;
                        $modify_same_user_level = 1;
                        $alter_admin_interface_options = 1;
                    }
                    $queryShida = "UPDATE vicidial_users SET pass='$pass', user_group='$user_group', full_name='$full_name',user_level='$user_level', delete_users='$delete_users', delete_user_groups='$delete_user_groups', delete_lists='$delete_lists', delete_campaigns='$delete_campaigns', delete_ingroups='$delete_ingroups', delete_remote_agents='$delete_remote_agents', load_leads='$load_leads', campaign_detail='$campaign_detail', ast_admin_access='$ast_admin_access', ast_delete_phones='$ast_delete_phones', delete_scripts='$delete_scripts', modify_leads='$modify_leads', hotkeys_active='$hotkeys_active', change_agent_campaign='$change_agent_campaign', agent_choose_ingroups='$agent_choose_ingroups', closer_campaigns='$closer_campaigns', scheduled_callbacks='$scheduled_callbacks', agentonly_callbacks='$agentonly_callbacks', agentcall_manual='$agentcall_manual', vicidial_recording='$vicidial_recording', vicidial_transfers='$vicidial_transfers', delete_filters='$delete_filters', alter_agent_interface_options='$alter_agent_interface_options', closer_default_blended='$closer_default_blended', delete_call_times='$delete_call_times', modify_call_times='$modify_call_times', modify_users='$modify_users', modify_campaigns='$modify_campaigns', modify_lists='$modify_lists', modify_scripts='$modify_scripts', modify_filters='$modify_filters', modify_ingroups='$modify_ingroups', modify_usergroups='$modify_usergroups', modify_remoteagents='$modify_remoteagents', modify_servers='$modify_servers', view_reports='$view_reports', vicidial_recording_override='$vicidial_recording_override', alter_custdata_override='$alter_custdata_override', qc_enabled='$qc_enabled', qc_user_level='$qc_user_level', qc_pass='$qc_pass', qc_finish='$qc_finish', qc_commit='$qc_commit', add_timeclock_log='$add_timeclock_log', modify_timeclock_log='$modify_timeclock_log', delete_timeclock_log='$delete_timeclock_log', alter_custphone_override='$alter_custphone_override', vdc_agent_api_access='$vdc_agent_api_access', modify_inbound_dids='$modify_inbound_dids', delete_inbound_dids='$delete_inbound_dids', alert_enabled='$alert_enabled', download_lists='$download_lists', agent_shift_enforcement_override='$agent_shift_enforcement_override', manager_shift_enforcement_override='$manager_shift_enforcement_override', shift_override_flag='$shift_override_flag', export_reports='$export_reports', delete_from_dnc='$delete_from_dnc', email='$email', user_code='$user_code', territory='$territory', allow_alerts='$allow_alerts', agent_choose_territories='$agent_choose_territories', custom_one='$custom_one', custom_two='$custom_two', custom_three='$custom_three', custom_four='$custom_four', custom_five='$custom_five', voicemail_id='$voicemail_id', agent_call_log_view_override='$agent_call_log_view_override', callcard_admin='$callcard_admin', agent_choose_blended='$agent_choose_blended', realtime_block_user_info='$realtime_block_user_info', custom_fields_modify='$custom_fields_modify', force_change_password='$force_change_password', agent_lead_search_override='$agent_lead_search_override', modify_shifts='$modify_shifts', modify_phones='$modify_phones', modify_carriers='$modify_carriers', modify_labels='$modify_labels', modify_statuses='$modify_statuses', modify_voicemail='$modify_voicemail', modify_audiostore='$modify_audiostore', modify_moh='$modify_moh', modify_tts='$modify_tts', preset_contact_search='$preset_contact_search', modify_contacts='$modify_contacts', modify_same_user_level='$modify_same_user_level', admin_hide_lead_data='$admin_hide_lead_data', admin_hide_phone_data='$admin_hide_phone_data', agentcall_email='$agentcall_email', modify_email_accounts='$modify_email_accounts', alter_admin_interface_options='$alter_admin_interface_options', max_inbound_calls='$max_inbound_calls', modify_custom_dialplans='$modify_custom_dialplans', wrapup_seconds_override='$wrapup_seconds_override', modify_languages='$modify_languages', selected_language='$selected_language', user_choose_language='$user_choose_language', ignore_group_on_search='$ignore_group_on_search', api_list_restrict='$api_list_restrict', api_allowed_functions='$api_allowed_functions', lead_filter_id='$lead_filter_id', admin_cf_show_hidden='$admin_cf_show_hidden', agentcall_chat='$agentcall_chat', user_hide_realtime='$user_hide_realtime', access_recordings='$access_recordings', modify_colors='$modify_colors', user_nickname='$user_nickname', user_new_lead_limit='$user_new_lead_limit', api_only_user='$api_only_user', modify_auto_reports='$modify_auto_reports', modify_ip_lists='$modify_ip_lists', ignore_ip_list='$ignore_ip_list', ready_max_logout='$ready_max_logout', export_gdpr_leads='$export_gdpr_leads', pause_code_approval='$pause_code_approval', max_hopper_calls='$max_hopper_calls', max_hopper_calls_hour='$max_hopper_calls_hour' WHERE user='$user'";
                    $queryTelevox = "UPDATE vicidial_clients_limit SET passTelevox='$pass' WHERE userTelevox='$user';";
                    if (sv_mysqli_query($con, $queryShida) && sv_mysqli_query($con, $queryTelevox)) {
                        if ($user_level == 2 || $user_level == 8) {
                            $grupo = limpia($_POST["grupo"]);
                            $query = "DELETE FROM dialvox_grupos_agentes WHERE Usuario = '$user'";
                            sv_mysqli_query($con, $query);
                            $query = "INSERT INTO dialvox_grupos_agentes (Usuario,Grupo) VALUES ('$user','$grupo')";
                            sv_mysqli_query($con, $query);
                        }
                        $salida["Estado"] = "ok";
                        $salida["Descripcion"] = "Se cambiaron los datos correctamente";
                        sv_mysqli_query($con, "UPDATE phones SET pass = '$pass',conf_secret='$pass' WHERE extension = '$user'");
                        $stmtA = "UPDATE servers SET rebuild_conf_files='Y' where generate_vicidial_conf='Y' and active_asterisk_server='Y' and server_ip='" . SERVER_IP_REAL . "'";
                        sv_mysqli_query($con, $stmtA);
                    } else {
                        $salida["Estado"] = "error";
                        $salida["Descripcion"] = $this->lang->line("desc_errorUsuariosEdit");
                    }
                }
            } else {
                $salida["Estado"] = "error";
                $salida["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            }
            $this->output->set_output(json_encode($salida));
            sv_mysqli_close($con);
        }
    }
    public function addUser()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $usuarioAPI = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $salida = array();
            $con = getConnection();
            $url = "";
            $usuario = limpia($_POST["usuario"]);
            $pass = limpia($_POST["password"]);
            $grupo = limpia($_POST["grupo"]);
            $nombre = limpia($_POST["nombre"]);
            $phoneLogin = $usuario;
            $phonePass = $pass;
            $nivel = 2;
            switch ($grupo) {
                case GRUPO_ADMINS:
                    $grupo = GRUPO_ADMINS;
                    $nivel = 9;
                    break;
                case GRUPO_AGENTES:
                    $grupo = GRUPO_AGENTES;
                    $nivel = 2;
                    break;
                case GRUPO_SUPERVISORES:
                    $nivel = 8;
                    $grupo = GRUPO_SUPERVISORES;
                    break;
            }
            $cliente = $_SESSION["Cliente"];
            if ($_SESSION["Cliente"] != -1) {
                $grupo = $_SESSION["Cliente"] . "_" . $grupo;
            } else {
                $cliente = limpia($_POST["cliente"]);
                $grupo = $cliente . "_" . $grupo;
            }
            $query = "SELECT user FROM vicidial_users WHERE user = '$usuario'";
            $result = sv_mysqli_query($con, $query);
            if (sv_mysqli_num_rows($result) > 0) {
                $salida["Estado"] = "error";
                $salida["Descripcion"] = $this->lang->line("desc_errorUsuariosRegister");
            } else {
                $query4 = "SELECT limit_number FROM vicidial_clients_limit WHERE idClient='$cliente'";
                $result4 = sv_mysqli_query($con, $query4);
                $row4 = sv_mysqli_fetch_array($result4);
                $salida["LIMI"] = $query4;
                $limite = $row4["limit_number"];
                $salida["limite"] = $limite;
                $query4 = "SELECT COUNT(user_id) AS CANT FROM vicidial_users WHERE user_group LIKE '%$cliente%'";
                $result4 = sv_mysqli_query($con, $query4);
                $row4 = sv_mysqli_fetch_array($result4);
                $cant = $row4["CANT"];
                $salida["CANTIDAD"] = $cant;
                $salida["CAAAAA"] = $query4;
                if ($cant + 1 <= $limite) {
                    $url = URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&function=add_user&agent_user=" . $usuario . "&agent_pass=" . urlencode($pass) . "&agent_user_level=" . $nivel . "&agent_full_name=" . urlencode($nombre) . "&agent_user_group=" . $grupo . "&phone_login=" . $phoneLogin . "&phone_pass=" . urlencode($phonePass);
                    $text = file_get_contents($url);
                    if (strpos($text, "ERROR") !== false) {
                        $salida["Estado"] = "error";
                        $salida["Descripcion"] = $text;
                    } else {

                        if ($nivel == 2) {
                            $grupo = limpia($_POST["grupo2"]);

                            if (NEED_WA && $_SESSION["allow_waCli"]) {
                                $allow_wa = limpia($_POST["allow_wa"]);

                                if ($allow_wa == 1) {
                                    $idUsuario = limpia($_POST["idUsuario_wa"]);
                                    if ($idUsuario === "") {
                                        $url = (RUTA_WA . "/Usuario/add");
                                        $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), 'nombre' => $nombre, 'password' => $pass, 'usuario' => $usuario, 'nivel' => 0);
                                        $options = array(
                                            'http' => array(
                                                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                                'method' => 'POST',
                                                'content' => http_build_query($data),
                                            ),
                                        );
                                        $context = stream_context_create($options);
                                        $result = file_get_contents($url, false, $context);
                                        $resultados = json_decode($result);
                                        if ($resultados->Estado == "ok") {

                                            $query = "INSERT INTO dialvox_grupos_agentes (Usuario,Grupo,wa_user,wa_pass,allow_wa,idusuario_wa) VALUES ('$usuario','$grupo','$usuario','$pass','1','$resultados->idUsuario')";
                                            $result = sv_mysqli_query($con, $query);
                                        } else {
                                            $salida["Estado"] = "error";
                                            $salida["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                                            $this->output->set_output(json_encode($salida));
                                            sv_mysqli_close($con);
                                            return;
                                        }
                                    } else {
                                        $url = (RUTA_WA . "/Usuario/edit");
                                        $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), 'nombre' => $nombre, 'password' => $pass, 'usuario' => $usuario, 'nivel' => 0, "id" => $idUsuario);
                                        $options = array(
                                            'http' => array(
                                                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                                'method' => 'POST',
                                                'content' => http_build_query($data),
                                            ),
                                        );
                                        $context = stream_context_create($options);
                                        $result = file_get_contents($url, false, $context);
                                        $resultados = json_decode($result);
                                        if ($resultados->Estado == "ok") {
                                            $query = "INSERT INTO dialvox_grupos_agentes (Usuario,Grupo,wa_user,wa_pass,allow_wa,idusuario_wa) VALUES ('$usuario','$grupo','$usuario','$pass','1','$idUsuario')";
                                            $result = sv_mysqli_query($con, $query);
                                        } else {
                                            $salida["Estado"] = "error";
                                            $salida["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                                            $this->output->set_output(json_encode($salida));
                                            sv_mysqli_close($con);
                                            return;
                                        }
                                    }
                                } else {
                                    $query = "INSERT INTO dialvox_grupos_agentes (Usuario,Grupo,allow_wa) VALUES ('$usuario','$grupo','0')";
                                    $result = sv_mysqli_query($con, $query);
                                }
                            } else {
                                $query = "INSERT INTO dialvox_grupos_agentes (Usuario,Grupo,allow_wa) VALUES ('$usuario','$grupo','0')";
                                $result = sv_mysqli_query($con, $query);
                            }
                        }
                        //if($nivel == 2){
                        $grupo = $cliente;
                        $query = "SELECT dialplan_number FROM phones ORDER BY CAST(dialplan_number AS UNSIGNED ) DESC LIMIT 1";
                        $result = sv_mysqli_query($con, $query);
                        $dialplan_number = 1000;
                        if ($row = sv_mysqli_fetch_array($result)) {
                            $dialplan_number = $row["dialplan_number"] + 1;
                        }
                        $extension = "";
                        $passExt = "";
                        $bandera = false;
                        if ($_POST["nueva"] == 1) {
                            $extension = $usuario;
                            $passExt = $pass;
                            $stmt = "INSERT INTO phones (extension,dialplan_number,voicemail_id,phone_ip,computer_ip,server_ip,login,pass,status,active,phone_type,fullname,company,picture,protocol,local_gmt,outbound_cid,conf_secret,voicemail_timezone,user_group,template_id,is_webphone,recording_exten) values('$extension','$dialplan_number','$dialplan_number','','','" . SERVER_IP_REAL . "','$extension','$pass','ACTIVE','Y','CCagent','ext $dialplan_number','','','SIP','-5.00','0000000000','$pass','eastern','$grupo','PLANTILLA','Y','$extension');";
                            $rslt = sv_mysqli_query($con, $stmt);
                            $stmt = "INSERT INTO phones_alias (alias_id,alias_name,logins_list) values('$extension','$extension','$extension');";
                            $rslt = sv_mysqli_query($con, $stmt);
                            $stmtA = "UPDATE servers SET rebuild_conf_files='Y' where generate_vicidial_conf='Y' and active_asterisk_server='Y' and server_ip='" . SERVER_IP_REAL . "'";
                            $rslt = sv_mysqli_query($con, $stmtA);
                            $bandera = true;
                        } else {
                            if ($_POST["extension"] == 1) {
                                $bandera = true;
                                $passExt = limpia($_POST["passExt"]);
                                $extension = $dialplan_number;
                                $stmt = "INSERT INTO phones (extension,dialplan_number,voicemail_id,phone_ip,computer_ip,server_ip,login,pass,status,active,phone_type,fullname,company,picture,protocol,local_gmt,outbound_cid,conf_secret,voicemail_timezone,user_group,is_webphone,recording_exten) values('$extension','$dialplan_number','$dialplan_number','','','" . SERVER_IP_REAL . "','" . $extension . "a','$passExt','ACTIVE','Y','CCagent','ext $dialplan_number','','','SIP','-5.00','0000000000','$passExt','eastern','$grupo','N','$extension')";
                                $rslt = sv_mysqli_query($con, $stmt);
                                $stmt = "INSERT INTO phones_alias (alias_id,alias_name,logins_list) values('$extension','$extension','" . $extension . "a');";
                                $rslt = sv_mysqli_query($con, $stmt);
                                $stmtA = "UPDATE servers SET rebuild_conf_files='Y' where generate_vicidial_conf='Y' and active_asterisk_server='Y' and server_ip='" . SERVER_IP_REAL . "'";
                                $rslt = sv_mysqli_query($con, $stmtA);
                                $salida["numExt"] = $extension;
                            }
                        }
                        if ($nivel >= 8) {
                            if ($_POST["extension"] == 1) {
                                $dialplan_number++;
                            }
                            $extension = $usuario;
                            $passExt = $pass;
                            $stmt = "INSERT INTO phones (extension,dialplan_number,voicemail_id,phone_ip,computer_ip,server_ip,login,pass,status,active,phone_type,fullname,company,picture,protocol,local_gmt,outbound_cid,conf_secret,voicemail_timezone,user_group,template_id,is_webphone,recording_exten) values('$extension','$dialplan_number','$dialplan_number','','','" . SERVER_IP_REAL . "','$extension','$pass','ACTIVE','Y','CCagent','ext $dialplan_number','','','SIP','-5.00','0000000000','$pass','eastern','$grupo','PLANTILLA','Y','$extension');";
                            $rslt = sv_mysqli_query($con, $stmt);
                            $stmt = "INSERT INTO phones_alias (alias_id,alias_name,logins_list) values('$extension','$extension','$extension');";
                            $rslt = sv_mysqli_query($con, $stmt);
                            $stmtA = "UPDATE servers SET rebuild_conf_files='Y' where generate_vicidial_conf='Y' and active_asterisk_server='Y' and server_ip='" . SERVER_IP_REAL . "'";
                            $rslt = sv_mysqli_query($con, $stmtA);
                            $grupoAgentes = limpia($_POST["grupo2"]);
                            $queryGrupoAgentes = "INSERT INTO dialvox_grupos_agentes (Usuario,Grupo,allow_wa) VALUES ('$usuario','$grupoAgentes','0')";
                            $resultGrupoAgentes = sv_mysqli_query($con, $queryGrupoAgentes);
                            $salida["queryGrupos"] = $queryGrupoAgentes;
                        }
                        if ($bandera) {
                            $query = "UPDATE vicidial_users SET agent_choose_blended='0', vicidial_transfers='1',closer_default_blended='1',agent_choose_ingroups='0',agentcall_manual='1',phone_login = '$extension',phone_pass = '$passExt',agentcall_chat='1' WHERE user='$usuario'";
                            sv_mysqli_query($con, $query);
                        } else {
                            $query = "UPDATE vicidial_users SET agent_choose_blended='0', vicidial_transfers='1',closer_default_blended='1',agent_choose_ingroups='0',agentcall_manual='1',phone_login = '',phone_pass = '',agentcall_chat='1' WHERE user='$usuario'";
                            sv_mysqli_query($con, $query);
                        }

                        //}
                        $salida["Estado"] = "ok";
                    }
                } else {
                    $salida["Estado"] = "error";
                    $salida["Descripcion"] = $this->lang->line("desc_errorUsuariosLimit");
                }
            }
            $this->output->set_output(json_encode($salida));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function index()
    {
        $this->load->view('usuarios/head');
        $this->load->view('usuarios/vw_usuarios');
        $this->load->view('usuarios/foot');
    }
    public function otro()
    {
        $this->load->view('reporteEstadisticas/head');
        $this->load->view('reporteEstadisticas/vw_reporte_estadisticas');
        $this->load->view('reporteEstadisticas/foot');
    }
    public function getUserStats()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $user = limpia($_GET["usuario"]);
            $fechaInicio = limpia($_GET["fechaInicio"]);
            $fechaFin = limpia($_GET["fechaFin"]);

            if ($fechaFin == "") {
                $fechaFin = $fechaInicio;
            }

            $campana = '';
            if (limpia($_GET["campana"]) != -1) {
                $campana = " AND campaign_id='" . limpia($_GET["campana"]) . "'";
            }

            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }
            $csv = false;
            $sal = array();
            $sal["Estado"] = "ok";
            if (isset($_GET["csv"]) and $_GET["csv"] == "true") {
                $csv = true;
                $tipoCSV = $_GET["tipo"];
            }
            $cadena = '';
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $cadena = "AND user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "')";
            }

            // Query para obentener los grupos
            $filtroGruposEntradaCampana = "";
            if ($campana != "") {
                $queryCampana = "SELECT closer_campaigns FROM vicidial_campaigns WHERE 1=1 $campana";
                $result = sv_mysqli_query($con, $queryCampana);
                if ($result && $result->get_num_rows() > 0) {
                    $row = sv_mysqli_fetch_array($result);
                    $closerCampaigns = $row["closer_campaigns"];
                    $filtroGruposEntradaCampana = " AND campaign_id IN ('" . str_replace(" ", "','", $closerCampaigns) . "') ";
                }
            } else {
                $queryIngroups = "SELECT group_id FROM vicidial_inbound_groups WHERE user_group='$cliente'";
                $result = sv_mysqli_query($con, $queryIngroups);
                if ($result && $result->get_num_rows() > 0) {
                    $filtroGruposEntradaCampana = " AND campaign_id IN (";
                    $primero = true;
                    while ($row = sv_mysqli_fetch_array($result)) {
                        if ($primero) {
                            $filtroGruposEntradaCampana .= "'" . $row["group_id"] . "'";
                            $primero = false;
                        } else {
                            $filtroGruposEntradaCampana .= ",'" . $row["group_id"] . "'";
                        }
                    }
                    $filtroGruposEntradaCampana .= ") ";
                }
            }

            $query = "SELECT user FROM vicidial_users WHERE user = '$usuario' $cadena LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT count(*) ,status, sum(length_in_sec)  from vicidial_log where user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') $campana group by status order by status";
                if ($archived) {
                    $query = "SELECT count(*) ,status, sum(length_in_sec)  from vicidial_log_archive where user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') $campana group by status order by status";
                }
                $rslt = sv_mysqli_query($con, $query);
                $VLstatuses_to_print = sv_mysqli_num_rows($rslt);
                $total_calls = 0;
                $o = 0;
                $p = 0;
                $VLstatuses_to_print = sv_mysqli_num_rows($rslt);
                $total_calls = 0;
                $o = 0;
                $p = 0;
                $counts = array();
                $call_sec = array();
                $status = array();
                while ($VLstatuses_to_print > $o) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $counts[$p] = $row[0];
                    $status[$p] = $row[1];
                    $call_sec[$p] = $row[2];
                    $p++;
                    $o++;
                }
                $query = "SELECT count(*),status, sum(length_in_sec) from vicidial_closer_log where user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') $campana  order by status";
                if ($archived) {
                    $query = "SELECT count(*),status, sum(length_in_sec) from vicidial_closer_log_archive where user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') $campana  order by status";
                }
                $rslt = sv_mysqli_query($con, $query);
                $VCLstatuses_to_print = sv_mysqli_num_rows($rslt);
                $o = 0;
                while ($VCLstatuses_to_print > $o) {
                    $status_match = 0;
                    $r = 0;
                    $row = sv_mysqli_fetch_array($rslt);
                    while ($VLstatuses_to_print > $r) {
                        if ($status[$r] == $row[1]) {
                            $counts[$r] = ($counts[$r] + $row[0]);
                            $call_sec[$r] = ($call_sec[$r] + $row[2]);
                            $status_match++;
                        }
                        $r++;
                    }
                    if ($status_match < 1) {
                        $counts[$p] = $row[0];
                        $status[$p] = $row[1];
                        $call_sec[$p] = $row[2];
                        $VLstatuses_to_print++;
                        $p++;
                    }
                    $o++;
                }
                $o = 0;
                $total_sec = 0;
                $sal["tiempoCharla"] = array();
                $sal["tiempoCharla"]["Registros"] = array();
                $sal["tiempoCharla"]["Total"] = array();
                while ($o < $p) {
                    $call_hours_minutes = $call_sec[$o];
                    $sal["tiempoCharla"]["Registros"][$o]["Estado"] = $status[$o];
                    $sal["tiempoCharla"]["Registros"][$o]["Cuenta"] = $counts[$o];
                    $sal["tiempoCharla"]["Registros"][$o]["Tiempo"] = $call_hours_minutes ? $call_hours_minutes : 0;
                    $total_calls = ($total_calls + $counts[$o]);
                    $total_sec = ($total_sec + $call_sec[$o]);
                    $call_seconds = 0;
                    $o++;
                }
                $sal["tiempoCharla"]["Total"]["Cuenta"] = $total_calls;
                $sal["tiempoCharla"]["Total"]["Tiempo"] = $total_sec;
                $stmt = "SELECT event,event_epoch,event_date,campaign_id,user_group,session_id,server_ip,extension,computer_ip,phone_login,phone_ip from vicidial_user_log where user='$user' and DATE(event_date)>= DATE('$fechaInicio')  and DATE(event_date) <= DATE('$fechaFin') $campana order by event_date";
                $rslt = sv_mysqli_query($con, $stmt);
                $events_to_print = sv_mysqli_num_rows($rslt);
                $total_calls = 0;
                $o = 0;
                $event_start_seconds = '';
                $event_stop_seconds = '';
                $donde = 0;
                $total_login_time = 0;
                $sal["HoraInicioCierreAgente"] = array();
                while ($events_to_print > $o) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $objeto = array();
                    if (preg_match('/LOGIN/', $row[0])) {
                        if ($row[10] == 'LOOKUP') {
                            $row[10] = '';
                        }
                        $event_start_seconds = $row[1];
                        $objeto["Evento"] = $row[0];
                        $objeto["Fecha"] = $row[2];
                        $resultxx = sv_mysqli_query($con, "SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id='" . $row[3] . "' $campana");
                        $nombreCampana = "";
                        if ($rowxx = sv_mysqli_fetch_array($resultxx)) {
                            $nombreCampana = $rowxx["campaign_name"];
                        } else {
                            $nombreCampana = "Campaña borrada";
                        }
                        $objeto["Campana"] = $nombreCampana;
                        $objeto["Grupo"] = $row[4];
                        $objeto["Sesion"] = $row[5];
                        $objeto["Servidor"] = $row[6];
                        $objeto["Telefono"] = $row[7];
                        $objeto["Computadora"] = $row[8];
                        $objeto["TelefonoInicio"] = $row[9];
                        $objeto["IPTelefono"] = $row[10];
                    }
                    if (preg_match('/LOGOUT/', $row[0])) {
                        if ($event_start_seconds) {
                            $event_stop_seconds = $row[1];
                            $event_seconds = ($event_stop_seconds - $event_start_seconds);
                            $total_login_time = ($total_login_time + $event_seconds);
                            $objeto["Evento"] = $row[0];
                            $objeto["Fecha"] = $row[2];
                            $resultxx = sv_mysqli_query($con, "SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id='" . $row[3] . "' $campana");
                            $nombreCampana = "";
                            if ($rowxx = sv_mysqli_fetch_array($resultxx)) {
                                $nombreCampana = $rowxx["campaign_name"];
                            } else {
                                $nombreCampana = "Campaña borrada";
                            }
                            $objeto["Campana"] = $nombreCampana;
                            $objeto["Grupo"] = $row[4];
                            $objeto["Sesion"] = $event_seconds;
                            $event_start_seconds = '';
                            $event_stop_seconds = '';
                        } else {
                            $objeto["Evento"] = $row[0];
                            $objeto["Fecha"] = $row[2];
                            $resultxx = sv_mysqli_query($con, "SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id='" . $row[3] . "' $campana");
                            $nombreCampana = "";
                            if ($rowxx = sv_mysqli_fetch_array($resultxx)) {
                                $nombreCampana = $rowxx["campaign_name"];
                            } else {
                                $nombreCampana = "Campaña borrada";
                            }
                            $objeto["Campana"] = $nombreCampana;
                        }
                    }
                    $sal["HoraInicioCierreAgente"]["Registros"][] = $objeto;
                    $donde++;
                    $total_calls = ($total_calls + 1);
                    $call_seconds = 0;
                    $o++;
                }
                $sal["HoraInicioCierreAgente"]["Total"] = $total_login_time;
                $stmt = "select user,campaign_id,event_date,blended,closer_campaigns,manager_change from vicidial_user_closer_log where user='$user' and DATE(event_date)>= DATE('$fechaInicio')  and DATE(event_date) <= DATE('$fechaFin') $campana order by event_date desc limit 1000;";
                $rslt = sv_mysqli_query($con, $stmt);
                $logs_to_print = sv_mysqli_num_rows($rslt);
                $u = 0;
                while ($logs_to_print > $u) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $sal["RegistrosMasCercanos"][$u]["Numero"] = ($u + 1);
                    $sal["RegistrosMasCercanos"][$u]["Hora"] = $row[2];
                    $resultxx = sv_mysqli_query($con, "SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id='" . $row[1] . "' $campana");
                    $nombreCampana = "";
                    if ($rowxx = sv_mysqli_fetch_array($resultxx)) {
                        $nombreCampana = $rowxx["campaign_name"];
                    } else {
                        $nombreCampana = "Campaña borrada";
                    }
                    $sal["RegistrosMasCercanos"][$u]["Campana"] = $nombreCampana;
                    $sal["RegistrosMasCercanos"][$u]["Mezcla"] = $row[3];
                    $sal["RegistrosMasCercanos"][$u]["Grupos"] = $row[4];
                    $sal["RegistrosMasCercanos"][$u]["Gerente"] = $row[5];
                    $u++;
                }
                $stmt = "select uniqueid,vlog.lead_id,vlog.list_id,campaign_id,call_date,start_epoch,end_epoch,length_in_sec,vlog.status,vlog.phone_code,vlog.phone_number,vlog.user,vlog.comments,processed,user_group,term_reason,alt_dial,first_name,last_name from vicidial_log vlog, vicidial_list vlist where vlog.user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') and vlog.lead_id=vlist.lead_id $campana order by call_date desc";
                if ($archived) {
                    $stmt = "select uniqueid,vlog.lead_id,vlog.list_id,campaign_id,call_date,start_epoch,end_epoch,length_in_sec,vlog.status,vlog.phone_code,vlog.phone_number,vlog.user,vlog.comments,processed,user_group,term_reason,alt_dial,first_name,last_name from vicidial_log_archive vlog, vicidial_list vlist where vlog.user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') and vlog.lead_id=vlist.lead_id $campana order by call_date desc";
                }
                $rslt = sv_mysqli_query($con, $stmt);
                $logs_to_print = sv_mysqli_num_rows($rslt);
                $u = 0;
                $sal["LlamadasSalientes"] = array();
                while ($logs_to_print > $u) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $u++;
                    $sal["LlamadasSalientes"][($u - 1)]["Numero"] = $u;
                    $sal["LlamadasSalientes"][($u - 1)]["Fecha"] = $row[4];
                    $sal["LlamadasSalientes"][($u - 1)]["Duracion"] = $row[7];
                    $sal["LlamadasSalientes"][($u - 1)]["Estado"] = $row[8];
                    $sal["LlamadasSalientes"][($u - 1)]["Telefono"] = $row[10];
                    $resultxx = sv_mysqli_query($con, "SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id='" . $row[3] . "' $campana");
                    $nombreCampana = "";
                    if ($rowxx = sv_mysqli_fetch_array($resultxx)) {
                        $nombreCampana = $rowxx["campaign_name"];
                    } else {
                        $nombreCampana = "Campaña borrada";
                    }
                    $sal["LlamadasSalientes"][($u - 1)]["Campana"] = $nombreCampana;
                    $sal["LlamadasSalientes"][($u - 1)]["Grupo"] = $row[14];
                    $sal["LlamadasSalientes"][($u - 1)]["Lista"] = $row[2];
                    $sal["LlamadasSalientes"][($u - 1)]["Registro"] = $row[1];
                    $sal["LlamadasSalientes"][($u - 1)]["Nombre"] = $row[17] . " " . $row[18];
                    $sal["LlamadasSalientes"][($u - 1)]["Razon"] = $row[15];
                }

                $stmt = "select call_date,(IFNULL((SELECT MAX(length_in_sec) FROM recording_log WHERE vicidial_id=vlog.uniqueid LIMIT 1),IFNULL((SELECT MAX(length_in_sec) FROM recording_log_archive WHERE vicidial_id=vlog.uniqueid LIMIT 1),IFNULL(length_in_sec,0)))) as length_in_sec,vlog.status,vlog.phone_number,campaign_id,queue_seconds,vlog.list_id,vlog.lead_id,term_reason,first_name,last_name from vicidial_closer_log vlog, vicidial_list vlist where vlog.user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') and vlog.lead_id=vlist.lead_id $filtroGruposEntradaCampana order by call_date desc";
                if ($archived) {
                    $stmt = "select call_date,(IFNULL((SELECT MAX(length_in_sec) FROM recording_log WHERE vicidial_id=vlog.uniqueid LIMIT 1),IFNULL((SELECT MAX(length_in_sec) FROM recording_log_archive WHERE vicidial_id=vlog.uniqueid LIMIT 1),IFNULL(length_in_sec,0)))) as length_in_sec,vlog.status,vlog.phone_number,campaign_id,queue_seconds,vlog.list_id,vlog.lead_id,term_reason,first_name,last_name from vicidial_closer_log_archive vlog, vicidial_list vlist where vlog.user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') and vlog.lead_id=vlist.lead_id $filtroGruposEntradaCampana order by call_date desc";
                }
                $rslt = sv_mysqli_query($con, $stmt);
                $logs_to_print = sv_mysqli_num_rows($rslt);
                $u = 0;
                $TOTALinSECONDS = 0;
                $TOTALagentSECONDS = 0;
                $sal["EntrantesCercanas"]["Registros"] = array();
                while ($logs_to_print > $u) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $TOTALinSECONDS = ($TOTALinSECONDS + $row[1]);
                    $AGENTseconds = ($row[1] - $row[5]);
                    if ($AGENTseconds < 0) {
                        $AGENTseconds = 0;
                    }
                    $TOTALagentSECONDS = ($TOTALagentSECONDS + $AGENTseconds);
                    $u++;
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Numero"] = $u;
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Fecha"] = $row[0];
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Duracion"] = $row[1];
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Estados"] = $row[2];
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Telefono"] = $row[3];
                    $resultxx = sv_mysqli_query($con, "SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id='" . $row[4] . "' OR ( closer_campaigns LIKE '%" . $row[4] . "%' $campana )");
                    $nombreCampana = "";
                    if ($rowxx = sv_mysqli_fetch_array($resultxx)) {
                        $nombreCampana = $rowxx["campaign_name"];
                    } else {
                        $nombreCampana = "Campaña borrada";
                    }
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Campana"] = $nombreCampana;
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Espera"] = $row[5];
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Agente"] = $AGENTseconds;
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Lista"] = $row[6];
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Registro"] = $row[7];
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Nombre"] = $row[9] . " " . $row[10];
                    $sal["EntrantesCercanas"]["Registros"][($u - 1)]["Razon"] = $row[8];
                }
                $sal["EntrantesCercanas"]["Totales"]["Segundos"] = $TOTALinSECONDS;
                $sal["EntrantesCercanas"]["Totales"]["Agente"] = $TOTALagentSECONDS;
                $stmt = "select event_time,lead_id,campaign_id,pause_sec,wait_sec,talk_sec,dispo_sec,dead_sec,status,sub_status,user_group from vicidial_agent_log where user='$user' and DATE(event_time)>= DATE('$fechaInicio')  and DATE(event_time) <= DATE('$fechaFin') and ( (pause_sec > 0) or (wait_sec > 0) or (talk_sec > 0) or (dispo_sec > 0) ) $campana order by event_time desc limit 10000";
                if ($archived) {
                    $stmt = "select event_time,lead_id,campaign_id,pause_sec,wait_sec,talk_sec,dispo_sec,dead_sec,status,sub_status,user_group from vicidial_agent_log_archive where user='$user' and DATE(event_time)>= DATE('$fechaInicio')  and DATE(event_time) <= DATE('$fechaFin') and ( (pause_sec > 0) or (wait_sec > 0) or (talk_sec > 0) or (dispo_sec > 0) ) $campana order by event_time desc limit 10000";
                }
                $rslt = sv_mysqli_query($con, $stmt);
                $logs_to_print = sv_mysqli_num_rows($rslt);
                $u = 0;
                $TOTALpauseSECONDS = 0;
                $TOTALwaitSECONDS = 0;
                $TOTALtalkSECONDS = 0;
                $TOTALdispoSECONDS = 0;
                $TOTALdeadSECONDS = 0;
                $TOTALcustomerSECONDS = 0;
                while ($logs_to_print > $u) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $event_time = $row[0];
                    $lead_id = $row[1];
                    $campaign_id = $row[2];
                    $pause_sec = $row[3];
                    $wait_sec = $row[4];
                    $talk_sec = $row[5];
                    $dispo_sec = $row[6];
                    $dead_sec = $row[7];
                    $status = $row[8];
                    $pause_code = $row[9];
                    $user_group = $row[10];
                    $customer_sec = ($talk_sec - $dead_sec);
                    if ($customer_sec < 0) {
                        $customer_sec = 0;
                    }
                    $TOTALpauseSECONDS = ($TOTALpauseSECONDS + $pause_sec);
                    $TOTALwaitSECONDS = ($TOTALwaitSECONDS + $wait_sec);
                    $TOTALtalkSECONDS = ($TOTALtalkSECONDS + $talk_sec);
                    $TOTALdispoSECONDS = ($TOTALdispoSECONDS + $dispo_sec);
                    $TOTALdeadSECONDS = ($TOTALdeadSECONDS + $dead_sec);
                    $TOTALcustomerSECONDS = ($TOTALcustomerSECONDS + $customer_sec);
                    $u++;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Numero"] = $u;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Fecha"] = $event_time;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Pausa"] = $pause_sec;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Espera"] = $wait_sec;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Conversacion"] = $talk_sec;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Dispo"] = $dispo_sec;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Muerto"] = $dead_sec;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Cliente"] = $customer_sec;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Estado"] = $status;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Registro"] = $lead_id;
                    $resultxx = sv_mysqli_query($con, "SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id='$campaign_id' $campana");
                    $nombreCampana = "";
                    if ($rowxx = sv_mysqli_fetch_array($resultxx)) {
                        $nombreCampana = $rowxx["campaign_name"];
                    } else {
                        $nombreCampana = $this->lang->line("texto_campanaUsuariosBorrada");
                    }
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["Campana"] = $nombreCampana;
                    $sal["ActividadAgente"]["Registros"][($u - 1)]["CodigoPausa"] = $pause_code;
                }
                $sal["ActividadAgente"]["Totales"]["Pausa"] = $TOTALpauseSECONDS;
                $sal["ActividadAgente"]["Totales"]["Espera"] = $TOTALwaitSECONDS;
                $sal["ActividadAgente"]["Totales"]["Conversacion"] = $TOTALtalkSECONDS;
                $sal["ActividadAgente"]["Totales"]["Dispo"] = $TOTALdispoSECONDS;
                $sal["ActividadAgente"]["Totales"]["Muerto"] = $TOTALdeadSECONDS;
                $sal["ActividadAgente"]["Totales"]["Cliente"] = $TOTALcustomerSECONDS;
                $stmt = "SELECT recording_id,channel,server_ip,extension,start_time,start_epoch,end_time,end_epoch,length_in_sec,length_in_min,filename,location,lead_id,user,vicidial_id from recording_log where user='$user' and DATE(start_time)>= DATE('$fechaInicio')  and DATE(start_time) <= DATE('$fechaFin') order by recording_id desc limit 10000;";
                if ($archived == true) {
                    $stmt = "SELECT recording_id,channel,server_ip,extension,start_time,start_epoch,end_time,end_epoch,length_in_sec,length_in_min,filename,location,lead_id,user,vicidial_id from recording_log_archive where user='$user' and DATE(start_time)>= DATE('$fechaInicio')  and DATE(start_time) <= DATE('$fechaFin') order by recording_id desc limit 10000;";
                }
                $rslt = sv_mysqli_query($con, $stmt);
                $logs_to_print = sv_mysqli_num_rows($rslt);
                $u = 0;
                $sal["Grabaciones"] = array();
                $sal["Grabaciones"]["Registros"] = array();
                while ($logs_to_print > $u) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $location = $row[11];
                    $CSV_location = $row[11];
                    if (strlen($location ?? "") > 2) {
                        $URLserver_ip = $location;
                        $URLserver_ip = preg_replace('/http:\/\//i', '', $URLserver_ip);
                        $URLserver_ip = preg_replace('/https:\/\//i', '', $URLserver_ip);
                        $URLserver_ip = preg_replace('/\/.*/i', '', $URLserver_ip);
                        $stmt = "select count(*) from servers where server_ip='$URLserver_ip';";
                        $rsltx = sv_mysqli_query($con, $stmt);
                        $rowx = sv_mysqli_fetch_array($rsltx);
                        if ($rowx[0] > 0) {
                            $stmt = "select recording_web_link,alt_server_ip,external_server_ip from servers where server_ip='$URLserver_ip';";
                            $rsltx = sv_mysqli_query($con, $stmt);
                            $rowx = sv_mysqli_fetch_array($rsltx);
                            if (preg_match("/ALT_IP/i", $rowx[0])) {
                                $location = preg_replace("/$URLserver_ip/i", "$rowx[1]", $location);
                            }
                            if (preg_match("/EXTERNAL_IP/i", $rowx[0])) {
                                $location = preg_replace("/$URLserver_ip/i", "$rowx[2]", $location);
                            }
                        }
                    }
                    $u++;
                    $sal["Grabaciones"]["Registros"][($u - 1)]["Numero"] = $u;
                    $sal["Grabaciones"]["Registros"][($u - 1)]["Registro"] = $row[12];
                    $sal["Grabaciones"]["Registros"][($u - 1)]["Fecha"] = $row[4];
                    $sal["Grabaciones"]["Registros"][($u - 1)]["Segundos"] = $row[8];
                    $sal["Grabaciones"]["Registros"][($u - 1)]["RECID"] = $row[0];
                    $sal["Grabaciones"]["Registros"][($u - 1)]["Nombre"] = $row[10];
                    $sal["Grabaciones"]["Registros"][($u - 1)]["Localizacion"] = $location;
                }
                $stmt = "select call_date,call_type,server_ip,phone_number,number_dialed,lead_id,callerid,group_alias_id,preset_name,customer_hungup,customer_hungup_seconds from user_call_log where user='$user' and DATE(call_date)>= DATE('$fechaInicio')  and DATE(call_date) <= DATE('$fechaFin') order by call_date desc limit 10000;";
                $rslt = sv_mysqli_query($con, $stmt);
                $logs_to_print = sv_mysqli_num_rows($rslt);
                $u = 0;
                while ($logs_to_print > $u) {
                    $row = sv_mysqli_fetch_array($rslt);
                    $C3HU = '';
                    if ($row[9] == 'BEFORE_CALL') {
                        $row[9] = 'BC';
                    }
                    if ($row[9] == 'DURING_CALL') {
                        $row[9] = 'DC';
                    }
                    if (strlen($row[9] ?? "") > 1) {
                        $C3HU = "$row[9] $row[10]";
                    }
                    $u++;
                    $sal["SalientesManuales"][($u - 1)]["Numero"] = $u;
                    $sal["SalientesManuales"][($u - 1)]["Fecha"] = $row[0];
                    $sal["SalientesManuales"][($u - 1)]["Tipo"] = $row[1];
                    $sal["SalientesManuales"][($u - 1)]["Servidor"] = $row[2];
                    $sal["SalientesManuales"][($u - 1)]["Telefono"] = $row[3];
                    $sal["SalientesManuales"][($u - 1)]["Marcado"] = $row[4];
                    $sal["SalientesManuales"][($u - 1)]["Registro"] = $row[5];
                    $sal["SalientesManuales"][($u - 1)]["Identificador"] = $row[6];
                    $sal["SalientesManuales"][($u - 1)]["Alias"] = $row[7];
                    $sal["SalientesManuales"][($u - 1)]["Configuracion"] = $row[8];
                    $sal["SalientesManuales"][($u - 1)]["C3HU"] = $C3HU;
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosUsuariosReporte");
            }
            sv_mysqli_close($con);
            if (!$csv) {
                // $sal["Estado"] = "ok";
                header('Content-type: application/json');
                $this->output->set_output(json_encode($sal));
            } else {
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=EstadisticasAgente($user)(" . $fechaInicio . "-" . $fechaFin . ").csv");
                ob_clean();
                $out = fopen('php://output', 'w');
                fwrite($out, "{$this->lang->line('header_1')}\n");
                fwrite($out, "{$this->lang->line('header_2')},{$this->lang->line('header_3')},HH:MM:SS\n");
                foreach ($sal["tiempoCharla"]["Registros"] as $value) {
                    fwrite($out, "{$value['Estado']},{$value['Cuenta']},{$value['Tiempo']}\n");
                }
                fwrite($out, "{$this->lang->line('header_4')},{$sal['tiempoCharla']['Total']['Cuenta']},{$sal['tiempoCharla']['Total']['Tiempo']}");
                fwrite($out, "\n\n");

                fwrite($out, "{$this->lang->line('header_5')}\n");
                fwrite($out, "{$this->lang->line('header_6')},{$this->lang->line('header_7')},{$this->lang->line('header_8')},{$this->lang->line('header_9')},{$this->lang->line('header_10')},{$this->lang->line('header_11')},{$this->lang->line('header_12')},{$this->lang->line('header_13')},{$this->lang->line('header_14')},{$this->lang->line('header_15')}\n");
                foreach ($sal["HoraInicioCierreAgente"]["Registros"] as $value) {
                    fwrite($out, "{$value['Evento']},{$value['Fecha']},{$value['Campana']},{$value['Grupo']},{$value['Sesion']}," . (isset($value['Servidor']) ? $value['Servidor'] : "") . "," . (isset($value['Telefono']) ? $value['Telefono'] : "") . "," . (isset($value['Computadora']) ? $value['Computadora'] : "") . "," . (isset($value['TelefonoInicio']) ? $value['TelefonoInicio'] : "") . "," . (isset($value['IPTelefono']) ? $value['IPTelefono'] : "") . "\n");
                }
                fwrite($out, "Total:,{$sal['HoraInicioCierreAgente']['Total']}");
                fwrite($out, "\n\n");

                fwrite($out, "{$this->lang->line('header_16')}\n");
                fwrite($out, "{$this->lang->line('header_17')},{$this->lang->line('header_18')},{$this->lang->line('header_19')},{$this->lang->line('header_2')},{$this->lang->line('header_8')},{$this->lang->line('header_9')},{$this->lang->line('header_20')},{$this->lang->line('header_21')},{$this->lang->line('header_22')}\n");
                foreach ($sal["LlamadasSalientes"] as $value) {
                    fwrite($out, "{$value['Numero']},{$value['Fecha']},{$value['Duracion']},{$value['Estado']},{$value['Campana']},{$value['Grupo']},{$value['Lista']},{$value['Registro']},{$value['Razon']}\n");
                }
                fwrite($out, "\n\n");

                fwrite($out, "{$this->lang->line('header_27')}\n");
                fwrite($out, "{$this->lang->line('header_17')},{$this->lang->line('header_18')},{$this->lang->line('header_19')},{$this->lang->line('header_2')},{$this->lang->line('header_12')},{$this->lang->line('header_8')},{$this->lang->line('header_23')},{$this->lang->line('header_24')},{$this->lang->line('header_20')},{$this->lang->line('header_21')},{$this->lang->line('header_25')},{$this->lang->line('header_22')}\n");
                foreach ($sal["EntrantesCercanas"]["Registros"] as $value) {
                    fwrite($out, "{$value['Numero']},{$value['Fecha']},{$value['Duracion']},{$value['Estados']},{$value['Telefono']},{$value['Campana']},{$value['Espera']},{$value['Agente']},{$value['Lista']},{$value['Registro']},{$value['Nombre']},{$value['Razon']}\n");
                }
                fwrite($out, "\n\n");

                fwrite($out, "{$this->lang->line('header_26')}\n");
                fwrite($out, "{$this->lang->line('header_17')},{$this->lang->line('header_18')},{$this->lang->line('header_28')},{$this->lang->line('header_29')},{$this->lang->line('header_30')},{$this->lang->line('header_31')},{$this->lang->line('header_32')},{$this->lang->line('header_33')},{$this->lang->line('header_2')},{$this->lang->line('header_21')},{$this->lang->line('header_8')},{$this->lang->line('header_35')}\n");
                foreach ($sal["ActividadAgente"]["Registros"] as $value) {
                    fwrite($out, "{$value['Numero']},{$value['Fecha']},{$value['Pausa']},{$value['Espera']},{$value['Conversacion']},{$value['Dispo']},{$value['Muerto']},{$value['Cliente']},{$value['Estado']},{$value['Registro']},{$value['Campana']},{$value['CodigoPausa']}\n");
                }
                fwrite($out, "\n\n");

                fwrite($out, "{$this->lang->line('header_36')}\n");
                fwrite($out, "{$this->lang->line('header_17')},{$this->lang->line('header_21')},{$this->lang->line('header_18')},{$this->lang->line('header_37')},{$this->lang->line('header_38')},{$this->lang->line('header_39')}\n");
                foreach ($sal["Grabaciones"]["Registros"] as $value) {
                    fwrite($out, "{$value['Numero']},{$value['Registro']},{$value['Numero']},{$value['Fecha']},{$value['Segundos']},{$value['RECID']},{$value['Nombre']}\n");
                }
                fwrite($out, "\n\n");

                fclose($out);
            }
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function tomarUsuario()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $user = limpia($_POST["usuario"]);
            $cadena = '';
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $cadena = "AND user_group IN ('" . $cliente . "_" . GRUPO_ADMINS . "','" . $cliente . "_" . GRUPO_AGENTES . "','" . $cliente . "_" . GRUPO_SUPERVISORES . "')";
            }
            $query = "SELECT pass,user_group,user,full_name FROM vicidial_users WHERE user = '$user' AND active = 'Y' $cadena LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $salida = array();
            $sePuede = true;
            $error = 0;
            $pass = "";
            $guardar = array();
            if ($row) {
                if ($_SESSION["Grupo"] == GRUPO_ADMINS || ($_SESSION["Grupo"] == GRUPO_SUPERVISORES && (strpos($row["user_group"], GRUPO_ADMINS) === false))) {
                    $campana = "";
                    if ((strpos($row["user_group"], GRUPO_AGENTES) !== false)) {
                        $guardar["extension"] = limpia($_POST["userExt"]);
                        $guardar["pass_ext"] = limpia($_POST["passExt"]);
                        $campana = limpia($_POST["campana"]);
                        $cliente = "";
                        $grupo = $row["user_group"];
                        $a = strpos($grupo, "_");
                        $extra = "";
                        if ($a === false) {
                            $cliente = -1;
                        } else {
                            $cliente = "";
                            for ($i = $a - 1; $i >= 0; $i--) {
                                $cliente .= $grupo[$i];
                            }
                            $cliente = strrev($cliente);
                            $extra = "AND user_group = '$cliente'";
                        }
                        $query1 = "SELECT campaign_id,dial_method FROM vicidial_campaigns WHERE active = 'Y' $extra AND campaign_id = '$campana' LIMIT 1";
                        $result1 = sv_mysqli_query($con, $query1);
                        if (sv_mysqli_num_rows($result1) <= 0) {
                            $sePuede = false;
                            $error = 2;
                        } else {
                            $row3 = sv_mysqli_fetch_array($result1);
                            $guardar["dial_method"] = $row3["dial_method"];

                            $query2 = "SELECT userTelevox,passTelevox,windows_check,max_time_dispo,allow_beep,time_beep,time_repeat,allow_wa,idcampaign_wa FROM vicidial_tables_windows WHERE campaign_id = '$campana'";
                            $result2 = sv_mysqli_query($con, $query2);
                            $row4 = sv_mysqli_fetch_array($result2);
                            $guardar["windows_check"] = $row4["windows_check"];
                            $guardar["max_time_dispo"] = $row4["max_time_dispo"];
                            $guardar["allow_beep"] = $row4["allow_beep"];
                            $guardar["time_beep"] = $row4["time_beep"];
                            $guardar["time_repeat"] = $row4["time_repeat"];
                            $guardar["allow_wa"] = $row4["allow_wa"];
                            $guardar["userTelevox"] = $row4["userTelevox"];
                            $guardar["passTelevox"] = $row4["passTelevox"];
                            if (NEED_WA) {
                                $guardar["allow_wa"] = $row4["allow_wa"];
                                $guardar["wa_camp"] = $row4["idcampaign_wa"];
                                $query2 = "SELECT wa_user,wa_pass,allow_wa FROM dialvox_grupos_agentes WHERE Usuario = '$user'";
                                $result2 = sv_mysqli_query($con, $query2);
                                $row4 = sv_mysqli_fetch_array($result2);
                                $guardar["wa_user"] = $row4["wa_user"];
                                $guardar["wa_pass"] = $row4["wa_pass"];
                                $guardar["WA_USER"] = $row4["allow_wa"];
                            }

                            if ($row3["dial_method"] != 'INBOUND_MAN') {
                                $query = "SELECT count(hopper_id) FROM vicidial_hopper where campaign_id = '$campana' and status='READY'";
                                $result = sv_mysqli_query($con, $query);
                                $row2 = sv_mysqli_fetch_array($result);
                                if ($row2[0] <= 0) {
                                    $error = 3;
                                    $sePuede = false;
                                }
                            }
                        }
                        $query = "SELECT campaign_id,dial_method FROM vicidial_campaigns WHERE active = 'Y' $extra AND campaign_id = '$campana' LIMIT 1";
                        $result = sv_mysqli_query($con, $query);
                        if (sv_mysqli_num_rows($result) <= 0) {
                            $sePuede = false;
                            $error = 2;
                        } else {
                        }
                    }
                    if ($sePuede) {
                        $salida["Estado"] = "Ok";
                        $salida["Grupo"] = $row["user_group"];
                        session_destroy();
                        session_start();
                        foreach ($guardar as $key => $val) {
                            $_SESSION[$key] = $val;
                        }
                        $_SESSION["Usuario"] = $user;
                        $_SESSION["Password"] = $pass;
                        $_SESSION["Grupo"] = $row["user_group"];
                        $a = strpos($_SESSION["Grupo"], "_");
                        if ($a === false) {
                            $_SESSION["Cliente"] = -1;
                        } else {
                            $_SESSION["Cliente"] = "";
                            for ($i = $a - 1; $i >= 0; $i--) {
                                $_SESSION["Cliente"] .= $_SESSION["Grupo"][$i];
                            }
                            $_SESSION["Cliente"] = strrev($_SESSION["Cliente"]);
                        }
                        $tipo = GRUPO_AGENTES;
                        if (strpos($salida["Grupo"], GRUPO_ADMINS) !== false) {
                            $tipo = GRUPO_ADMINS;
                            $querygruposAgentes = "SELECT Grupo FROM dialvox_grupos_agentes WHERE Usuario = '$user' LIMIT 1";
                            $resultGrupoAgentes = sv_mysqli_query($con, $querygruposAgentes);
                            $grupoDeAgentes = "";
                            if ($resultGrupoAgentes) {
                                if ($rowGruposAgentes = sv_mysqli_fetch_array($resultGrupoAgentes)) {
                                    $grupoDeAgentes = $rowGruposAgentes["Grupo"];
                                }
                            }
                            $_SESSION["Categoria"] = $grupoDeAgentes;
                        }

                        if (strpos($salida["Grupo"], GRUPO_AGENTES) !== false) {
                            $tipo = GRUPO_AGENTES;
                            $_SESSION["extension"] = limpia($_POST["extension"]);
                            $_SESSION["pass_ext"] = limpia($_POST["pass_ext"]);
                            $querygruposAgentes = "SELECT Grupo FROM dialvox_grupos_agentes WHERE Usuario = '$user' LIMIT 1";
                            $resultGrupoAgentes = sv_mysqli_query($con, $querygruposAgentes);
                            $grupoDeAgentes = "";
                            if ($resultGrupoAgentes) {
                                if ($rowGruposAgentes = sv_mysqli_fetch_array($resultGrupoAgentes)) {
                                    $grupoDeAgentes = $rowGruposAgentes["Grupo"];
                                }
                            }
                            $_SESSION["Categoria"] = $grupoDeAgentes;
                        }
                        if (strpos($salida["Grupo"], GRUPO_SUPERVISORES) !== false) {
                            $tipo = GRUPO_SUPERVISORES;
                            $querygruposAgentes = "SELECT Grupo FROM dialvox_grupos_agentes WHERE Usuario = '$user' LIMIT 1";
                            $resultGrupoAgentes = sv_mysqli_query($con, $querygruposAgentes);
                            $grupoDeAgentes = "";
                            if ($resultGrupoAgentes) {
                                if ($rowGruposAgentes = sv_mysqli_fetch_array($resultGrupoAgentes)) {
                                    $grupoDeAgentes = $rowGruposAgentes["Grupo"];
                                }
                            }
                            $_SESSION["Categoria"] = $grupoDeAgentes;
                        }

                        $salida["Grupo"] = $tipo;
                        $salida["Cliente"] = $_SESSION["Cliente"];
                        $_SESSION["Grupo"] = $tipo;
                        $_SESSION["Campana"] = $campana;
                        $_SESSION["Nombre"] = $row["full_name"];
                        if (NEED_WA) {
                            $query2 = "SELECT allow_wa,user_wa,pass_wa,idclient_wa FROM vicidial_clients_limit WHERE idClient='{$_SESSION["Cliente"]}'";
                            $result2 = sv_mysqli_query($con, $query2);
                            $row4 = sv_mysqli_fetch_array($result2);
                            $_SESSION["allow_waCli"] = $row4["allow_wa"];
                            $_SESSION["user_wa"] = $row4["user_wa"];
                            $_SESSION["pass_wa"] = $row4["pass_wa"];
                            $_SESSION["idclient_wa"] = $row4["idclient_wa"];
                        }
                        if ($_SESSION["Cliente"] != -1) {
                            $query2 = "SELECT allow_chat,userTelevox,passTelevox,allowTelevox,allowGlobalList,allowACD,allowInboundsReports FROM vicidial_clients_limit WHERE idClient='{$_SESSION["Cliente"]}'";
                            $result2 = sv_mysqli_query($con, $query2);
                            $row4 = sv_mysqli_fetch_array($result2);
                            $_SESSION["userTelevox"] = $row4["userTelevox"];
                            $_SESSION["passTelevox"] = $row4["passTelevox"];
                            $_SESSION["allowTelevox"] = $row4["allowTelevox"];
                            $_SESSION["allowGlobalList"] = $row4["allowGlobalList"];
                            $_SESSION["allowACD"] = $row4["allowACD"];
                            $_SESSION["allowInboundsReports"] = $row4["allowInboundsReports"];
                            $_SESSION["allow_chat"] = $row4["allow_chat"];
                        } else {

                            $_SESSION["userTelevox"] = "admin";
                            $_SESSION["passTelevox"] = "admin";
                        }
                        session_write_close();
                    } else {
                        $salida["Estado"] = "error";
                        if ($error == 2) {
                            $salida["Descripcion"] = $this->lang->line("desc_permisosUsuariosCampana");
                        } else {
                            $salida["Descripcion"] = $this->lang->line("desc_errorUsuariosCampanaSel");
                        }
                    }
                } else {
                    $salida["Estado"] = "error";
                    $salida["Descripcion"] = $this->lang->line("desc_permisosUsuariosTake");
                    //header('Location: /Dialvox/index.php');
                }
            } else {
                $salida["Estado"] = "error";
                $salida["Descripcion"] = $this->lang->line("desc_errorUsuariosNotFound");
                //header('Location: /Dialvox/index.php');

            }
            sv_mysqli_close($con);
            $this->output->set_output(json_encode($salida));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }

    public function changeRank()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = limpia($_POST["id"]);
            $sal = array();
            $con = getConnection();
            $cliente = $_SESSION["Cliente"];
            $LOGallowed_campaignsSQL = "AND user_group LIKE '%$cliente%'";
            if ($cliente == -1) {
                $LOGallowed_campaignsSQL = "";
            }
            $query = "SELECT user FROM vicidial_users WHERE user = '$campana' $LOGallowed_campaignsSQL LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $ingroup = limpia($_POST["ingroup"]);
                $rank = limpia($_POST["rank"]);
                $query = "INSERT IGNORE INTO vicidial_inbound_group_agents(user,group_id) VALUE ('$campana','$ingroup')";
                sv_mysqli_query($con, $query);
                $query = "UPDATE vicidial_inbound_group_agents SET group_rank='$rank' WHERE user='$campana' AND group_id='$ingroup'";
                sv_mysqli_query($con, $query);
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosUsuariosEdit");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function coincideGruposDeEntrada($gruposDeEntradaA, $gruposDeEntradaB)
    {
        $gruposResultantes = "";
        for ($i = 0; $i < count($gruposDeEntradaA); $i++) {
            for ($j = 0; $j < count($gruposDeEntradaB); $j++) {
                if (strcmp($gruposDeEntradaA[$i], $gruposDeEntradaB[$j]) === 0) {
                    $gruposResultantes .= ($gruposDeEntradaA[$i] . ' ');
                }
            }
        }
        $gruposResultantes .= '-';
        return $gruposResultantes;
    }
    public function convierteStringGruposDeEntradaAArreglo($gruposDeEntrada)
    {
        $gruposDeEntrada = preg_replace('/-$/', '', $gruposDeEntrada);
        $arrFinal = array();
        $arrGruposDeEntrada = explode(' ', $gruposDeEntrada);
        for ($i = 0; $i < count($arrGruposDeEntrada); $i++) {
            if (strlen($arrGruposDeEntrada[$i]) > 0) {
                $arrFinal[] = trim($arrGruposDeEntrada[$i]);
            }
        }
        return $arrFinal;
    }
    public function changeIngroup()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('usuarios', "spanish");
                break;
            case "en":
                $this->lang->load('usuarios', "english");
                break;
            default:
                $this->lang->load('usuarios', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = limpia($_POST["id"]);
            $sal = array();
            $con = getConnection();
            $cliente = $_SESSION["Cliente"];
            $LOGallowed_campaignsSQL = "AND user_group LIKE '%$cliente%'";
            if ($cliente == -1) {
                $LOGallowed_campaignsSQL = "";
            }
            $query = "SELECT user FROM vicidial_users WHERE user = '$campana' $LOGallowed_campaignsSQL LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $ingroups = limpia($_POST["ingroups"]);
                $query = "UPDATE vicidial_users SET closer_campaigns='$ingroups' WHERE user='$campana'";
                sv_mysqli_query($con, $query);
                $queryEstaActivo = "SELECT campaign_id, NOW() as hoy FROM vicidial_live_agents WHERE user = '$campana' LIMIT 1";
                if ($resultEstaActivo = sv_mysqli_query($con, $queryEstaActivo)) {
                    if ($rowEstaActivo = sv_mysqli_fetch_array($resultEstaActivo)) {
                        $campanaActiva = $rowEstaActivo["campaign_id"];
                        $NOW_TIME = $rowEstaActivo["hoy"];
                        $queryObtenerGruposDeEntradaDeCampana = "SELECT closer_campaigns FROM vicidial_campaigns WHERE campaign_id = '$campanaActiva' LIMIT 1";
                        if ($resultObtenerGruposDeEntradaDeCampana = sv_mysqli_query($con, $queryObtenerGruposDeEntradaDeCampana)) {
                            if ($rowObtenerGruposDeEntradasDeCampana = sv_mysqli_fetch_array($resultObtenerGruposDeEntradaDeCampana)) {
                                $strGruposDeEntradaDeCampana = $rowObtenerGruposDeEntradasDeCampana["closer_campaigns"];
                                $arrGruposDeEntradaDeCampana = $this->convierteStringGruposDeEntradaAArreglo($strGruposDeEntradaDeCampana);
                                $arrGruposDeEntradaDeAgente = $this->convierteStringGruposDeEntradaAArreglo($ingroups);
                                $gruposDeEntradaResultantes = $this->coincideGruposDeEntrada($arrGruposDeEntradaDeAgente, $arrGruposDeEntradaDeCampana);
                                $arrGruposResultantes = $this->convierteStringGruposDeEntradaAArreglo($arrGruposResultantes);
                                $queryCambioVicidialLiveAgents = "UPDATE vicidial_live_agents set external_ingroups='$gruposDeEntradaResultantes',external_blended='0',external_igb_set_user='6666',manager_ingroup_set='SET' where user='$campana'";
                                if ($resultCambioVicidialLiveAgents = sv_mysqli_query($con, $queryCambioVicidialLiveAgents)) {
                                    $queryEliminacionInboundAgents = "DELETE FROM vicidial_live_inbound_agents where user='$campana'";
                                    if ($resultEliminacionInboundAgents = sv_mysqli_query($con, $queryEliminacionInboundAgents)) {
                                        for ($i = 0; $i < count($arrGruposResultantes); $i++) {
                                            if (strlen($arrGruposResultantes[$i]) > 0) {
                                                $queryObtenerStats = "SELECT group_weight,calls_today FROM vicidial_inbound_group_agents where user='$campana' and group_id='$arrGruposResultantes[$i]'";
                                                if ($resultObtenerStats = sv_mysqli_query($con, $queryObtenerStats)) {
                                                    $group_weight = 0;
                                                    $calls_today = 0;
                                                    if ($rowObtenerStats = sv_mysqli_fetch_array($resultObtenerStats)) {
                                                        $group_weight = $row["group_weight"];
                                                        $calls_today = $row["calls_today"];
                                                    }
                                                    $queryInsertaStats = "INSERT INTO vicidial_live_inbound_agents set user='$campana',group_id='$arrGruposResultantes[$i]',group_weight='$group_weight',calls_today='$calls_today',last_call_time='$NOW_TIME',last_call_finish='$NOW_TIME'";
                                                    $resultInsertaStats = sv_mysqli_query($con, $queryInsertaStats);
                                                    if (!$resultInsertaStats) {
                                                        $sal["Estado"] = "error";
                                                        $sal["Descripcion"] = $this->lang->line("desc_changeIngroup_error_db_insertarStats");
                                                    }
                                                } else {
                                                    $sal["Estado"] = "error";
                                                    $sal["Descripcion"] = $this->lang->line("desc_changeIngroup_error_db_obtenerStats");
                                                }
                                            }
                                        }
                                    } else {
                                        $sal["Estado"] = "error";
                                        $sal["Descripcion"] = $this->lang->line("desc_changeIngroup_error_db_eliminarInboundAgents");
                                    }
                                } else {
                                    $sal["Estado"] = "error";
                                    $sal["Descripcion"] = $this->lang->line("desc_changeIngroup_error_db_cambiarVicidialLive");
                                }
                            } else {
                                $sal["Estado"] = "error";
                                $sal["Descripcion"] = $this->lang->line("desc_changeIngroup_error_campanaNoExiste");
                            }
                        } else {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_changeIngroup_error_db_obtenerGruposDeEntradaDeCampana");
                        }
                    }
                    if (!array_key_exists("Estado", $sal)) {
                        $sal["Estado"] = "ok";
                    }
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_changeIngroup_error_db_estaActivoEnSistema");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosUsuariosEdit");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosUsuarios");
            $this->output->set_output(json_encode($sal));
        }
    }

    // Transferencia a agentes
    public function getAgentesParaTransferencia()
    {

        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"];

            $grupo = $_POST["grupo"];

            $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%'";

            $query = "SELECT 
                        a.user as user,
                        u.full_name as name, 
                        a.status as status,
                        a.pause_code as pause_code,
                        ga.Grupo as grupo,
                        g.Grupo as id_grupo 
                    FROM vicidial_live_agents AS a 
                    INNER JOIN vicidial_users as u on a.user = u.user 
                    INNER JOIN dialvox_grupos_agentes as ga ON u.user = ga.Usuario 
                    INNER JOIN dialvox_grupos AS g ON g.Id = ga.Grupo 
                    WHERE 
                        g.Id='$grupo' AND 
                        u.user != '$usuario' AND 
                        u.user_group LIKE '%$cliente%'";

            $sal = array();
            $sal["Registros"] = array();
            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $estado = $row["status"];
                if ($estado == "PAUSED" && $row["pause_code"] == "DAUTO") {
                    $estado = "READY";
                }

                $sal["Registros"][] = array(
                    "usuario" => $row["user"],
                    "nombre" => $row["name"],
                    "estado" => $estado
                );
            }
            $sal["Estado"] = "ok";
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    // Transferencia a agentes
}
