<?php

require_once "BASEPATH.php";

class ReporteTiempoReal extends MY_Controller
{
    public function realTimeReport()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportetiemporeal', "spanish");
                break;
            case "en":
                $this->lang->load('reportetiemporeal', "english");
                break;
            default:
                $this->lang->load('reportetiemporeal', "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';
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sal = array();
            $campana = limpia($_GET["campana"]);
            $con = getConnection();
            if ($campana == -1) {
                $campana = "campaign_id";
            } else {
                $campana = "'" . $campana . "'";
            }
            $dondeq = "";
            $dondeq1 = "";
            $dondeq2 = "";
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $dondeq = "campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group  = '$cliente') AND";
                $dondeq1 = "AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group  = '$cliente') ";
                $dondeq2 = "AND user_group LIKE '$cliente%'";
            }
            $grupo = limpia($_GET["grupo"]);
            $andGrupo = "";
            if ($grupo != -1) {
                $query = "SELECT Usuario FROM dialvox_grupos_agentes WHERE Grupo = '$grupo'";
                $result = sv_mysqli_query($con, $query);
                $listaUsuarios = "";
                while ($row = sv_mysqli_fetch_array($result)) {
                    $listaUsuarios .= "'" . $row["Usuario"] . "',";
                }
                if ($listaUsuarios != "") {
                    $listaUsuarios = substr($listaUsuarios, 0, -1);
                    $andGrupo = "AND user IN ($listaUsuarios)";
                } else {
                    $andGrupo = "AND 1 = 2";
                }
            }
            $query = "SELECT *, TIMESTAMPDIFF(SECOND,vicidial_live_agents.last_state_change,NOW()) as dif, (SELECT full_name from vicidial_users where user = vicidial_live_agents.user) as nombre, (SELECT user from vicidial_users where user = vicidial_live_agents.user) as usuario,(SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) as nomCampa FROM vicidial_live_agents WHERE $dondeq campaign_id = $campana AND campaign_id <> 'Robot' $andGrupo";
            $query .= " ORDER BY status DESC, dif ASC, calls_today DESC";
            $result = sv_mysqli_query($con, $query);
            $donde = 0;
            $sal["agentes"] = array();
            $sal["agents_waiting"] = $sal["agents_paused"] = $sal["agents_in_dead_calls"] = $sal["agents_in_dispo"] = $sal["agents_in_calls"] = $sal["agents_in_queue"] = 0;
            while ($row = sv_mysqli_fetch_array($result)) {

                if ($row["status"] == "CLOSER") {
                    $row["status"] = "READY";
                }

                if ($row["status"] == "PAUSED") {
                    if ($row["dif"] >= 21600) {
                        continue;
                    } else {
                        if ($row["lead_id"] > 0) {
                            $row["status"] = "DISPO";
                        } else {
                            $log_id = $row["agent_log_id"];
                            $query2 = "SELECT sub_status FROM vicidial_agent_log WHERE agent_log_id>= $log_id AND user = '" . $row["user"] . "' ORDER BY agent_log_id DESC LIMIT 1";
                            $result2 = sv_mysqli_query($con, $query2);
                            $row2 = sv_mysqli_fetch_array($result2);
                            //$sal[$donde]["CausaPausa"] = $row2["sub_status"];
                            $sal["agentes"][$donde]["CausaPausa"] = $row2["sub_status"];
                            $sal["agents_paused"]++;
                        }
                    }
                }
                if ($row["status"] == "READY") {
                    if ($row["lead_id"] > 0) {
                        $row["status"] = "DISPO";
                    } else {
                        $sal["agents_waiting"]++;
                    }
                }
                if ($row["status"] == "INCALL") {
                    $result1 = sv_mysqli_query($con, "SELECT callerid,phone_number FROM vicidial_auto_calls WHERE callerid = '" . $row["callerid"] . "' LIMIT 1");
                    if ($row1 = sv_mysqli_fetch_array($result1)) {
                        $sal["agents_in_calls"]++;
                        $sal["agentes"][$donde]["TelefonoActual"] = $row1["phone_number"];
                    } else {
                        $sal["agentes"][$donde]["TelefonoActual"] = '';
                        $row["status"] = "DEAD";
                    }
                }
                if ($row["status"] == "DISPO") {
                    $sal["agents_in_dispo"]++;
                }

                if ($row["status"] == "DEAD") {
                    $sal["agents_in_dead_calls"]++;
                }

                if ($row["status"] == "QUEUE") {
                    $sal["agents_in_queue"]++;
                }
                if ($row["comments"] === "INBOUND") {
                    $sal["agentes"][$donde]["TipoLlamada"] = "Entrada";
                } else {
                    $sal["agentes"][$donde]["TipoLlamada"] = "Salida";
                }
                $query5 = "DELETE FROM ayuda WHERE TIMESTAMPDIFF(SECOND,hora,NOW())>30";
                $result5 = sv_mysqli_query($con, $query5);
                $query5 = "SELECT TIMESTAMPDIFF(SECOND,hora,NOW()) AS segundos FROM ayuda WHERE usuario ='" . $row["user"] . "' ORDER BY hora DESC LIMIT 1";
                $result5 = sv_mysqli_query($con, $query5);
                if ($row9 = sv_mysqli_fetch_array($result5)) {
                    $sal["agentes"][$donde]["ayuda"] = $row9["segundos"];
                } else {
                    $sal["agentes"][$donde]["ayuda"] = 0;
                }

                $query5 = "SELECT TIMESTAMPDIFF(SECOND,fecha,NOW()) AS segundos FROM dialvox_pausa_report WHERE agente ='" . $row["user"] . "' AND TIMESTAMPDIFF(SECOND,fecha,NOW()) <= 20 LIMIT 1";
                $result5 = sv_mysqli_query($con, $query5);
                if ($row9 = sv_mysqli_fetch_array($result5)) {
                    $sal["agentes"][$donde]["pausa"] = $row9["segundos"];

                } else {
                    $sal["agentes"][$donde]["pausa"] = null;
                }

                $sal["agentes"][$donde]["Campana"] = $row["nomCampa"];
                $sal["agentes"][$donde]["Nombre"] = $row["nombre"];
                $sal["agentes"][$donde]["Extension"] = $row["extension"];
                $sal["agentes"][$donde]["Status"] = $row["status"];
                $usuarioReporteReal = $sal["agentes"][$donde]["idUsuario"] = $row["usuario"];
                //$sal["agentes"][$donde]["TelefonoActual"] = $row["currentPhone"] == NULL ? '' : $row["currentPhone"];
                $sal["agentes"][$donde]["Tiempo"] = $row["dif"];
                $totalLlamads = intval($row["calls_today"]);
                $sal["agentes"][$donde]["Llamadas"] = "$totalLlamads";
                $sal["agentes"][$donde]["session_id"] = $row["conf_exten"];
                $color = "";
                if ($sal["agentes"][$donde]["Status"] == "PAUSED") {
                    $color = "rgba(255,152,0," . (($row["dif"] / 350) + .20) . ")";
                }

                if ($sal["agentes"][$donde]["Status"] == "INCALL") {
                    $color = "rgba(39,195,74," . (($row["dif"] / 350) + .20) . ")";
                }

                if ($sal["agentes"][$donde]["Status"] == "DISPO") {
                    $color = "rgba(244,67,54," . (($row["dif"] / 350) + .20) . ")";
                }

                if ($sal["agentes"][$donde]["Status"] == "DEAD") {
                    $color = "rgba(96,125,139," . (($row["dif"] / 350) + .20) . ")";
                }

                if ($sal["agentes"][$donde]["Status"] == "READY") {
                    $color = "rgba(3,169,244," . (($row["dif"] / 350) + .20) . ")";
                }

                if ($sal["agentes"][$donde]["Status"] == "QUEUE") {
                    $color = "rgba(39,195,74," . (($row["dif"] / 350) + .20) . ")";
                }

                if ($sal["agentes"][$donde]["Status"] == "PAUSED") {
                    $sal["agentes"][$donde]["Status"] = "Pausado";
                }

                if ($sal["agentes"][$donde]["Status"] == "INCALL") {
                    $sal["agentes"][$donde]["Status"] = "En llamada";
                }

                if ($sal["agentes"][$donde]["Status"] == "DISPO") {
                    $sal["agentes"][$donde]["Status"] = "Calificando";
                }

                if ($sal["agentes"][$donde]["Status"] == "DEAD") {
                    $sal["agentes"][$donde]["Status"] = "Llamada Cortada";
                }

                if ($sal["agentes"][$donde]["Status"] == "READY") {
                    $sal["agentes"][$donde]["Status"] = "Disponible";
                }

                if ($sal["agentes"][$donde]["Status"] == "QUEUE") {
                    $sal["agentes"][$donde]["Status"] = "En cola";
                }

                $sal["agentes"][$donde]["Color"] = $color;

                $query6 = "SELECT id,latencia_telefonia, latencia_dialvox, latencia_vicidial, ip_telefonia, ip_web, fecha_telefonia, fecha_dialvox, fecha_vicidial FROM dialvox_latencias WHERE usuario = '" . $row["user"] . "' LIMIT 1";
                $result6 = mysqli_query($con, $query6);
                if ($latencia = mysqli_fetch_assoc($result6)) {
                    $sal["agentes"][$donde]["latencia_telefonia"] = $latencia["latencia_telefonia"];
                    $sal["agentes"][$donde]["latencia_dialvox"] = $latencia["latencia_dialvox"];
                } else {
                    $sal["agentes"][$donde]["latencia_telefonia"] = null;
                    $sal["agentes"][$donde]["latencia_dialvox"] = null;
                }

                $queryPauseCode = "SELECT COUNT(id_report) AS Cant FROM dialvox_pausa_report WHERE agente='$usuarioReporteReal' AND DATE(fecha)=CURRENT_DATE AND resuelto=0";
                $resultPauseCode = sv_mysqli_query($con, $queryPauseCode);
                if ($rowa = sv_mysqli_fetch_array($resultPauseCode)) {
                    if ($rowa["Cant"] > 0) {
                        $sal["agentes"][$donde]["requiereAprovacion"] = true;
                    } else {
                        $sal["agentes"][$donde]["requiereAprovacion"] = false;
                        $sal["agentes"][$donde]["pausa"] = null;
                    }

                } else {
                    $sal["agentes"][$donde]["requiereAprovacion"] = false;
                }

                $donde++;
            }
            $sal["agentes_total"] = $donde;
            $query = "select now() AS AHORA, avg(auto_dial_level) AS NIVEL,max(dial_status_a) as METODO,max(dial_status_b),max(dial_status_c),max(dial_status_d),max(dial_status_e),max(lead_order) AS ORDEN,max(lead_filter_id) AS FILTRO,max(hopper_level) AS HP1,max(dial_method),max(adaptive_maximum_level),avg(adaptive_dropped_percentage),avg(adaptive_dl_diff_target),avg(adaptive_intensity),max(available_only_ratio_tally),max(adaptive_latest_server_time),max(local_call_time),max(dial_timeout),max(dial_statuses) AS ESTATUS,max(agent_pause_codes_active),max(list_order_mix),max(auto_hopper_level) AS HP2 from vicidial_campaigns WHERE $dondeq campaign_id = $campana";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);

            $query = "select sum(dialable_leads),sum(calls_today),sum(drops_today),avg(drops_answers_today_pct),avg(differential_onemin),avg(agents_average_onemin),sum(balance_trunk_fill),sum(answers_today),max(status_category_1),sum(status_category_count_1),max(status_category_2),sum(status_category_count_2),max(status_category_3),sum(status_category_count_3),max(status_category_4),sum(status_category_count_4),sum(agent_calls_today),sum(agent_wait_today),sum(agent_custtalk_today),sum(agent_acw_today),sum(agent_pause_today) from vicidial_campaign_stats where $dondeq campaign_id = $campana";
            $result = sv_mysqli_query($con, $query);
            $row2 = sv_mysqli_fetch_array($result);

            $query = "select sum(local_trunk_shortage) from vicidial_campaign_server_stats WHERE $dondeq campaign_id = $campana";
            $result = sv_mysqli_query($con, $query);
            $row3 = sv_mysqli_fetch_array($result);

            $query = "select sum(calls_today),sum(drops_today),sum(answers_today) from vicidial_campaign_stats where $dondeq campaign_id = $campana";
            $result = sv_mysqli_query($con, $query);
            $row4 = sv_mysqli_fetch_array($result);

            $query = "select count(*) from vicidial_hopper WHERE $dondeq campaign_id = $campana";
            $result = sv_mysqli_query($con, $query);
            $row5 = sv_mysqli_fetch_array($result);

            $query = "SELECT list_id FROM vicidial_lists WHERE campaign_id = $campana $dondeq1 AND active = 'Y'";
            $result = sv_mysqli_query($con, $query);
            $listasIn = "";
            while ($rowListasXd = sv_mysqli_fetch_array($result)) {
                $listasIn .= "'" . $rowListasXd["list_id"] . "',";
            }
            if ($listasIn != "") {
                $listasIn = substr($listasIn, 0, -1);
                $listasIn2 = "list_id IN ($listasIn) AND ";
            } else {
                $listasIn2 = "1 = 2 AND";
            }
            $query = "SELECT (SELECT COUNT(uniqueid) FROM vicidial_log WHERE $listasIn2 status IN ('DROP','PDROP')) AS dejadas, (SELECT COUNT(uniqueid) FROM vicidial_log WHERE $listasIn2 status NOT IN ('DROP','PDROP')) AS contestadas";
            //$sal["query"] = $query;
            $result6 = sv_mysqli_query($con, $query);
            $row6 = sv_mysqli_fetch_array($result6);

            $sal["nivel"] = (float) $row["NIVEL"];
            $sal["filtro"] = $row["FILTRO"];
            $sal["volcado"] = $row3[0] . "/" . $row2[6];
            $sal["registros"] = $row2[0];
            $sal["tiempo"] = $row["AHORA"];
            $sal["llamadas"] = $row4[0];
            $sal["agentesProm"] = $row2[5];
            $sal["metodo"] = $row["METODO"];
            $sal["hopper"] = $row["HP1"] . "/" . $row["HP2"];
            //$sal["dejadas"] = $row4[1]."/".$row4[2];
            $sal["dejadas"] = $row6[0] . "/" . $row6[1];
            $sal["dejadasDejadas"] = $row6[0];
            $sal["dejadasContestadas"] = $row6[1];
            $sal["dl"] = sprintf("%01.2f", $row2[4]);
            $sal["estados"] = $row["ESTATUS"];
            $sal["registrosHopper"] = $row5[0];
            $drpctTODAY = 0.0;
            if ($row4[2] > 0) {
                $drpctTODAY = (($row4[1] / $row4[2]) * 100);
                $drpctTODAY = round($drpctTODAY, 2);
                $drpctTODAY = sprintf("%01.2f", $drpctTODAY);
            }
            $sal["porcentaje"] = $drpctTODAY;
            $sal["diff"] = $row2[4];
            $sal["orden"] = $row["ORDEN"];
            $query = "select MAX(adaptive_maximum_level) as maximo from vicidial_campaigns WHERE $dondeq campaign_id = $campana";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $sal["maximo"] = (float) $row["maximo"];
            $sal["Estado"] = "ok";
            $stmt = "select closer_campaigns from vicidial_campaigns where active='Y' and $dondeq campaign_id = $campana";
            $rslt = sv_mysqli_query($con, $stmt);
            $closer_campaigns = "";
            while ($row = sv_mysqli_fetch_array($rslt)) {
                $closer_campaigns .= "$row[0]";
            }
            $closer_campaigns = preg_replace("/^ | -$/", "", $closer_campaigns);
            $closer_campaigns = preg_replace("/ - /", " ", $closer_campaigns);
            $closer_campaigns = preg_replace("/ /", "','", $closer_campaigns);
            $closer_campaignsSQL = "'$closer_campaigns'";
            $query = "SELECT status,campaign_id,phone_number,server_ip,UNIX_TIMESTAMP(call_time),call_type,queue_priority,agent_only from vicidial_auto_calls where status NOT IN('XFER') and ( (call_type='IN' and campaign_id IN($closer_campaignsSQL)) or (call_type IN('OUT','OUTBALANCE') and $dondeq campaign_id = $campana) ) order by queue_priority desc,campaign_id,call_time";
            $k = 0;
            $agentonlycount = 0;
            $rslt = sv_mysqli_query($con, $query);
            $parked_to_print = sv_mysqli_num_rows($rslt);
            $CDstatus = $CDcampaign_id = $CDphone_number = $CDserver_ip = $CDcall_time = $CDcall_type = $CDqueue_priority = $CDagent_only = array();
            $out_total = 0;
            $out_ring = 0;
            $out_live = 0;
            $in_ivr = 0;
            $out_calls = 0;
            if ($parked_to_print > 0) {
                $i = 0;
                $out_total = 0;
                $out_ring = 0;
                $out_live = 0;
                $in_ivr = 0;
                $out_calls = 0;
                while ($i < $parked_to_print) {
                    $row = sv_mysqli_fetch_array($rslt);
                    if (preg_match("/LIVE/i", $row[0])) {
                        $out_live++;
                    } else {
                        if (preg_match("/IN/i", $row[5])) {
                            $in_ivr++;
                        }
                        if (preg_match("/OUT/i", $row[5])) {
                            $out_calls++;
                        }
                        if (!preg_match("/CLOSER/i", $row[0])) {
                            $out_ring++;
                        }
                    }
                    $out_total++;
                    $i++;
                }
            }
            $sal["llamadasActivas"] = $out_total;
            $sal["llamadasSonando"] = $out_ring;
            $sal["llamadasEsperandoPorAgentes"] = $out_live;
            $sal["llamadasEnIVR"] = $in_ivr;
            $sal["llamadasSalientes"] = $out_calls;

            $sal["llamadasEntrantes"] = array();
            $query = "SELECT vig.group_name,vac.phone_number,vac.agent_only,vac.agent_grab,TIMESTAMPDIFF(SECOND,vac.call_time,NOW()) AS seconds,vac.campaign_id FROM vicidial_auto_calls AS vac INNER JOIN vicidial_inbound_groups AS vig ON vig.group_id=vac.campaign_id WHERE (vac.campaign_id IN ($closer_campaignsSQL) OR vac.campaign_id = 'AGENTDIRECT') AND vac.call_type='IN' AND vac.status='LIVE' ORDER BY vac.queue_priority DESC,vac.campaign_id,vac.call_time";
            $result = sv_mysqli_query($con, $query);
            $sal["ERROR"] = mysqli_error($con);
            while ($row = sv_mysqli_fetch_array($result)) {
                $mostrar = true;
                if ($row["campaign_id"] == 'AGENTDIRECT') {
                    $STRqueryBuscarAgente = "SELECT COUNT(user) AS CUENTA FROM vicidial_users WHERE user = '" . $row["agent_only"] . "' $dondeq2 LIMIT 1";
                    if ($queryBuscarAgente = sv_mysqli_query($con, $STRqueryBuscarAgente)) {
                        if ($rowBuscarAgente = sv_mysqli_fetch_array($queryBuscarAgente)) {
                            if ($rowBuscarAgente["CUENTA"] == 0) {
                                $mostrar = false;
                            }
                        } else {
                            $mostrar = false;
                        }
                    } else {
                        $mostrar = false;
                    }

                }
                if ($mostrar) {
                    $fila = array();
                    $fila["Grupo"] = $row["group_name"];
                    $fila["Telefono"] = $row["phone_number"];
                    $fila["AgentOnly"] = $row["agent_only"];
                    $fila["AgentGrab"] = $row["agent_grab"];
                    $fila["tiempo"] = $row["seconds"];
                    $sal["llamadasEntrantes"][] = $fila;
                }
            }
            $this->output->set_output(json_encode($sal));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosTiempoReal");
            $this->output->set_output(json_encode($sal));
        }
    }

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

        include_once RUTA_APP . 'Conexion.php';
        if (1 == 1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sal = array();
            $agente = $_POST["agente"];
            $con = getConnection();
            $query = "SELECT *, TIMESTAMPDIFF(SECOND,vicidial_live_agents.last_state_change,NOW()) as dif, (SELECT full_name from vicidial_users where user = vicidial_live_agents.user) as nombre,(SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) as nomCampa FROM vicidial_live_agents WHERE campaign_id != 'Robot' and user = '$agente' ORDER BY status DESC, dif ASC, calls_today DESC";
            $sal["query"] = $query;
            $result = sv_mysqli_query($con, $query);
            $donde = 0;
            if ($row = sv_mysqli_fetch_array($result)) {
                if ($row["status"] == "PAUSED") {
                    if ($row["dif"] >= 21600) {
                    }
                    if ($row["lead_id"] > 0) {
                        $row["status"] = "DISPO";
                    } else {
                        $log_id = $row["agent_log_id"];
                        $query2 = "SELECT sub_status FROM vicidial_agent_log WHERE agent_log_id>= $log_id AND user = '" . $row["user"] . "' ORDER BY agent_log_id DESC LIMIT 1";
                        $result2 = sv_mysqli_query($con, $query2);
                        $row2 = sv_mysqli_fetch_array($result2);
                        //$sal[$donde]["CausaPausa"] = $row2["sub_status"];
                        $sal["CausaPausa"] = $row2["sub_status"];
                    }
                }
                if ($row["status"] == "READY") {
                    if ($row["lead_id"] > 0) {
                        $row["status"] = "DISPO";
                    } else {
                    }
                }
                if ($row["status"] == "INCALL") {
                    $result = sv_mysqli_query($con, "SELECT callerid FROM vicidial_auto_calls WHERE callerid = '" . $row["callerid"] . "' LIMIT 1");
                    if ($row1 = sv_mysqli_fetch_array($result)) {
                    } else {
                        $row["status"] = "DEAD";
                    }
                }
                $sal["Campana"] = $row["nomCampa"];
                $sal["Nombre"] = $row["nombre"];
                $sal["Extension"] = $row["extension"];
                $sal["Status"] = $row["status"];
                $sal["idUsuario"] = $row["user"];
                $sal["Tiempo"] = $row["dif"];
                $sal["Llamadas"] = $row["calls_today"];
                if ($row["comments"] == "INBOUND") {
                    $sal["TipoLlamada"] = "Entrada";
                } else {
                    $sal["TipoLlamada"] = "Salida";
                }
                $sal["Estado"] = "ok";
                $color = "";
            } else {
                $sal["Estado"] = "error";
            }
            $this->output->set_output(json_encode($sal));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosTiempoReal");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function index()
    {
        include_once RUTA_APP . 'Conexion.php';
        $webSocketURL = "wss://" . SERVER_IP . ":8089/ws";
        $con = getConnection();
        $query = "SELECT web_socket_url FROM servers WHERE server_ip = '" . limpia(SERVER_IP_REAL) . "' LIMIT 1";
        if ($result = sv_mysqli_query($con, $query)) {
            if ($row = sv_mysqli_fetch_array($result)) {
                $webSocketURL = $row["web_socket_url"];
            }
        }
        sv_mysqli_close($con);
        $data = array(
            "webSocketURL" => $webSocketURL,
        );
        $this->load->view('reporteTiempoReal/head');
        $this->load->view('reporteTiempoReal/vw_reporte_tiempo_real', $data);
        $this->load->view('reporteTiempoReal/foot');
    }
    public function monitor()
    {
        $this->load->view('reporteTiempoReal/monitor');
    }
    public function barge()
    {
        $this->load->view('reporteTiempoReal/barge');
    }
    public function iniciaMonitor()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sesion_id = str_replace("SIP/", "", $_POST["sesion_id"]);

            $nombreFile = "tuGfa_" . $usuario . "_" . time() . "_" . mt_rand(1, 50);
            $fp = fopen("/var/spool/asterisk/outgoing/" . $nombreFile, 'w');
            fwrite($fp, "Channel: SIP/" . $usuario . "\n");
            fwrite($fp, "MaxRetries: 2\n");
            fwrite($fp, "Callerid: \"Dialvox\"\n");
            fwrite($fp, "RetryTime: 2000\n");
            fwrite($fp, "WaitTime: 30\n");
            fwrite($fp, "Archive: yes\n");
            fwrite($fp, "Context: " . CONTEXTO_SISTEMA . "\n");
            fwrite($fp, "Extension: 201" . $sesion_id . "\n");
            fwrite($fp, "Priority: 1\n");
            fclose($fp);
            $sal["Estado"] = "ok";
            $sal["File_Name"] = $nombreFile;
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function iniciaBarge()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sesion_id = str_replace("SIP/", "", $_POST["sesion_id"]);

            $nombreFile = "tuGfa_" . $usuario . "_" . time() . "_" . mt_rand(1, 50);
            $fp = fopen("/var/spool/asterisk/outgoing/" . $nombreFile, 'w');
            fwrite($fp, "Channel: SIP/" . $usuario . "\n");
            fwrite($fp, "MaxRetries: 2\n");
            fwrite($fp, "Callerid: \"Dialvox\"\n");
            fwrite($fp, "RetryTime: 2000\n");
            fwrite($fp, "WaitTime: 30\n");
            fwrite($fp, "Archive: yes\n");
            fwrite($fp, "Context: " . CONTEXTO_SISTEMA . "\n");
            fwrite($fp, "Extension: 202" . $sesion_id . "\n");
            fwrite($fp, "Priority: 1\n");
            fclose($fp);
            $sal["Estado"] = "ok";
            $sal["File_Name"] = $nombreFile;
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function eliminarAyuda()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_POST["usuario"];
            $query = "DELETE FROM ayuda WHERE usuario = '$usuario'";
            $con = getConnection();
            $result = sv_mysqli_query($con, $query);
            $sal = array(
                "Estado" => "ok",
                "Resultado" => $result,
            );
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function iniciaHijack()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sesion_id = str_replace("SIP/", "", $_POST["sesion_id"]);

            $nombreFile = "tuGfa_" . $usuario . "_" . time() . "_" . mt_rand(1, 50);
            $fp = fopen("/var/spool/asterisk/outgoing/" . $nombreFile, 'w');
            fwrite($fp, "Channel: SIP/" . $usuario . "\n");
            fwrite($fp, "MaxRetries: 2\n");
            fwrite($fp, "Callerid: \"Dialvox\"\n");
            fwrite($fp, "RetryTime: 2000\n");
            fwrite($fp, "WaitTime: 30\n");
            fwrite($fp, "Archive: yes\n");
            fwrite($fp, "Context: " . CONTEXTO_SISTEMA . "\n");
            fwrite($fp, "Extension: 200" . $sesion_id . "\n");
            fwrite($fp, "Priority: 1\n");
            fclose($fp);
            $sal["Estado"] = "ok";
            $sal["File_Name"] = $nombreFile;
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    ////// Gamificacion

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

        if (
            (!empty($_SESSION["Usuario"])
                && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES))
        ) {

            header('Content-type: application/json');

            include_once RUTA_APP . 'Sesiones.php';
            include_once RUTA_APP . 'Conexion.php';
            $con = getConnection();

            $users = $_POST["users"];
            $status = $_POST["status"];
            $dateIni = $_POST["dateIni"];
            $dateFin = $_POST["dateFin"];
            $campanas = $_POST["campanas"];
            $archived = false;
            if (isset($_POST["archived"]) && limpia($_POST["archived"]) == 1) {
                $archived = true;
            }
            if ($campanas === "") {
                $campanas = "";
            } else {
                $campanas = "'" . str_replace(",", "','", $campanas) . "'";
            }

            $userWhere = "user IN ('$users')";
            $statusWhere = "AND status IN ('$status')";
            $closerCampaignsArray = array();
            $closerCampaigns = "";

            if ($campanas === "") {
                $campaignWhere = "";
            }

            $where = "";

            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $where = "campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group  = '$cliente') AND";
            }

            $query_ingroups = "SELECT closer_campaigns FROM vicidial_campaigns WHERE campaign_id IN ($campanas)";

            if ($campanas === "" || $campanas === "''") {
                $query_ingroups = "SELECT closer_campaigns FROM vicidial_campaigns WHERE campaign_id IN ('')";
            }

            $result_closer = sv_mysqli_query($con, $query_ingroups);

            while ($row = sv_mysqli_fetch_array($result_closer)) {
                $closerCampaignsArray[] =
                "'" . implode("','", explode(" ", $row["closer_campaigns"])) . "'";
            }

            $closerCampaigns = implode(",", $closerCampaignsArray);

            $campaignWhere = "AND campaign_id IN ($campanas, $closerCampaigns)";

            if ($campanas === "") {
                $campaignWhere = "";
            }

            $query = "SELECT COUNT(*) as count, user FROM vicidial_log WHERE $where DATE(call_date) >= DATE('$dateIni') AND DATE(call_date) <= DATE('$dateFin') AND $userWhere $statusWhere $campaignWhere GROUP BY user ";

            if ($archived) {
                $query .= " UNION SELECT COUNT(*) as count, user FROM vicidial_log_archive WHERE $where DATE(call_date) >= DATE('$dateIni') AND DATE(call_date) <= DATE('$dateFin') AND $userWhere $statusWhere $campaignWhere GROUP BY user ";
            }
            $query = "SELECT SUM(T.count) AS count,T.user AS user FROM ($query) AS T GROUP BY T.user ORDER BY T.count DESC ";

            $query2 = "SELECT COUNT(*) as count, user FROM vicidial_closer_log WHERE DATE(call_date) >= DATE('$dateIni') AND DATE(call_date) <= DATE('$dateFin') AND $userWhere $statusWhere $campaignWhere GROUP BY user";
            if ($archived) {
                $query2 .= " UNION SELECT COUNT(*) as count, user FROM vicidial_closer_log WHERE DATE(call_date) >= DATE('$dateIni') AND DATE(call_date) <= DATE('$dateFin') AND $userWhere $statusWhere $campaignWhere GROUP BY user";
            }
            $query2 = "SELECT SUM(T.count) AS count, T.user AS user FROM ($query2) AS T GROUP BY T.user ORDER BY T.count DESC";
            $activos = "vicidial_users as T";

            if ($_POST["activos"] === 'true') {
                $activos = "vicidial_live_agents as T";
            }

            $query_users = "SELECT user, (SELECT full_name FROM vicidial_users WHERE user = T.user LIMIT 1) as full_name FROM $activos WHERE $userWhere";

            $result = sv_mysqli_query($con, $query);
            $result2 = sv_mysqli_query($con, $query2);
            $result_users = sv_mysqli_query($con, $query_users);

            $sal = array(
                "Registros" => array(),
            );

            while ($row = sv_mysqli_fetch_array($result_users)) {
                $sal["Registros"][$row["user"]] = array(
                    "count" => 0,
                    "fullName" => $row["full_name"],
                );
            }

            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Registros"][$row["user"]]["count"] = $row["count"];
            }

            while ($row = sv_mysqli_fetch_array($result2)) {
                $sal["Registros"][$row["user"]]["count"] += $row["count"];
            }
            $sal["QUERY"] = $query;
            $sal["QUERY2"] = $query2;
            $sal["Estado"] = "ok";

            sv_mysqli_close($con);

            $this->output->set_output(json_encode($sal));
        } else {

            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosTiempoReal");
            $this->output->set_output(json_encode($sal));
        }
    }

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

        if (
            (!empty($_SESSION["Usuario"])
                && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES))
        ) {

            header('Content-type: application/json');

            include_once RUTA_APP . 'Sesiones.php';
            include_once RUTA_APP . 'Conexion.php';

            $where = "";

            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $where = "user_group  = '$cliente'";
            }

            $query_campaigns = "SELECT campaign_id,campaign_name FROM vicidial_campaigns WHERE $where";

            $con = getConnection();
            $result_campaigns = sv_mysqli_query($con, $query_campaigns);

            $sal = array(
                "Agentes" => array(),
                "Estados" => array(),
                "Campanas" => array(),
            );

            $tmpWhere = array();
            while ($row = sv_mysqli_fetch_array($result_campaigns)) {
                $cid = $row["campaign_id"];
                $sal["Campanas"][] = array(
                    "label" => $row["campaign_name"],
                    "value" => $cid,
                );
                $tmpWhere[] = $cid;
            }

            $cids = implode("','", $tmpWhere);
            $where = "campaign_id IN ('$cids')";
            $campanas = $_POST["campanas"];

            $query = "SELECT status,status_name FROM vicidial_campaign_statuses WHERE $where AND campaign_id IN ('$campanas')";

            $cliente = $_SESSION["Cliente"] . "_AGENTES";

            // Se hace la query para obtener los usuarios
            // si discriminar de los activos
            // y se crea una bandera para los
            // activos
            $usuarios = "SELECT user FROM vicidial_users WHERE user_group='$cliente'";
            $res_usuarios = sv_mysqli_query($con, $usuarios);
            $checar_activos = $_POST["activos"] === 'true';

            if ($checar_activos) {

                // Si se tienen que listar
                // solo los agentes activos
                // se guardan los del cliente
                // en un arreglo para
                // hacer la query de los live_agents
                $arr_usuarios_cliente = [];
                while (
                    $row_usuarios = sv_mysqli_fetch_array($res_usuarios)
                ) {
                    $arr_usuarios_cliente[] = $row_usuarios["user"];
                }

                $str_usuarios_cliente = implode(
                    "','",
                    $arr_usuarios_cliente
                );

                $usuarios = "SELECT user FROM vicidial_live_agents WHERE user IN ('$str_usuarios_cliente') AND campaign_id IN ('$campanas')";
                $res_usuarios = sv_mysqli_query($con, $usuarios);
            }

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

            while ($row = sv_mysqli_fetch_array($res_usuarios)) {
                $user = $row["user"];
                $sal["Agentes"][] = array(
                    "label" => $user,
                    "value" => $user,
                );
            }

            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Estados"][] = array(
                    "label" => $row["status_name"],
                    "value" => $row["status"],
                );
            }

            $sal["Estado"] = "ok";

            sv_mysqli_close($con);

            $this->output->set_output(json_encode($sal));
        } else {

            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosSalientes");
            $this->output->set_output(json_encode($sal));
        }
    }

    ////// Gamificacion

}
