<?php

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

class Clientes 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 getDialReport()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false && $_SESSION["Cliente"] == -1)) {
            //header('Content-type: application/json');
            header('Content-Type: application/csv');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            // $campana = limpia($_GET["campana"]);
            $limiteFechas = "";
            $cliente = $_GET["cliente"];
            $donde = "";
            $archived = false;
            if (isset($_GET["archived"]) && $_GET["archived"] == 1) {
                $archived = true;
            }
            if (isset($_GET["fechaIni"])) {
                $fechaIni = limpia($_GET["fechaIni"]);
                $limiteFechas .= "AND DATE(call_date) >= DATE('$fechaIni')";
            }

            if (isset($_GET["fechaFin"])) {
                $fechaFin = limpia($_GET["fechaFin"]);
                $limiteFechas .= "AND DATE(call_date) <= DATE('$fechaFin')";
            } else if (isset($_GET["fechaIni"])) {
                $fechaIni = limpia($_GET["fechaIni"]);
                $limiteFechas .= "AND DATE(call_date) <= DATE('$fechaIni')";
            }

            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $queryCliente = "SELECT user_group FROM vicidial_users WHERE user_group LIKE '" . $cliente . "\_" . GRUPO_ADMINS . "' GROUP BY user_group ORDER BY user_group LIMIT 1";
            $resultCliente = sv_mysqli_query($con, $queryCliente);
            if ($rowCliente = sv_mysqli_fetch_array($resultCliente)) {
                $nombreCliente = $rowCliente["user_group"];
                header("Content-Disposition: attachment; filename=\"Registro de llamadas para el cliente: $nombreCliente.csv\"");
                $queryIFT = "SELECT tipo FROM dialvox_ift WHERE nirserie=LEFT(vicidial_log.phone_number,6) LIMIT 1";
                $queryIFTArchive = "SELECT tipo FROM dialvox_ift WHERE nirserie=LEFT(vicidial_log_archive.phone_number,6) LIMIT 1";
                $duracionQuery = "SEC_TO_TIME((GREATEST(IF((end_epoch-start_epoch) IS NULL,0,(end_epoch-start_epoch)),(SELECT IF(MAX((end_epoch-start_epoch)) IS NULL,0,MAX((end_epoch-start_epoch))) FROM recording_log WHERE vicidial_id=vicidial_log.uniqueid))))";
                $duracionQueryArchive = "SEC_TO_TIME((GREATEST(IF((end_epoch-start_epoch) IS NULL,0,(end_epoch-start_epoch)),(SELECT IF(MAX((end_epoch-start_epoch)) IS NULL,0,MAX((end_epoch-start_epoch))) FROM recording_log WHERE vicidial_id=vicidial_log_archive.uniqueid))))";
                $query = "SELECT lead_id,(SELECT vendor_lead_code FROM vicidial_list WHERE lead_id = vicidial_log.lead_id) AS vendor_lead_code,(SELECT list_name FROM vicidial_lists WHERE list_id = vicidial_log.list_id) AS list_id,call_date,status,phone_number,user,alt_dial,SEC_TO_TIME((GREATEST(IF((end_epoch-start_epoch) IS NULL,0,(end_epoch-start_epoch)),(SELECT IF(MAX((end_epoch-start_epoch)) IS NULL,0,MAX((end_epoch-start_epoch))) FROM recording_log WHERE vicidial_id=vicidial_log.uniqueid)))) AS duracion,  (ADDTIME(TIME_FORMAT(" . $duracionQuery . ",'%H:%i:00'), IF(SECOND(" . $duracionQuery . ")>0,'00:01:00','00:00:00'))) as tiempo_telefonia, (" . $queryIFT . ") AS tipo_telefono,term_reason FROM vicidial_log WHERE campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '$cliente')  $limiteFechas";
                if ($archived) {
                    $query .= " UNION SELECT lead_id,(SELECT vendor_lead_code FROM vicidial_list WHERE lead_id = vicidial_log_archive.lead_id) AS vendor_lead_code,(SELECT list_name FROM vicidial_lists WHERE list_id = vicidial_log_archive.list_id) AS list_id,call_date,status,phone_number,user,alt_dial,SEC_TO_TIME((GREATEST(IF((end_epoch-start_epoch) IS NULL,0,(end_epoch-start_epoch)),(SELECT IF(MAX((end_epoch-start_epoch)) IS NULL,0,MAX((end_epoch-start_epoch))) FROM recording_log WHERE vicidial_id=vicidial_log_archive.uniqueid)))) AS duracion,(ADDTIME(TIME_FORMAT(" . $duracionQueryArchive . ",'%H:%i:00'), IF (SECOND(" . $duracionQueryArchive . ")>0,'00:01:00','00:00:00'))) as tiempo_telefonia, (" . $queryIFTArchive . ") AS tipo_telefono,term_reason FROM vicidial_log_archive WHERE campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '$cliente') $limiteFechas ";
                }
                $query .= " ORDER BY call_date";
                //echo($query);
                $result = sv_mysqli_query($con, $query);
                $out = "";
                $sal["Registros"] = array();
                $stmtNombres = "SELECT '" . $this->lang->line("dialReport_causaColgado") . "' AS label_term_reason,'" . $this->lang->line("dialReport_llave") . "' AS label_vendor_lead_code, '" . $this->lang->line("dialReport_ordenNumero") . "' AS label_alt_dial,'" . $this->lang->line("dialReport_idRegistro") . "' AS label_lead_id, '" . $this->lang->line("dialReport_fechaRegistro") . "' AS label_entry_date, '" . $this->lang->line("dialReport_fechaModificacion") . "' AS label_modify_date, '" . $this->lang->line("dialReport_estadoRegistro") . "' AS label_status, '" . $this->lang->line("dialReport_usuario") . "' AS label_user, '" . $this->lang->line("dialReport_nombreList") . "' AS label_list_id, '" . $this->lang->line("dialReport_llamadoReinicio") . "' AS label_called_since_last_reset, '" . $this->lang->line("dialReport_zonaHoraria") . "' AS label_gmt_offset_now, '" . $this->lang->line("dialReport_codigoTelefonico") . "' AS label_phone_code, '" . $this->lang->line("dialReport_fechaNacimiento") . "' AS label_date_of_birth,'" . $this->lang->line("dialReport_vecesLlamado") . "' AS label_called_count, '" . $this->lang->line("dialReport_fechaUltimoLlamado") . "' AS label_last_local_call_time,'" . $this->lang->line("dialReport_pais") . "' AS label_country_code,'" . $this->lang->line("dialReport_rango") . "' AS label_rank, '" . $this->lang->line("dialReport_autor") . "' AS label_owner,'" . $this->lang->line("dialReport_titulo") . "' AS label_title,'" . $this->lang->line("dialReport_nombre") . "' AS label_first_name,'" . $this->lang->line("dialReport_segundoNombre") . "' AS label_middle_initial,'" . $this->lang->line("dialReport_apellidos") . "' AS label_last_name,'" . $this->lang->line("dialReport_direccion") . "' AS label_address1,'" . $this->lang->line("dialReport_direccion2") . "' AS label_address2,'" . $this->lang->line("dialReport_telefonoAlt2") . "' AS label_address3,'" . $this->lang->line("dialReport_ciudad") . "' AS label_city,'" . $this->lang->line("dialReport_estado") . "' AS label_state,'" . $this->lang->line("dialReport_provincia") . "' AS label_province,'" . $this->lang->line("dialReport_codigoPostal") . "' AS label_postal_code,'" . $this->lang->line("dialReport_genero") . "' AS label_gender,'" . $this->lang->line("dialReport_telefono") . "' AS label_phone_number,'" . $this->lang->line("dialReport_telefonoAlt") . "' AS label_alt_phone,label_security_phrase,'" . $this->lang->line("dialReport_email") . "' AS label_email,'" . $this->lang->line("dialReport_comentarios") . "' AS label_comments, '" . $this->lang->line("dialReport_duracion") . "' as label_duracion, '" . $this->lang->line("dialReport_minutosTelefonia") . "' as label_tiempo_telefonia, '" . $this->lang->line("dialReport_tipoTelefono") . "' as label_tipo_telefono from system_settings";
                $resultNombres = sv_mysqli_query($con, $stmtNombres, MYSQLI_ASSOC);
                $rowNombres = sv_mysqli_fetch_array($resultNombres);
                while ($row1 = sv_mysqli_fetch_array($result)) {
                    //$sal["Registros"][] = $row1;
                    $llaves = array_keys($row1);
                    $objeto = array();
                    for ($i = 0; $i < count($llaves); $i++) {
                        $titulo = "label_" . $llaves[$i];
                        if (array_key_exists($titulo, $rowNombres) && $rowNombres[$titulo] != "") {
                            $objeto[$rowNombres[$titulo]] = $row1[$llaves[$i]];
                        } else {
                            $objeto[$llaves[$i]] = $row1[$llaves[$i]];
                        }
                    }
                    $sal["Registros"][] = $objeto;
                }
                foreach ($sal["Registros"] as &$nombre) {
                    if ($nombre[$this->lang->line("dialReport_causaColgado")] == "CALLER") {
                        $nombre[$this->lang->line("dialReport_causaColgado")] = $this->lang->line("dialReport_causaColgado_cliente");
                    }
                    if ($nombre[$this->lang->line("dialReport_causaColgado")] == "AGENT") {
                        $nombre[$this->lang->line("dialReport_causaColgado")] = $this->lang->line("dialReport_causaColgado_agente");
                    }

                    if ($nombre[$this->lang->line("dialReport_usuario")] == "VDAD") {
                        $nombre[$this->lang->line("dialReport_usuario")] = $this->lang->line("dialReport_usuario_sistema");
                    }
                    if ($nombre[$this->lang->line("dialReport_ordenNumero")] == "MAIN") {
                        $nombre[$this->lang->line("dialReport_ordenNumero")] = $this->lang->line("dialReport_ordenNumero_alt");
                    }
                    if ($nombre[$this->lang->line("dialReport_ordenNumero")] == "NONE") {
                        $nombre[$this->lang->line("dialReport_ordenNumero")] = $this->lang->line("dialReport_ordenNumero_principal");
                    }
                    if ($nombre[$this->lang->line("dialReport_ordenNumero")] == "ADDR3") {
                        $nombre[$this->lang->line("dialReport_ordenNumero")] = $this->lang->line("dialReport_ordenNumero_alt2");
                    }
                }
                ob_start();
                $out = fopen('php://output', 'w');
                $test = array();
                $this->trata($out, $sal["Registros"], $test);
                fclose($out);
                $str = ob_get_contents();
                ob_end_clean();
                $this->output->set_output($str);
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desC_permisosLlamadasCliente");
            }
        }
    }
    public function getClients()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES) && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $registros = 10;
            $pagina = $_POST["pagina"] - 1;
            $skip = $registros * $pagina;
            $query = "SELECT user_group FROM vicidial_users WHERE user_group LIKE '%\_" . GRUPO_ADMINS . "' GROUP BY user_group ORDER BY user_group LIMIT $skip,$registros";
            $result = sv_mysqli_query($con, $query);
            $sal["Registros"] = array();
            $donde = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $a = strpos($row["user_group"], "_");
                $cliente = "";
                for ($i = $a - 1; $i >= 0; $i--) {
                    $cliente .= $row["user_group"][$i];
                }
                $cliente = strrev($cliente);
                $sal["Registros"][$donde]["nombre"] = $cliente;
                $test = 'Y';
                $result1 = sv_mysqli_query($con, "SELECT active FROM vicidial_users WHERE user = '$cliente' AND user_group = '" . $cliente . "_" . GRUPO_ADMINS . "' LIMIT 1");
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $test = $row1["active"];
                }
                $sal["Registros"][$donde]["activo"] = $test;
                $result1 = sv_mysqli_query($con, "SELECT COUNT(campaign_id) FROM vicidial_campaigns WHERE user_group = '$cliente'");
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $sal["Registros"][$donde]["campanas"] = $row1[0];
                }
                $result1 = sv_mysqli_query($con, "SELECT COUNT(list_id) FROM vicidial_lists WHERE campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '$cliente')");
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $sal["Registros"][$donde]["listas"] = $row1[0];
                }
                $result1 = sv_mysqli_query($con, "SELECT COUNT(user) FROM vicidial_users WHERE user_group LIKE '" . $cliente . "\_%'");
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $sal["Registros"][$donde]["usuarios"] = $row1[0];
                }
                $result1 = sv_mysqli_query($con, "SELECT COUNT(user) FROM vicidial_users WHERE user_group = '" . $cliente . "_" . GRUPO_ADMINS . "'");
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $sal["Registros"][$donde]["admins"] = $row1[0];
                }
                $result1 = sv_mysqli_query($con, "SELECT COUNT(user) FROM vicidial_users WHERE user_group = '" . $cliente . "_" . GRUPO_SUPERVISORES . "'");
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $sal["Registros"][$donde]["supervisor"] = $row1[0];
                }
                $result1 = sv_mysqli_query($con, "SELECT COUNT(user) FROM vicidial_users WHERE user_group = '" . $cliente . "_" . GRUPO_AGENTES . "'");
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $sal["Registros"][$donde]["agentes"] = $row1[0];
                }

                $donde++;
            }
            $result = sv_mysqli_query($con, "SELECT count(*) FROM (SELECT COUNT(user_group) FROM vicidial_users WHERE user_group LIKE '%\_" . GRUPO_ADMINS . "' GROUP BY user_group) AS X");
            $row = sv_mysqli_fetch_array($result);
            $sal["Cuenta"] = $row[0];
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function assocVozCliente()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';

            $cliente = limpia($_POST["cliente"]);
            $id_voz = limpia($_POST["id_voz"]);
            $con = getConnection();
            $sal = array();
            $query = "INSERT INTO dialvox_voces_cliente(id_voz,cliente) VALUES('$id_voz','$cliente')";
            sv_mysqli_query($con, $query);
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function disassocVozCliente()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';

            $cliente = limpia($_POST["cliente"]);
            $id_voz = limpia($_POST["id_voz"]);
            $con = getConnection();
            $sal = array();
            $query = "DELETE FROM dialvox_voces_cliente WHERE id_voz='$id_voz' AND cliente ='$cliente'";
            sv_mysqli_query($con, $query);
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getVocesByClient()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';

            $cliente = limpia($_POST["cliente"]);
            $con = getConnection();
            $sal = array();
            $query = "SELECT id_voz,(SELECT nombre FROM dialvox_voces WHERE id_voz=T.id_voz) as nombre FROM dialvox_voces_cliente T WHERE cliente='$cliente'";
            $result = sv_mysqli_query($con, $query);
            $sal["Registros"] = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Registros"][] = $row;
            }
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getClientsSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES) && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $query = "SELECT user_group FROM vicidial_users WHERE user_group LIKE '%\_" . GRUPO_ADMINS . "' GROUP BY user_group ORDER BY user_group";
            $result = sv_mysqli_query($con, $query);
            $sal["Registros"] = array();
            $donde = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $a = strpos($row["user_group"], "_");
                $cliente = "";
                for ($i = $a - 1; $i >= 0; $i--) {
                    $cliente .= $row["user_group"][$i];
                }
                $cliente = strrev($cliente);
                $sal["Registros"][$donde]["nombre"] = $cliente;
                $donde++;
            }
            $row = sv_mysqli_fetch_array($result);
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function addClient()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $password = limpia($_POST["password"]);
            $nombre = limpia($_POST["nombre"]);
            $numero = limpia($_POST["limite"]);
            $allowTelevox = limpia($_POST["allowTelevox"]);
            $allowGlobalList = limpia($_POST["allowGlobalList"]);
            $allowACD = limpia($_POST["allowACD"]);
            $allow_chat = limpia($_POST["allow_chat"]);
            $allowTTS = limpia($_POST["allowTTS"]);
            $allowFiles = limpia($_POST["allowFiles"]);
            $allowEncuestas = limpia($_POST["allowEncuestas"]);

            $allowInboundsReports = limpia($_POST["allowInboundsReports"]);
            $sal["Estado"] = "ok";
            $query = "SELECT user_group FROM vicidial_users WHERE user_group = '" . $nombre . "_" . GRUPO_ADMINS . "' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_clienteExistente");
            } else {
                if (strlen($nombre) < 2) {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_nombreCorto");
                } else {
                    if (NEED_WA) {
                        $allow_wa = limpia($_POST["allow_wa"]);
                        if ($allow_wa == 1) {
                            $usuarioWA = $_POST["UsuarioWA"];
                            $passwordWA = $_POST["passwordWA"];
                            $objectId = $_POST["ObjectIdWA"];
                            $query = "INSERT INTO vicidial_clients_limit(idClient,limit_number,allow_wa,user_wa,pass_wa,idclient_wa,userTelevox,passTelevox,allowTelevox,allowGlobalList,allowACD,allowInboundsReports,allow_chat,allowTTS,allowFiles,allowEncuestas) VALUES('$nombre','$numero','1','$usuarioWA','$passwordWA','$objectId','$nombre','$password','$allowTelevox','$allowGlobalList','$allowACD','$allowInboundsReports','$allow_chat','$allowTTS','$allowFiles','$allowEncuestas')";
                            sv_mysqli_query($con, $query);
                        } else {
                            sv_mysqli_query($con, "INSERT INTO vicidial_clients_limit(idClient,limit_number,allow_wa,userTelevox,passTelevox,allowTelevox,allowGlobalList,allowACD,allowInboundsReports,allow_chat,allowTTS,allowFiles,allowEncuestas) VALUES('$nombre','$numero','0','$nombre','$password','$allowTelevox','$allowGlobalList','$allowACD','$allowInboundsReports','$allow_chat','$allowTTS','$allowFiles','$allowEncuestas')");
                        }
                    } else {
                        sv_mysqli_query($con, "INSERT INTO vicidial_clients_limit(idClient,limit_number,allow_wa,userTelevox,passTelevox,allowTelevox,allowGlobalList,allowACD,allowInboundsReports,allow_chat,allowTTS,allowFiles,allowEncuestas) VALUES('$nombre','$numero','0','$nombre','$password','$allowTelevox','$allowGlobalList','$allowACD','$allowInboundsReports','$allow_chat','$allowTTS','$allowFiles','$allowEncuestas')");
                    }
                    if ($sal["Estado"] != "error") {
                        $idTel = 0;
                        $result = sv_mysqli_query($con, "SELECT MAX(id)+1 AS MAX FROM navegador.tbl_usuario");
                        if ($row = sv_mysqli_fetch_array($result)) {
                            $idTel = $row["MAX"] ?? 1;
                        }
                        sv_mysqli_query($con, "INSERT INTO navegador.tbl_usuario(id, usuario, password,reproducir,grafica,descargar,eliminar,log,modificar,configurar,comentar,status,reportes,idClientes) values('$idTel','" . base64_encode(base64_encode($nombre)) . "','" . base64_encode(base64_encode($password)) . "','1','1','1','1','1','0','0','1','1','1','$nombre')");
                        sv_mysqli_query($con, "INSERT INTO vicidial_user_groups(user_group,group_name,allowed_campaigns,admin_viewable_groups) values('" . $nombre . "','General $nombre','-ALL-CAMPAIGNS-','---ALL---')");
                        sv_mysqli_query($con, "INSERT INTO vicidial_user_groups(user_group,group_name,allowed_campaigns,admin_viewable_groups) values('" . $nombre . "_" . GRUPO_ADMINS . "','Administradores $nombre','-ALL-CAMPAIGNS-','---ALL---')");
                        sv_mysqli_query($con, "INSERT INTO vicidial_user_groups(user_group,group_name,allowed_campaigns,admin_viewable_groups) values('" . $nombre . "_" . GRUPO_AGENTES . "','Agentes $nombre','-ALL-CAMPAIGNS-','---ALL---')");
                        sv_mysqli_query($con, "INSERT INTO vicidial_user_groups(user_group,group_name,allowed_campaigns,admin_viewable_groups) values('" . $nombre . "_" . GRUPO_SUPERVISORES . "','Supervisores $nombre','-ALL-CAMPAIGNS-','---ALL---')");

                        $nivel = 9;
                        $grupo = $nombre . "_" . GRUPO_ADMINS;
                        $url = URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&function=add_user&agent_user=" . $nombre . "&agent_pass=" . urlencode($password) . "&agent_user_level=" . $nivel . "&agent_full_name=" . urlencode("Admin " . $nombre) . "&agent_user_group=" . $grupo;
                        $text = file_get_contents($url);
                        $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 = $nombre;
                        $pass = $password;
                        $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);
                        $stmt = "UPDATE vicidial_users SET phone_login='$extension',phone_pass='$pass' WHERE user='$nombre'";
                        $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);
                        $sal["Estado"] = "ok";
                        $sal["Usuario"] = $nombre;
                        $sal["text"] = $text;
                        $sal["Password"] = $password;
                    }
                }
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }

    }
    public function getClientDetail()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $nombre = limpia($_POST["nombre"]);
            $query = "SELECT user_group FROM vicidial_users WHERE user_group = '" . $nombre . "_" . GRUPO_ADMINS . "' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT * FROM vicidial_clients_limit WHERE idClient='$nombre' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                $row2 = sv_mysqli_fetch_array($result);
                $sal["Cliente"] = $row2;
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_clienteNoEncontrado");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function editClient()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $nombre = limpia($_POST["nombre"]);
            $limite = limpia($_POST["limite"]);
            $allowTelevox = limpia($_POST["allowTelevox"]);
            $allowGlobalList = limpia($_POST["allowGlobalList"]);
            $allowACD = limpia($_POST["allowACD"]);
            $allow_chat = limpia($_POST["allow_chat"]);
            $allowInboundsReports = limpia($_POST["allowInboundsReports"]);
            $allowTTS = limpia($_POST["allowTTS"]);
            $allowFiles = limpia($_POST["allowFiles"]);
            $allowEncuestas = limpia($_POST["allowEncuestas"]);

            $query = "SELECT user_group FROM vicidial_users WHERE user_group = '" . $nombre . "_" . GRUPO_ADMINS . "' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $allow_wa = limpia(isset($_POST["allow_wa"]) ? $_POST["allow_wa"] : 0);
                $query = "UPDATE vicidial_clients_limit SET allowEncuestas='$allowEncuestas',allowFiles='$allowFiles',allowTTS='$allowTTS',allowTelevox='$allowTelevox',allowGlobalList='$allowGlobalList',allowACD='$allowACD',allowInboundsReports='$allowInboundsReports', allow_wa='$allow_wa',limit_number='$limite',allow_chat='$allow_chat' WHERE idClient='$nombre'";
                sv_mysqli_query($con, $query);
                if (NEED_WA) {
                    if ($allow_wa == 1) {
                        $usuarioWA = $_POST["UsuarioWA"];
                        $passwordWA = $_POST["passwordWA"];
                        $objectId = $_POST["ObjectIdWA"];
                        $query = "UPDATE vicidial_clients_limit SET user_wa='$usuarioWA', pass_wa='$passwordWA', idclient_wa='$objectId' WHERE idClient='$nombre'";
                        sv_mysqli_query($con, $query);
                    }
                }
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_clienteNoEncontrado");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function changeClientStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('clientes', "spanish");
                break;
            case "en":
                $this->lang->load('clientes', "english");
                break;
            default:
                $this->lang->load('clientes', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS && $_SESSION["Cliente"] == -1) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $nombre = limpia($_POST["nombre"]);
            $query = "SELECT user_group FROM vicidial_users WHERE user_group = '" . $nombre . "_" . GRUPO_ADMINS . "' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                if (strlen($nombre) < 2) {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_nombreCorto");
                } else {
                    $query = "SELECT active,user FROM vicidial_users WHERE user = '$nombre' AND user_group = '" . $nombre . "_" . GRUPO_ADMINS . "' LIMIT 1";
                    $result = sv_mysqli_query($con, $query);
                    $row = sv_mysqli_fetch_array($result);
                    if ($row["active"] == 'Y') {
                        sv_mysqli_query($con, "UPDATE vicidial_users SET active = 'N' WHERE user_group IN ('" . $nombre . "_" . GRUPO_ADMINS . "','" . $nombre . "_" . GRUPO_AGENTES . "','" . $nombre . "_" . GRUPO_SUPERVISORES . "')");
                        sv_mysqli_query($con, "UPDATE vicidial_campaigns SET active = 'N' WHERE user_group = '$nombre'");
                    } else {
                        sv_mysqli_query($con, "UPDATE vicidial_users SET active = 'Y' WHERE user = '" . $row["user"] . "' LIMIT 1");
                    }
                    $sal["Estado"] = "ok";
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_clienteNoEncontrado");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }

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

        header('Content-type: application/json');
        $sal = array(
            "Estado" => "ok",
        );
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            include_once RUTA_APP . 'Sesiones.php';

            $r = array();
            if (isset($_POST["omnicanalidad"])) {
                $r = OmnicanalidadConfig::insert(
                    $_POST["cliente"],
                    $_POST["label"],
                    $_POST["url"],
                    $_POST["userField"],
                    $_POST["passwordField"],
                    $_POST["userValue"],
                    $_POST["passwordValue"],
                    $_POST["loginURL"],
                    $_POST["redirectURL"],
                    $_POST["icon"]
                );
            } else {
                $r = ExtrasConfig::insert(
                    $_POST["cliente"],
                    $_POST["label"],
                    $_POST["url"],
                    $_POST["script"],
                    $_POST["icon"]
                );
            }

            if ($r != null) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $r["ERROR"];
            }

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

    }

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

        header('Content-type: application/json');
        $sal = array(
            "Estado" => "ok",
        );
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            include_once RUTA_APP . 'Sesiones.php';

            $r = array();
            if (isset($_POST["omnicanalidad"])) {
                $r = OmnicanalidadConfig::update(
                    $_POST["id"],
                    $_POST["label"],
                    $_POST["url"],
                    $_POST["userField"],
                    $_POST["passwordField"],
                    $_POST["userValue"],
                    $_POST["passwordValue"],
                    $_POST["loginURL"],
                    $_POST["redirectURL"],
                    $_POST["icon"]
                );
            } else {
                $r = ExtrasConfig::update(
                    $_POST["id"],
                    $_POST["label"],
                    $_POST["url"],
                    $_POST["script"],
                    $_POST["icon"]
                );
            }

            if ($r != null) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $r["ERROR"];
            }

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

    }

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

        header('Content-type: application/json');
        $sal = array(
            "Estado" => "ok",
        );
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            include_once RUTA_APP . 'Sesiones.php';

            $r = array();
            if (isset($_POST["omnicanalidad"])) {
                $r = OmnicanalidadConfig::delete($_POST["id"]);
            } else {
                $r = ExtrasConfig::delete($_POST["id"]);
            }

            if ($r != null) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $r["ERROR"];
            }

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

    }

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

        header('Content-type: application/json');
        $sal = array(
            "Estado" => "ok",
            "Section" => null,
        );
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            include_once RUTA_APP . 'Sesiones.php';

            $r = array();
            if (isset($_POST["omnicanalidad"])) {
                $r = OmnicanalidadConfig::getById($_POST["id"]);
            } else {
                $r = ExtrasConfig::getById($_POST["id"]);
            }

            if ($r != null) {
                $sal["Section"] = $r->toJSON();
            }
        } else {
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
        }
        $this->output->set_output(json_encode($sal));
    }

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

        header('Content-type: application/json');
        $sal = array(
            "Estado" => "ok",
            "Sections" => array(),
        );
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Cliente"] == -1) {
            include_once RUTA_APP . 'Sesiones.php';

            $r = array();
            if (isset($_POST["omnicanalidad"])) {
                $r = OmnicanalidadConfig::getAllByCliente($_POST["cliente"], true);
            } else {
                $r = ExtrasConfig::getAllByCliente($_POST["cliente"], true);
            }

            if ($r != null) {
                $sal["Sections"] = $r;
            }
        } else {
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
        }
        $this->output->set_output(json_encode($sal));
    }

    public function index()
    {
        $this->load->view('clientes/head');
        $this->load->view('clientes/vw_clientes');
        $this->load->view('clientes/foot');
    }
}
