<?php

require_once "BASEPATH.php";
class HomeAdmin extends MY_Controller
{
    public function logout()
    {
        if (!empty($_SESSION["Usuario"])) {
            session_destroy();
            header('Location: ' . MODULOS . 'login');
        }
        header('Location: ' . MODULOS . 'login');
    }
    public function index()
    {
        $this->load->view('homeAdmin/head');
        $this->load->view('homeAdmin/vw_home');
        $this->load->view('homeAdmin/foot');
    }

    public function dameHistorico()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeadmin', "spanish");
                break;
            case "en":
                $this->lang->load('homeadmin', "english");
                break;
            default:
                $this->lang->load('homeadmin', "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');
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $grupo = GRUPO_AGENTES;
            $cliente = $_SESSION["Cliente"];
            $query = "SELECT agents_in_calls,agents_in_dead_calls,agents_in_dispo,agents_in_queue,agents_logged_in,agents_paused,agents_waiting,fecha FROM tabla_grafica_daily WHERE user_group='" . $cliente . "';";
            $result = sv_mysqli_query($con, $query);
            $sal = array();
            /*$sal['cliente']=$cliente;
            $sal['query']=$usuario;*/
            $formato = 'H:i';
            while ($row = sv_mysqli_fetch_array($result)) {
                $fecha = strtotime($row['fecha']);
                $sal[$fecha]['real'] = $row['fecha'];
                $sal[$fecha]['etiqueta'] = date($formato, strtotime($row['fecha']));
                $sal[$fecha]['agents_in_calls'] = $row["agents_in_calls"];
                $sal[$fecha]['agents_in_dead_calls'] = $row["agents_in_dead_calls"];
                $sal[$fecha]['agents_in_dispo'] = $row["agents_in_dispo"];
                $sal[$fecha]['agents_in_queue'] = $row["agents_in_queue"];
                $sal[$fecha]['agents_logged_in'] = $row["agents_logged_in"];
                $sal[$fecha]['agents_paused'] = $row["agents_paused"];
                $sal[$fecha]['agents_waiting'] = $row["agents_waiting"];
            }
            $this->output->set_output(json_encode($sal));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function rellenaHistorico()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeadmin', "spanish");
                break;
            case "en":
                $this->lang->load('homeadmin', "english");
                break;
            default:
                $this->lang->load('homeadmin', "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');
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $grupo = GRUPO_AGENTES;
            $sal = array();
            $cliente = $_SESSION["Cliente"];
            if ($cliente == -1) {
                $cliente = limpia($_POST['Cliente']);
            }
            $sal['cliente'] = $cliente;
            $sal['query'] = $usuario;
            $campana = limpia($_POST["campana"]);
            if ($campana == -1) {
                $campana = "campaign_id";
            } else {
                $campana = "'" . $campana . "'";
            }
            $dondeq = "";
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $dondeq = "campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group  = '$cliente') AND";
            }
            $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 $dondeq campaign_id = $campana AND campaign_id != 'Robot' ORDER BY status DESC, dif ASC, calls_today DESC";
            //$query = " SELECT status FROM vicidial_live_agents WHERE $dondeq ;";
            $result = sv_mysqli_query($con, $query);
            $donde = 0;
            $sal["agents_waiting"] = $sal["agents_paused"] = $sal["agents_in_dead_calls"] = $sal["agents_in_dispo"] = $sal["agents_in_calls"] = $sal["agents_in_queue"] = 0;
            $agentesLogueados = 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["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 FROM vicidial_auto_calls WHERE callerid = '" . $row["callerid"] . "' LIMIT 1");
                    if ($row1 = sv_mysqli_fetch_array($result1)) {
                        $sal["agents_in_calls"]++;
                    } else {
                        $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"]++;
                }

                $agentesLogueados++;
            }
            $sal["agents_logged_in"] = $agentesLogueados;
            $query = "INSERT INTO tabla_grafica_daily (user_group,agents_in_calls,agents_in_dead_calls,agents_in_dispo,agents_in_queue,agents_logged_in,agents_paused,agents_waiting) VALUES ('" . $cliente . "'," . $sal["agents_in_calls"] . "," . $sal['agents_in_dead_calls'] . "," . $sal['agents_in_dispo'] . "," . $sal['agents_in_queue'] . "," . $sal['agents_logged_in'] . "," . $sal['agents_paused'] . "," . $sal['agents_waiting'] . ");";
            sv_mysqli_query($con, $query);
            $sal["query"] = $query;
            $this->output->set_output(json_encode($sal));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function dameInfo()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeadmin', "spanish");
                break;
            case "en":
                $this->lang->load('homeadmin', "english");
                break;
            default:
                $this->lang->load('homeadmin', "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');
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $grupo = GRUPO_AGENTES;
            $and = "";
            $and1 = "";
            if ($_SESSION["Cliente"] != -1) {
                $grupo = $_SESSION["Cliente"] . "_" . GRUPO_AGENTES;
                $and = "AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '" . $_SESSION["Cliente"] . "' UNION SELECT group_id FROM vicidial_inbound_groups WHERE user_group = '" . $_SESSION["Cliente"] . "')";
                $and1 = "AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '" . $_SESSION["Cliente"] . "' UNION SELECT group_id FROM vicidial_inbound_groups WHERE user_group = '" . $_SESSION["Cliente"] . "')";
            } else {
                $query = "SELECT user_group FROM vicidial_user_groups WHERE user_group LIKE '%" . GRUPO_AGENTES . "'";
                $result = sv_mysqli_query($con, $query);
                $grupo = "";
                while ($row = sv_mysqli_fetch_array($result)) {
                    $grupo .= ($row["user_group"] . "|");
                }

                $grupo = substr($grupo, 0, -1);
            }
            $campana = limpia($_POST["campana"]);
            if ($campana == -1) {
                $campana = "campaign_id";
            } else {
                $campana = "'" . $campana . "'";
            }
            $dondeq = "";
            if ($_SESSION["Cliente"] != -1) {
                $cliente = $_SESSION["Cliente"];
                $dondeq = "campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group  = '$cliente') AND";
            }
            $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 $dondeq campaign_id = $campana AND campaign_id != 'Robot' ORDER BY status DESC, dif ASC, calls_today DESC";
            $sal["query1"] = $query;
            $result = sv_mysqli_query($con, $query);
            $donde = 0;
            $sal["agents_waiting"] = $sal["agents_paused"] = $sal["agents_in_dead_calls"] = $sal["agents_in_dispo"] = $sal["agents_in_calls"] = $sal["agents_in_queue"] = 0;
            $agentesLogueados = 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["agentes"][$donde]["CausaPausa"] = $row2["sub_status"];

                            if ($row2["sub_status"] == "DAUTO") {
                                $sal["agents_waiting"]++;
                            } else {
                                $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 FROM vicidial_auto_calls WHERE callerid = '" . $row["callerid"] . "' LIMIT 1");
                    if ($row1 = sv_mysqli_fetch_array($result1)) {
                        $sal["agents_in_calls"]++;
                    } else {
                        $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"]++;
                }

                $agentesLogueados++;
            }
            $sal["agents_logged_in"] = $agentesLogueados;
            $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 1 = 1 $and1 AND campaign_id = $campana AND status NOT IN('XFER')";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $sal["llamadas_activas"] = $row["CUENTA"];
            $sal["hora"] = $row["HORA"];
            $query = "select status,call_type from vicidial_auto_calls where status NOT IN('XFER') and ( (call_type='IN') or (call_type='OUT') ) $and";
            $sal["query2"] = $query;
            $result = sv_mysqli_query($con, $query);
            $ringing_calls = 0;
            $in_ivr = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                if (!preg_match("/LIVE|CLOSER/i", $row[0])) {
                    $ringing_calls++;
                }
                if (!preg_match("/LIVE/i", $row[0]) && preg_match("/IN/i", $row[1])) {
                    $in_ivr++;
                }
            }
            $sal["llamadasEntrantes"] = $in_ivr;

            $sal["Estado"] = "ok";
            $sal["llamadas_sonando"] = $ringing_calls;
            $this->output->set_output(json_encode($sal));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
}
