<?php

require_once "BASEPATH.php";
include_once "Clases/ConfigExtras.php";
include_once "Clases/ConfigOmnicanalidad.php";

class Login extends MY_Controller
{
    public function validaExtension()
    {
        require_once RUTA_APP . 'Conexion.php';
        $con = getConnection();
        $extension = limpia($_POST['extension']);
        $pass = limpia($_POST['pass']);
        $query = "SELECT extension FROM phones WHERE login IN (SELECT logins_list FROM phones_alias WHERE BINARY alias_name='$extension') AND active = 'Y' AND BINARY pass='$pass' LIMIT 1";
        $salida = array();
        $result = sv_mysqli_query($con, $query);
        if ($row = sv_mysqli_fetch_array($result)) {
            $salida["Estado"] = "ok";
            $salida["Extension"] = $row["extension"];
        } else {
            $salida["Estado"] = "error";
        }
        sv_mysqli_close($con);
        header('Content-type: application/json');
        $this->output->set_output(json_encode($salida));
    }
    public function campanas()
    {
        require_once RUTA_APP . 'Conexion.php';
        $con = getConnection();
        $user = limpia($_POST['user']);
        $pass = limpia($_POST['pass']);
        $query = "SELECT user_group FROM vicidial_users  WHERE BINARY user = '$user' AND BINARY pass = '$pass' AND active = 'Y' LIMIT 1";
        $result = sv_mysqli_query($con, $query);
        $salida = array();
        if ($row = sv_mysqli_fetch_array($result)) {
            $salida["Estado"] = "Ok";
            $grupo = $row["user_group"];
            $salida["Campanas"] = array();
            $cliente = "";
            $a = strpos($grupo, "_");
            $salida["Tipo"] = GRUPO_AGENTES;
            if (strpos($grupo, GRUPO_ADMINS) !== false) {
                $salida["Tipo"] = GRUPO_ADMINS;
            }

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

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

            if ($a === false) {
                $cliente = -1;
            } else {
                $cliente = "";
                for ($i = $a - 1; $i >= 0; $i--) {
                    $cliente .= $grupo[$i];
                }
                $cliente = strrev($cliente);
            }
            $and = "";
            if ($cliente != -1) {
                //$and = "AND (user_group = '".$cliente."_".GRUPO_ADMINS."' OR user_group = '---ALL---')";
                $and = "AND user_group = '" . $cliente . "'";
            }
            $query = "SELECT campaign_id, campaign_name FROM vicidial_campaigns  WHERE active = 'Y' $and AND campaign_id IN (SELECT campaign_id  FROM dialvox_agentes_campanas WHERE user='$user' )";
            $result = sv_mysqli_query($con, $query);
            $i = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $salida["Campanas"][$i]["id"] = $row["campaign_id"];
                $salida["Campanas"][$i]["nombre"] = $row["campaign_name"];
                $i++;
            }
            $query = "SELECT dialplan_number FROM phones WHERE BINARY extension = '$user' AND BINARY pass = '$pass'";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $salida["Nueva"] = true;
            } else {
                $salida["Nueva"] = false;
            }
        } else {
            $salida["Estado"] = "Error";
        }
        sv_mysqli_close($con);
        header('Content-type: application/json');
        //ob_clean();
        //print(json_encode($salida));
        $this->output->set_output(json_encode($salida));
    }
    public function index()
    {
        $this->load->view('login/head');
        $this->load->view('login/vw_login');
        $this->load->view('login/foot');
    }
    public function entra()
    {
        include_once RUTA_APP . 'Conexion.php';
        $con = getConnection();
        $user = limpia($_POST['user']);
        $pass = limpia($_POST['pass']);
        if (isset($_POST["campana"])) {
            $campana = limpia($_POST["campana"]);
        } else {
            $campana = -1;
        }

        $query = "SELECT * FROM vicidial_users  WHERE BINARY user = '$user' AND BINARY pass = '$pass' AND active = 'Y' LIMIT 1";
        $result = sv_mysqli_query($con, $query);
        $salida = array();
        if ($row = sv_mysqli_fetch_array($result)) {
            $sePuede = true;
            $error = 0;
            if (strpos($row["user_group"], GRUPO_AGENTES) !== false) {
                $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."_".GRUPO_ADMINS."' OR user_group = '---ALL---')";
                    $extra = "AND user_group = '" . $cliente . "'";
                }
                $query = "SELECT campaign_id,campaign_recording,dial_method,campaign_allow_inbound 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 {
                    $row3 = sv_mysqli_fetch_array($result);
                    $_SESSION["dial_method"] = $row3["dial_method"];
                    $_SESSION["INBOUND"] = $row3["campaign_allow_inbound"] == "Y";
                    $_SESSION["campaign_recording"] = $row3["campaign_recording"];
                    if ($row3["dial_method"] != 'INBOUND_MAN' && !$_SESSION["INBOUND"]) {
                        $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;
                        }
                    }
                    $query2 = "SELECT 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);
                    $_SESSION["windows_check"] = $row4["windows_check"];
                    $_SESSION["max_time_dispo"] = $row4["max_time_dispo"];
                    $_SESSION["time_beep"] = $row4["time_beep"];
                    $_SESSION["allow_beep"] = $row4["allow_beep"];
                    $_SESSION["time_repeat"] = $row4["time_repeat"];

                    if (NEED_WA) {
                        $_SESSION["allow_wa"] = $row4["allow_wa"];
                        $_SESSION["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);
                        $_SESSION["wa_user"] = $row4["wa_user"];
                        $_SESSION["wa_pass"] = $row4["wa_pass"];
                        $_SESSION["WA_USER"] = $row4["allow_wa"];
                    }

                    $query2 = "SELECT extension FROM phones WHERE login IN (SELECT logins_list FROM phones_alias WHERE BINARY alias_name='" . limpia($_POST["extension"]) . "') AND active = 'Y' AND BINARY pass='" . limpia($_POST["pass_ext"]) . "' LIMIT 1";
                    $result2 = sv_mysqli_query($con, $query2);
                    $row4 = sv_mysqli_fetch_array($result2);
                    $_POST["extension"] = $salida["extSali"] = $row4["extension"];

                    $queryAutopausa = "SELECT Tono,CodigoPausa,Volumen,MetodoDistribucion,TiempoTimbrado FROM dialvox_campana_autopausa WHERE Campana='$campana'";
                    $resultAutopausa = sv_mysqli_query($con, $queryAutopausa);
                    if ($resultAutopausa) {
                        $rowAutopausa = sv_mysqli_fetch_array($resultAutopausa);
                        if ($rowAutopausa) {
                            $_SESSION["autopausa_Activa"] = true;
                            $_SESSION["autopausa_Codigo"] = $rowAutopausa["CodigoPausa"];
                            $_SESSION["autopausa_Tono"] = $rowAutopausa["Tono"];
                            $_SESSION["autopausa_Volumen"] = $rowAutopausa["Volumen"];
                            $_SESSION["autopausa_MetodoDistribucion"] = $rowAutopausa["MetodoDistribucion"];
                            $_SESSION["autopausa_TiempoTimbrado"] = $rowAutopausa["TiempoTimbrado"];
                        }
                    }
                }
            }
            if ($sePuede) {
                $salida["Estado"] = "Ok";
                //$salida["Permisos"] = $row;
                $salida["Grupo"] = $row["user_group"];
                $_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"]);
                }
                if ($resultLogo = sv_mysqli_query($con, "SELECT COUNT(*) AS CUENTA FROM dialvox_logos_clientes WHERE idCliente = '" . $_SESSION["Cliente"] . "'")) {
                    if ($rowLogo = sv_mysqli_fetch_array($resultLogo)) {
                        $cuentaLogo = $rowLogo["CUENTA"];
                        if ($cuentaLogo > 0) {
                            $_SESSION["Logo"] = "SI";
                        }
                    }
                }
                $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);
                    if ($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 allowEncuestas,allowTTS,allowFiles,allow_chat,userTelevox,passTelevox,allowTelevox,allowGlobalList,allowACD,allowInboundsReports FROM vicidial_clients_limit WHERE idClient='{$_SESSION["Cliente"]}'";
                    $result2 = sv_mysqli_query($con, $query2);
                    if ($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"];
                        $_SESSION["allowEncuestas"] = $row4["allowEncuestas"];
                        $_SESSION["allowTTS"] = $row4["allowTTS"];
                        $_SESSION["allowFiles"] = $row4["allowFiles"];

                        // Obteniendo encuesta por defecto
                        if ($tipo == GRUPO_AGENTES) {
                            $queryEncuestaDefault = "SELECT id_encuesta FROM dialvox_campaign_encuesta WHERE campaign_id='$campana' AND is_default=TRUE";
                            $resultEncuestaDefault = sv_mysqli_query($con, $queryEncuestaDefault);
                            if (sv_mysqli_num_rows($resultEncuestaDefault) > 0) {
                                $rowEncuestaDefault = sv_mysqli_fetch_array($resultEncuestaDefault);
                                $_SESSION["agente_IdEncuestaDefault"] = $rowEncuestaDefault["id_encuesta"];
                            }
                        }
                        // Obteniendo encuesta por defecto

                    }

                    if ($tipo != GRUPO_AGENTES) {
                        $_SESSION["ConfigOmnicanalidad"] = OmnicanalidadConfig::getAllByCliente($_SESSION["Cliente"], true, true);
                        $_SESSION["ConfigExtras"] = ExtrasConfig::getAllByCliente($_SESSION["Cliente"], true, true);
                    }
                } else {

                    $_SESSION["userTelevox"] = "admin";
                    $_SESSION["passTelevox"] = "admin";
                }
                session_write_close();
            } else {
                $salida["Estado"] = "Error";
                $salida["Tipo"] = $error;
            }
            //$this->input->set_cookie($arr);
        } else {
            $salida["Tipo"] = 1;
            $salida["Estado"] = "Error";
        }
        sv_mysqli_close($con);
        $this->output->set_output(json_encode($salida));
    }
}
