<?php
/*
<-------ESTE ES EL SCRIPT PARA EL PLAN DE MARCACION------->
exten => _666.,1,ANSWER()
exten => _666.,n,Set(AUDIOBLASTER=${CURL(http://localhost/Dialvox/index.php/Campanas/getAudio?id=${EXTEN:3})})
exten => _666.,n,PLAYBACK(${AUDIOBLASTER})
exten => _666.,n,HANGUP()
<--------------------------------------------------------->
<-------ESTA ES LA ESTRUCTURA DE LA TABLA dialvox_ift----->
CREATE TABLE `dialvox_ift` (
`id` int(11) NOT NULL,
`nirserie` int(11) DEFAULT NULL,
`numi` varchar(10) DEFAULT NULL,
`numf` varchar(10) DEFAULT NULL,
`tipo` varchar(30) DEFAULT NULL,
`carrier` varchar(200) DEFAULT NULL,
`estado` varchar(200) DEFAULT NULL,
`municipio` varchar(200) DEFAULT NULL,
`poblacion` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `nirserie_numi_numf` (`nirserie`,`numi`,`numf`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
<--------------------------------------------------------->
CREATE TABLE

 */
require_once "BASEPATH.php";
require_once 'Clases/ClienteDatos.php';
require_once 'Clases/AudioDatos.php';
require_once 'Clases/RemoteAgentDatos.php';
require_once 'Clases/FrameAgenteDatos.php';
class Campanas extends MY_Controller
{
    public function addCampaignToUser()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $user = limpia($_POST["user"]);
            $campana = limpia($_POST["campana"]);
            $cliente = $_SESSION["Cliente"];
            $donde = "";
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                if ($cliente != -1) {
                    $donde = "AND user_group = '" . $cliente . "_AGENTES'";
                }
                $query = "SELECT user FROM vicidial_users WHERE user = '$user' $donde LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $query = "INSERT IGNORE INTO dialvox_agentes_campanas(user,campaign_id) VALUES ('$user','$campana') ";
                    sv_mysqli_query($con, $query);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = "El usuario no existe";
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = "La campaña no existe";
            }
        } else {
            $sal["Estado"] = "error";
            $sal["Descripcion"] = "No tiene los permisos para ver los estatus de esta campaña";
        }
        $this->output->set_output(json_encode($sal));
    }
    public function deleteCampaignToUser()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $user = limpia($_POST["user"]);
            $campana = limpia($_POST["campana"]);
            $cliente = $_SESSION["Cliente"];
            $donde = "";
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                if ($cliente != -1) {
                    $donde = "AND user_group = '" . $cliente . "_AGENTES'";
                }
                $query = "SELECT user FROM vicidial_users WHERE user = '$user' $donde LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $query = "DELETE FROM  dialvox_agentes_campanas WHERE user='$user' AND campaign_id='$campana' ";
                    sv_mysqli_query($con, $query);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = "El usuario no existe";
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = "La campaña no existe";
            }
        } else {
            $sal["Estado"] = "error";
            $sal["Descripcion"] = "No tiene los permisos para ver los estatus de esta campaña";
        }
        $this->output->set_output(json_encode($sal));
    }
    public function listCampaignToUserByUser()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $user = limpia($_POST["user"]);
            $cliente = $_SESSION["Cliente"];
            $donde = "";
            if ($cliente != -1) {
                $donde = "AND user_group = '" . $cliente . "_AGENTES'";
            }
            $query = "SELECT user FROM vicidial_users WHERE user = '$user' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $sal["Registros"] = array();
                $query = "SELECT campaign_id FROM dialvox_agentes_campanas WHERE user='$user'  ";
                $result = sv_mysqli_query($con, $query);
                while ($row = sv_mysqli_fetch_array($result)) {
                    $sal["Registros"][] = $row["campaign_id"];
                }
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = "El usuario no existe";
            }
        } else {
            $sal["Estado"] = "error";
            $sal["Descripcion"] = "No tiene los permisos para ver los estatus de esta campaña";
        }
        $this->output->set_output(json_encode($sal));
    }
    public function listCampaignToUserByCampaign()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $campana = limpia($_POST["campana"]);
            $cliente = $_SESSION["Cliente"];
            $donde = "";
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT user FROM dialvox_agentes_campanas WHERE campaign_id='$campana'  ";
                $result = sv_mysqli_query($con, $query);
                while ($row = sv_mysqli_fetch_array($result)) {
                    $sal["Registros"][] = $row["user"];
                }
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = "La campaña no existe";
            }
        } else {
            $sal["Estado"] = "error";
            $sal["Descripcion"] = "No tiene los permisos para ver los estatus de esta campaña";
        }
        $this->output->set_output(json_encode($sal));
    }
    public function getAudio()
    {
        include_once RUTA_APP . 'Conexion.php';
        $con = getConnection();
        $resp = "conf-onlyperson";
        $query = "SELECT am_message_exten FROM vicidial_campaigns WHERE campaign_id = '" . $_GET["id"] . "' LIMIT 1";
        //echo($query);
        if ($result = sv_mysqli_query($con, $query)) {
            if ($row = sv_mysqli_fetch_array($result)) {
                $resp = $row["am_message_exten"];
            }
        }
        sv_mysqli_close($con);
        $this->output->set_output($resp);
    }
    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('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) {
            //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 = $_SESSION["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'";
            }
            $query = "SELECT campaign_id,campaign_name FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            $nombreCampana = "";
            if ($row = sv_mysqli_fetch_array($result)) {
                $nombreCampana = $row["campaign_name"];
                header("Content-Disposition: attachment; filename=\"Registro de llamadas en campaña: $nombreCampana.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 = "";
                $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 = '$campana' $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 = '$campana' $limiteFechas ";
                }
                $query .= " ORDER BY call_date";
                //echo($query);
                $result = sv_mysqli_query($con, $query, MYSQLI_ASSOC);
                $out = "";
                $sal["Registros"] = array();
                $stmtNombres = "SELECT '{$this->lang->line('label_term_reason')}' AS label_term_reason, '{$this->lang->line('label_vendor_lead_code')}' AS label_vendor_lead_code, '{$this->lang->line('label_alt_dial')}' AS label_alt_dial,'{$this->lang->line('label_lead_id')}' AS label_lead_id, '{$this->lang->line('label_entry_date')}' AS label_entry_date, '{$this->lang->line('label_modify_date')}' AS label_modify_date, '{$this->lang->line('label_status')}' AS label_status, '{$this->lang->line('label_user')}' AS label_user, '{$this->lang->line('label_list_id')}' AS label_list_id, '{$this->lang->line('label_called_since_last_reset')}' AS label_called_since_last_reset, '{$this->lang->line('label_gmt_offset_now')}' AS label_gmt_offset_now, '{$this->lang->line('label_phone_code')}' AS label_phone_code, '{$this->lang->line('label_date_of_birth')}' AS label_date_of_birth,'{$this->lang->line('label_called_count')}' AS label_called_count, '{$this->lang->line('label_last_local_call_time')}' AS label_last_local_call_time,'{$this->lang->line('label_country_code')}' AS label_country_code,'{$this->lang->line('label_rank')}' AS label_rank, '{$this->lang->line('label_owner')}' AS label_owner,'{$this->lang->line('label_title')}' AS label_title,'{$this->lang->line('label_first_name')}' AS label_first_name,'{$this->lang->line('label_middle_initial')}' AS label_middle_initial,'{$this->lang->line('label_last_name')}' AS label_last_name,'{$this->lang->line('label_address1')}' AS label_address1,'{$this->lang->line('label_address2')}' AS label_address2,'{$this->lang->line('label_address3')}' AS label_address3,'{$this->lang->line('label_city')}' AS label_city,'{$this->lang->line('label_state')}' AS label_state,'{$this->lang->line('label_province')}' AS label_province,'{$this->lang->line('label_postal_code')}' AS label_postal_code,'{$this->lang->line('label_gender')}' AS label_gender,'{$this->lang->line('label_phone_number')}' AS label_phone_number,'{$this->lang->line('label_alt_phone')}' AS label_alt_phone,label_security_phrase,'{$this->lang->line('label_email')}' AS label_email,'{$this->lang->line('label_comments')}' AS label_comments, '{$this->lang->line('label_duracion')}' as label_duracion, '{$this->lang->line('label_tiempo_telefonia')}' as label_tiempo_telefonia, '{$this->lang->line('label_tipo_telefono')}' 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("label_term_reason")] == "CALLER") {
                        $nombre[$this->lang->line("label_term_reason")] = $this->lang->line("label_caller");
                    }
                    if ($nombre[$this->lang->line("label_term_reason")] == "AGENT") {
                        $nombre[$this->lang->line("label_term_reason")] = $this->lang->line("label_agente");
                    }
                    if ($nombre[$this->lang->line("label_user")] == "VDAD") {
                        $nombre[$this->lang->line("label_user")] = $this->lang->line("label_vdad");
                    }
                    if ($nombre[$this->lang->line("label_alt_dial")] == "MAIN") {
                        $nombre[$this->lang->line("label_alt_dial")] = $this->lang->line("label_main");
                    }
                    if ($nombre[$this->lang->line("label_alt_dial")] == "NONE") {
                        $nombre[$this->lang->line("label_alt_dial")] = $this->lang->line("label_none");
                    }
                    if ($nombre[$this->lang->line("label_alt_dial")] == "ADDR3") {
                        $nombre[$this->lang->line("label_alt_dial")] = $this->lang->line("label_addr3");
                    }
                }
                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_permisosLlamadas");
            }
        }
    }

    public function changeAltStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $status = limpia($_POST["status"]);
            $campana = limpia($_POST["campana"]);
            $cliente = $_SESSION["Cliente"];
            $donde = "";
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id,auto_alt_dial_statuses FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $estatus = $row["auto_alt_dial_statuses"];
                if (strpos($estatus, " $status ") === false) {
                    $estatus = substr($estatus, 0, -1);
                    $estatus .= ($status . " -");
                } else {
                    $estatus = str_replace(" $status ", " ", $estatus);
                }
                $query = "UPDATE vicidial_campaigns SET auto_alt_dial_statuses = '$estatus' WHERE campaign_id = '$campana' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEstados");
            }
        }
    }
    public function changeDialStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $status = limpia($_POST["status"]);
            $campana = limpia($_POST["campana"]);
            $cliente = $_SESSION["Cliente"];
            $donde = "";
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id,dial_statuses FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $estatus = $row["dial_statuses"];
                if (strpos($estatus, " $status ") === false) {
                    $estatus = substr($estatus, 0, -1);
                    $estatus .= ($status . " -");
                } else {
                    $estatus = str_replace(" $status ", " ", $estatus);
                }
                $query = "UPDATE vicidial_campaigns SET dial_statuses = '$estatus' WHERE campaign_id = '$campana' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEstados");
            }
        }
    }
    public function getCarriersSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();

            $sal = array();
            $and = "";
            if ($_SESSION["Cliente"] != -1) {
                $and = "WHERE user_group = '" . $_SESSION["Cliente"] . "'";
            }
            $query = "SELECT carrier_id,carrier_name FROM vicidial_server_carriers $and";
            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $objeto = array();
                $objeto["nombre"] = $row["carrier_name"];
                $objeto["id"] = $row["carrier_id"];
                $sal["Registros"][] = $objeto;
            }
            $sal["Estado"] = "ok";
            $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 editStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $cliente = $_SESSION["Cliente"];
            $status = limpia($_POST["status"]);
            $nombre = limpia($_POST["nombre"]);
            $seleccionable = limpia($_POST["seleccionable"]);
            $human = limpia($_POST["human"]);
            $categoria = limpia($_POST["categoria"]);
            $sale = limpia($_POST["sale"]);
            $dnc = limpia($_POST["dnc"]);
            $cc = limpia($_POST["cc"]);
            $completed = limpia($_POST["limpia"]);
            $callback = limpia($_POST["callback"]);
            $unwork = limpia($_POST["unwork"]);
            $ni = limpia($_POST["ni"]);
            $answering_machine = limpia($_POST["answering_machine"]);
            $campana = limpia($_POST["campana"]);
            $blackPhone = limpia($_POST["blackPhone"]);
            $blackLead = limpia($_POST["blackLead"]);
            $query = "SELECT campaign_id FROM vicidial_campaign_statuses WHERE status = '$status' AND campaign_id = '$campana' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $cliente = $_SESSION["Cliente"];
                $donde = "";
                if ($cliente != -1) {
                    $donde = "AND user_group = '" . $cliente . "'";
                }
                $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    if (strlen($nombre) < 2 || strlen($nombre) > 30) {
                        $sal["Estado"] = "error";
                        $sal["Estado"] = "El nombre debe tener entre 2 y 30 caracteres";
                    } else {
                        $cliente = $_SESSION["Cliente"];
                        $mas = "";
                        if ($cliente == -1) {
                            $cliente = "";
                        } else {
                            $mas = "+";
                        }

                        $query = "SELECT vsc_name,vsc_id FROM vicidial_status_categories WHERE vsc_id REGEXP '^" . $cliente . "" . $mas . "[0-9]+$' AND vsc_id = '$categoria' LIMIT 1";
                        $result = sv_mysqli_query($con, $query);
                        if ($row = sv_mysqli_fetch_array($result)) {
                            $query = "UPDATE vicidial_campaign_statuses SET answering_machine = '$answering_machine', status_name = '$nombre',selectable = '$seleccionable',human_answered = '$human',category = '$categoria',sale = '$sale',dnc = '$dnc',customer_contact = '$cc',not_interested = '$ni',unworkable = '$unwork',scheduled_callback = '$callback',completed = '$completed' WHERE status = '$status' AND campaign_id = '$campana' LIMIT 1";
                            $result = sv_mysqli_query($con, $query);
                            $query = "UPDATE dialvox_campaign_statuses SET blackPhone = '$blackPhone', blackLead = '$blackLead' WHERE status = '$status' AND campaign_id = '$campana' LIMIT 1";
                            $result = sv_mysqli_query($con, $query);
                            $sal["Estado"] = "ok";
                        } else {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_categoriaInvalida");
                        }
                    }
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_permisosEditarEstado");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_editarEstado");
            }
            $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 assocBlackList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $cliente = $_SESSION["Cliente"];
            $campana = limpia($_POST["campana"]);
            $lista = limpia($_POST["lista"]);
            $lista = $lista != -1 ? "'$lista'" : "NULL";
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $cliente = $_SESSION["Cliente"];
                $donde = "";
                if ($cliente != -1) {
                    $donde = "AND cliente= '" . $cliente . "'";
                }
                $query = "SELECT idblacklist FROM blacklist WHERE idblacklist = $lista $donde LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($lista == "NULL") {
                    $query = "UPDATE vicidial_tables_windows SET idblacklist=$lista WHERE campaign_id = '$campana' LIMIT 1";
                    $result = sv_mysqli_query($con, $query);
                    $sal["Estado"] = "ok";
                } else {
                    if ($row = sv_mysqli_fetch_array($result)) {
                        $query = "UPDATE vicidial_tables_windows SET idblacklist=$lista WHERE campaign_id = '$campana' LIMIT 1";
                        $result = sv_mysqli_query($con, $query);
                        $sal["Estado"] = "ok";
                    } else {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_listaInvalida");
                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("%campana%", $campana, $this->lang->line("desc_campanaInvalidaX"));
            }
            $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 deleteStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $cliente = $_SESSION["Cliente"];
            $status = limpia($_POST["status"]);
            $campana = limpia($_POST["campana"]);
            $query = "SELECT campaign_id FROM vicidial_campaign_statuses WHERE status = '$status' AND campaign_id = '$campana' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $cliente = $_SESSION["Cliente"];
                $donde = "";
                if ($cliente != -1) {
                    $donde = "AND user_group = '" . $cliente . "'";
                }
                $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $query = "DELETE FROM vicidial_campaign_statuses WHERE status = '$status' AND campaign_id = '$campana' LIMIT 1";
                    $result = sv_mysqli_query($con, $query);
                    $sal["QUERY"] = $query;
                    $query = "DELETE FROM dialvox_campaign_statuses WHERE status = '$status' AND campaign_id = '$campana' LIMIT 1";
                    $result = sv_mysqli_query($con, $query);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_permisosEliminarEstado");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_eliminarEstado");
            }
            $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 getStatuses()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $registros = 10;
            $pagina = limpia($_POST["pagina"]) - 1;
            $skip = $registros * $pagina;
            $sal = array();
            $cliente = $_SESSION["Cliente"];
            $campana = limpia($_POST["campana"]);
            $donde = "";
            $textoBusqueda = "";
            if (isset($_POST["texto"])) {
                $textoBusqueda = limpia($_POST["texto"]);
            }
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id,dial_statuses,auto_alt_dial_statuses FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT status,status_name,selectable,human_answered,(SELECT vsc_id FROM vicidial_status_categories WHERE vsc_id = vicidial_campaign_statuses.category) as category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,answering_machine,'propios' from vicidial_campaign_statuses where campaign_id='$campana' AND status_name LIKE '%$textoBusqueda%'UNION SELECT status,status_name,selectable,human_answered,'Estatus de sistema' category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,answering_machine,'sistema' from vicidial_statuses WHERE status_name LIKE '%$textoBusqueda%' LIMIT $skip,$registros";
                $result = sv_mysqli_query($con, $query);
                $sal["Registros"] = array();
                $estatus = $row["dial_statuses"];
                $alt = $row["auto_alt_dial_statuses"];
                while ($row = sv_mysqli_fetch_array($result)) {
                    $objeto = $row;
                    if ($row["propios"] != "sistema") {
                        $objeto["sistema"] = "N";
                        $result2 = sv_mysqli_query($con, "SELECT blackPhone,blackLead FROM dialvox_campaign_statuses WHERE campaign_id='$campana' AND status='{$row["status"]}'");
                        if ($row2 = sv_mysqli_fetch_array($result2)) {
                            $objeto["blackPhone"] = $row2["blackPhone"];
                            $objeto["blackLead"] = $row2["blackLead"];
                        } else {
                            $objeto["blackPhone"] = "0";
                            $objeto["blackLead"] = "0";
                            sv_mysqli_query($con, "INSERT INTO dialvox_campaign_statuses(campaign_id,status,blackPhone,blackLead) VALUES('$campana','{$row["status"]}','0','0')");
                        }
                    } else {
                        $objeto["sistema"] = "Y";
                    }
                    if (strpos($estatus, " {$row["status"]} ") === false) {
                        $objeto["marcable"] = "N";
                    } else {
                        $objeto["marcable"] = 'Y';
                    }
                    if (strpos($alt, " {$row["status"]} ") === false) {
                        $objeto["siguiente"] = "N";
                    } else {
                        $objeto["siguiente"] = 'Y';
                    }
                    $sal["Registros"][] = $objeto;
                }
                $query = "SELECT (SELECT COUNT(status) from vicidial_statuses WHERE status_name LIKE '%$textoBusqueda%') + (SELECT COUNT(status) FROM vicidial_campaign_statuses where campaign_id='$campana'  AND status_name LIKE '%$textoBusqueda%' AND selectable = 'Y')";
                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                $sal["Cuenta"] = $row[0];
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosListasEstados");
            }

            $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 convierteStringGruposDeEntradaAArreglo($gruposDeEntrada)
    {
        $gruposDeEntrada = preg_replace('/-$/', '', $gruposDeEntrada);
        $arrFinal = array();
        $arrGruposDeEntrada = explode(' ', $gruposDeEntrada);
        for ($i = 0; $i < count($arrGruposDeEntrada); $i++) {
            if (strlen($arrGruposDeEntrada[$i]) > 0) {
                $arrFinal[] = trim($arrGruposDeEntrada[$i]);
            }
        }
        return $arrFinal;
    }
    public function coincideGruposDeEntrada($gruposDeEntradaA, $gruposDeEntradaB)
    {
        $gruposResultantes = "";
        for ($i = 0; $i < count($gruposDeEntradaA); $i++) {
            for ($j = 0; $j < count($gruposDeEntradaB); $j++) {
                if (strcmp($gruposDeEntradaA[$i], $gruposDeEntradaB[$j]) === 0) {
                    $gruposResultantes .= ($gruposDeEntradaA[$i] . ' ');
                }
            }
        }
        $gruposResultantes .= '-';
        return $gruposResultantes;
    }
    public function addStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $cliente = $_SESSION["Cliente"];
            $campana = limpia($_POST["campana"]);
            $cliente = $_SESSION["Cliente"];
            $status = limpia($_POST["status"]);
            $nombre = limpia($_POST["nombre"]);
            $seleccionable = limpia($_POST["seleccionable"]);
            $human = limpia($_POST["human"]);
            $categoria = limpia($_POST["categoria"]);
            $sale = limpia($_POST["sale"]);
            $dnc = limpia($_POST["dnc"]);
            $cc = limpia($_POST["cc"]);
            $completed = limpia($_POST["limpia"]);
            $callback = limpia($_POST["callback"]);
            $unwork = limpia($_POST["unwork"]);
            $ni = limpia($_POST["ni"]);
            $answering_machine = limpia($_POST["answering_machine"]);
            $blackPhone = limpia($_POST["blackPhone"]);
            $blackLead = limpia($_POST["blackLead"]);

            $donde = "";
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $status = limpia($_POST["status"]);
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT status from vicidial_campaign_statuses where campaign_id='$campana' AND status = '$status'";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = "El status ya esta en uso";
                } else {
                    if (strlen($status) < 1 || strlen($status) > 8) {
                        $sal["Estado"] = "error";
                        $sal["Estado"] = "El status debe tener entre 1 y 8 caracteres";
                    } else {
                        if (strlen($nombre) < 2 || strlen($nombre) > 30) {
                            $sal["Estado"] = "error";
                            $sal["Estado"] = "El nombre debe tener entre 2 y 30 caracteres";
                        } else {
                            $cliente = $_SESSION["Cliente"];
                            $mas = "";
                            if ($cliente == -1) {
                                $cliente = "";
                            } else {
                                $mas = "+";
                            }

                            $query = "SELECT vsc_name,vsc_id FROM vicidial_status_categories WHERE vsc_id REGEXP '^" . $cliente . "" . $mas . "[0-9]+$' AND vsc_id = '$categoria' LIMIT 1";
                            $result = sv_mysqli_query($con, $query);
                            if ($row = sv_mysqli_fetch_array($result)) {
                                $query = "INSERT INTO vicidial_campaign_statuses (campaign_id,status,status_name,selectable,human_answered,category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,answering_machine) VALUES ('$campana','$status','$nombre','$seleccionable','$human','$categoria','$sale','$dnc','$cc','$ni','$unwork','$callback','$completed','$answering_machine') ";
                                $result = sv_mysqli_query($con, $query);
                                $query = "INSERT INTO dialvox_campaign_statuses (campaign_id,status,blackPhone,blackLead) VALUES ('$campana','$status','$blackPhone','$blackLead') ";
                                $result = sv_mysqli_query($con, $query);
                                $sal["Estado"] = "ok";
                            } else {
                                $sal["Estado"] = "error";
                                $sal["Descripcion"] = $this->lang->line("desc_categoriaInvalida");
                            }
                        }
                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosVerEstados");
            }

            $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 changeIngroupCampaign()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = limpia($_POST["id"]);
            $sal = array();
            $con = getConnection();
            $cliente = $_SESSION["Cliente"];
            $LOGallowed_campaignsSQL = "AND user_group = '$cliente'";
            if ($cliente == -1) {
                $LOGallowed_campaignsSQL = "";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $LOGallowed_campaignsSQL LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $ingroups = limpia($_POST["ingroups"]);
                $query = "UPDATE vicidial_campaigns SET closer_campaigns='$ingroups' WHERE campaign_id='$campana'";
                sv_mysqli_query($con, $query);
                //Aqui se obtienen todos los usuarios logueados a esta campaña en la tabla de vicidial_live_agents
                $queryUsuariosLogueados = "SELECT user, NOW() as hoy FROM vicidial_live_agents WHERE campaign_id = '$campana'";
                if ($resultUsuariosLogueados = sv_mysqli_query($con, $queryUsuariosLogueados)) {
                    while ($rowUsuariosLogueados = sv_mysqli_fetch_array($resultUsuariosLogueados)) {
                        //Aqui se buscan los grupos de entrada que coincidan entre el usuario y la campaña
                        //Primero se obtienen los grupos de entrada a los que esta subscrito el usuario
                        $usuarioUsuarioLogueado = $rowUsuariosLogueados["user"];
                        $NOW_TIME = $rowUsuariosLogueados["hoy"];
                        $gruposDeEntradaDeLaCampana = $this->convierteStringGruposDeEntradaAArreglo($ingroups);
                        //Buscamos todos los grupos de entrada en los que esta permitido el agente
                        $queryGruposDeEntradaDelUsuario = "SELECT closer_campaigns FROM vicidial_users WHERE user = '$usuarioUsuarioLogueado' LIMIT 1";
                        if ($resultGruposDeEntradaDelUsuario = sv_mysqli_query($con, $queryGruposDeEntradaDelUsuario)) {
                            if ($rowGruposDeEntradaDelUsuario = sv_mysqli_fetch_array($resultGruposDeEntradaDelUsuario)) {
                                //Creamos un arreglo a partir de los grupos de entrada, separando por espacio
                                $gruposDeEntradaDelAgente = $this->convierteStringGruposDeEntradaAArreglo($rowGruposDeEntradaDelUsuario["closer_campaigns"]);
                                $gruposDeEntradaResultantes = $this->coincideGruposDeEntrada($gruposDeEntradaDeLaCampana, $gruposDeEntradaDelAgente);
                                //Ahora se realiza el procedimiento para el cambio en caliente
                                $queryCambioVicidialLiveAgents = "UPDATE vicidial_live_agents set external_ingroups='$gruposDeEntradaResultantes',external_blended='0',external_igb_set_user='6666',manager_ingroup_set='SET' where user='$usuarioUsuarioLogueado'";
                                if ($resultCambioVicidialLiveAgents = sv_mysqli_query($con, $queryCambioVicidialLiveAgents)) {
                                    $queryEliminacionInboundAgents = "DELETE FROM vicidial_live_inbound_agents where user='$usuarioUsuarioLogueado'";
                                    if ($resultEliminacionInboundAgents = sv_mysqli_query($con, $queryEliminacionInboundAgents)) {
                                        $arrGruposResultantes = $this->convierteStringGruposDeEntradaAArreglo($gruposDeEntradaResultantes);
                                        for ($i = 0; $i < count($arrGruposResultantes); $i++) {
                                            if (strlen($arrGruposResultantes[$i]) > 0) {
                                                $queryObtenerStats = "SELECT group_weight,calls_today FROM vicidial_inbound_group_agents where user='$usuarioUsuarioLogueado' and group_id='$arrGruposResultantes[$i]'";
                                                if ($resultObtenerStats = sv_mysqli_query($con, $queryObtenerStats)) {
                                                    $group_weight = 0;
                                                    $calls_today = 0;
                                                    if ($rowObtenerStats = sv_mysqli_fetch_array($resultObtenerStats)) {
                                                        $group_weight = $row["group_weight"];
                                                        $calls_today = $row["calls_today"];
                                                    }
                                                    $queryInsertaStats = "INSERT INTO vicidial_live_inbound_agents set user='$usuarioUsuarioLogueado',group_id='$arrGruposResultantes[$i]',group_weight='$group_weight',calls_today='$calls_today',last_call_time='$NOW_TIME',last_call_finish='$NOW_TIME'";
                                                    $resultInsertaStats = sv_mysqli_query($con, $queryInsertaStats);
                                                    if (!$resultInsertaStats) {
                                                        $sal["Estado"] = "error";
                                                        $sal["Descripcion"] = $this->lang->line("desc_changeIngroupCampaign_error_db_insertarStats");
                                                        break;
                                                    }
                                                } else {
                                                    $sal["Estado"] = "error";
                                                    $sal["Descripcion"] = $this->lang->line("desc_changeIngroupCampaign_error_db_obtenerStats");
                                                    break;
                                                }
                                            }
                                        }
                                    } else {
                                        $sal["Estado"] = "error";
                                        $sal["Descripcion"] = $this->lang->line("desc_changeIngroupCampaign_error_db_eliminarInboundAgents");
                                        break;
                                    }
                                } else {
                                    $sal["Estado"] = "error";
                                    $sal["Descripcion"] = $this->lang->line("desc_changeIngroupCampaign_error_db_cambiarVicidialLive");
                                    break;
                                }
                            } else {
                                $sal["Estado"] = "error";
                                $sal["Descripcion"] = $this->lang->line("desc_changeIngroupCampaign_error_buscarGruposDeEntradaDeUsuario_usuarioNoEncontrado");
                                break;
                            }
                        } else {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_changeIngroupCampaign_error_db_buscarGruposDeEntradaDeUsuario");
                            break;
                        }
                    }
                    if (!array_key_exists("Estado", $sal)) {
                        $sal["Estado"] = "ok";
                    }
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_changeIngroupCampaign_error_db_buscarUsuariosLogueados");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditarCampana");
            }
            $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 changeXfersCampaign()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = limpia($_POST["id"]);
            $sal = array();
            $con = getConnection();
            $cliente = $_SESSION["Cliente"];
            $LOGallowed_campaignsSQL = "AND user_group = '$cliente'";
            if ($cliente == -1) {
                $LOGallowed_campaignsSQL = "";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $LOGallowed_campaignsSQL LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $ingroups = limpia($_POST["ingroups"]);
                $query = "UPDATE vicidial_campaigns SET xfer_groups='$ingroups' WHERE campaign_id='$campana'";
                sv_mysqli_query($con, $query);
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditarCampana");
            }
            $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 duplicateCampaign()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = limpia($_POST["campana"]);
            $sal = array();
            $con = getConnection();
            $cliente = $_SESSION["Cliente"];
            $LOGallowed_campaignsSQL = "AND user_group = '$cliente'";
            if ($cliente == -1) {
                $LOGallowed_campaignsSQL = "";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $LOGallowed_campaignsSQL LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT campaign_id,campaign_name FROM vicidial_campaigns WHERE campaign_id = '$campana'";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $nombre = $row["campaign_name"] . "_copia";
                    $query = "SELECT (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id REGEXP '^[0-9]+$' ORDER BY CAST(campaign_id AS INT) DESC LIMIT 1) AS Campa, (SELECT campaign_id FROM vicidial_lists WHERE campaign_id REGEXP '^[0-9]+$' ORDER BY CAST(campaign_id as INT) DESC LIMIT 1) AS List";
                    $result = sv_mysqli_query($con, $query);
                    $id = 10;
                    if ($row = sv_mysqli_fetch_array($result)) {
                        $max_id = max($row["Campa"], $row["List"]);
                        $id = $max_id + 1;
                    }
                    $query = "INSERT INTO vicidial_campaigns (campaign_id,campaign_name,active,dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,list_order_mix,campaign_allow_inbound,manual_dial_list_id,default_xfer_group,xfer_groups,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_shift_id,qc_get_record_launch,qc_show_recording,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_third_audio_file,survey_third_status,survey_third_exten,survey_fourth_digit,survey_fourth_audio_file,survey_fourth_status,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,campaign_calldate,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_hopper_level,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_pause_precall_code,auto_resume_precall,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,in_group_dial,in_group_dial_select,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dead_max_dispo,dispo_max,dispo_max_dispo,pause_max,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,allow_chats,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo) SELECT '$id','$nombre',active,dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,list_order_mix,campaign_allow_inbound,manual_dial_list_id,default_xfer_group,xfer_groups,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_shift_id,qc_get_record_launch,qc_show_recording,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_third_audio_file,survey_third_status,survey_third_exten,survey_fourth_digit,survey_fourth_audio_file,survey_fourth_status,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,campaign_calldate,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_hopper_level,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_pause_precall_code,auto_resume_precall,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,in_group_dial,in_group_dial_select,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dead_max_dispo,dispo_max,dispo_max_dispo,pause_max,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,allow_chats,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo FROM vicidial_campaigns WHERE campaign_id = '$campana'";
                    $result = sv_mysqli_query($con, $query);
                    $stmtA = "INSERT INTO vicidial_campaign_stats (campaign_id) values('$id');";
                    $rslt = sv_mysqli_query($con, $stmtA);
                    $stmtA = "INSERT INTO vicidial_campaign_stats_debug (campaign_id) values('$id');";
                    $rslt = sv_mysqli_query($con, $stmtA);
                    $query = "INSERT INTO vicidial_campaign_statuses (campaign_id,status,status_name,selectable,human_answered,category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,answering_machine) SELECT '$id',status,status_name,selectable,human_answered,category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,answering_machine FROM vicidial_campaign_statuses WHERE campaign_id = '$campana'";
                    $result = sv_mysqli_query($con, $query);

                    // Query para las pausas
                    $query = "INSERT INTO dialvox_pausas(campaign_id,pause_code,tiempo_limite,requiere_password) SELECT '$id',pause_code,tiempo_limite,requiere_password FROM dialvox_pausas WHERE campaign_id = '$campana'";
                    $result = sv_mysqli_query($con, $query);
                    $sal["QUERY_PAUSAS"] = mysqli_error($con);
                    // Query para las pausas

                    // Query para los frames del agente
                    $query = "INSERT INTO dialvox_frame_agente(Titulo,Campana,Cliente,Url,Estatico) SELECT Titulo,'$id',Cliente,Url,Estatico FROM dialvox_frame_agente WHERE Campana = '$campana'";
                    $result = sv_mysqli_query($con, $query);
                    $sal["QUERY_FRAME"] = mysqli_error($con);
                    // Query para los frames del agente

                    $query = "INSERT INTO vicidial_pause_codes (campaign_id,pause_code, pause_code_name, billable, time_limit, require_mgr_approval) SELECT '$id', pause_code, pause_code_name, billable, time_limit, require_mgr_approval FROM vicidial_pause_codes WHERE campaign_id = '$campana'";
                    $result = sv_mysqli_query($con, $query);
                    $query = "INSERT INTO vicidial_tables_windows (campaign_id,windows_check,max_time_dispo,allow_beep,time_beep,time_repeat) SELECT '$id',windows_check,max_time_dispo,allow_beep,time_beep,time_repeat FROM vicidial_tables_windows WHERE campaign_id='$campana'";
                    $result = sv_mysqli_query($con, $query);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_campanaInvalida");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditarCampana");
            }
            $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 deleteCampaign()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            $usuario = $_SESSION["Usuario"];
            include_once RUTA_APP . 'Sesiones.php';
            $sal = array();
            $con = getConnection();
            $linea = 0;
            $campaign_id = $_POST["campana"];
            $cliente = $_SESSION["Cliente"];
            $LOGallowed_campaignsSQL = "AND user_group = '$cliente'";
            if ($cliente == -1) {
                $LOGallowed_campaignsSQL = "";
            }
            $query = "SELECT campaign_id,dial_method FROM vicidial_campaigns WHERE campaign_id = '$campaign_id' $LOGallowed_campaignsSQL LIMIT 1";
            $sal["query"] = $query;
            $result = sv_mysqli_query($con, $query);
            $LOGallowed_campaignsSQL = "";
            if ($row = sv_mysqli_fetch_array($result)) {
                if (strlen($campaign_id) >= 2) {
                    $dial_method = $row["dial_method"];
                    $stmtA = "DELETE from vicidial_campaigns where campaign_id='$campaign_id' $LOGallowed_campaignsSQL limit 1;";
                    sv_mysqli_query($con, $stmtA);
                    $stmt = "DELETE from vicidial_campaign_agents where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_live_agents where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_campaign_statuses where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_campaign_hotkeys where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_callbacks where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_campaign_stats where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_campaign_stats_debug where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_lead_recycle where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_campaign_server_stats where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_server_trunks where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_pause_codes where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_campaigns_list_mix where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_xfer_presets where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_xfer_stats where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_campaign_cid_areacodes where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_hopper where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_remote_agents where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;";
                    sv_mysqli_query($con, $stmt);

                    // Query para eliminar los frames del agente
                    $stmt = "DELETE FROM dialvox_frame_agente WHERE Campana='$campaign_id'";
                    sv_mysqli_query($con, $stmt);
                    // Query para eliminar los frames del agente

                    // Query para eliminar los frames del agente
                    $stmt = "DELETE FROM dialvox_pausas WHERE campaign_id='$campaign_id'";
                    sv_mysqli_query($con, $stmt);
                    // Query para eliminar los frames del agente

                    $stmt = "SELECT idcampaign_wa FROM vicidial_tables_windows where campaign_id='$campaign_id';";
                    $result = sv_mysqli_query($con, $stmt);
                    $row4 = sv_mysqli_fetch_array($result);
                    if ($row4["idcampaign_wa"] !== "") {
                        $data = array("id" => $row4["idcampaign_wa"], 'usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])));

                        $url = RUTA_WA . "/Campana/delete";
                        $options = array(
                            'http' => array(
                                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                'method' => 'POST',
                                'content' => http_build_query($data),
                            ),
                        );
                        $context = stream_context_create($options);
                        file_get_contents($url, false, $context);
                    }
                    $stmt = "DELETE FROM vicidial_tables_windows where campaign_id='$campaign_id';";
                    sv_mysqli_query($con, $stmt);
                    $SQL_log = "$stmtA|";
                    $SQL_log = preg_replace('/;/', '', $SQL_log);
                    $SQL_log = addslashes($SQL_log);
                    $ip = $_SERVER["REMOTE_ADDR"];
                    $stmt = "INSERT INTO vicidial_admin_log set event_date=NOW(), user='$usuario', ip_address='$ip', event_section='CAMPAIGNS', event_type='DELETE', record_id='$campaign_id', event_code='ADMIN DELETE CAMPAIGN', event_sql=\"$SQL_log\", event_notes=''";
                    sv_mysqli_query($con, $stmt);

                    if ($dial_method == 'INBOUND_MAN') {
                        $group_id = $campaign_id . "_ENT";
                        $stmtA = "DELETE from vicidial_inbound_groups where group_id='$group_id' and group_id NOT IN('AGENTDIRECT')";
                        $rslt = sv_mysqli_query($con, $stmtA);
                        $stmtB = "DELETE from vicidial_inbound_group_agents where group_id='$group_id'";
                        $rslt = sv_mysqli_query($con, $stmtB);
                        $stmtC = "DELETE from vicidial_live_inbound_agents where group_id='$group_id'";
                        $rslt = sv_mysqli_query($con, $stmtC);
                        $stmtD = "DELETE from vicidial_campaign_stats where campaign_id='$group_id'";
                        $rslt = sv_mysqli_query($con, $stmtD);
                        $stmtE = "DELETE from vicidial_campaign_stats_debug where campaign_id='$group_id'";
                        $rslt = sv_mysqli_query($con, $stmtE);
                    }

                    $campana_autopausa = $campaign_id;
                    $query_autopausa = "DELETE FROM dialvox_campana_autopausa WHERE Campana='$campana_autopausa'";
                    sv_mysqli_query($con, $query_autopausa);

                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_campanaIdInvalido");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEliminarCampana");
            }
            $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 descargarReporteFromWA()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) && $_SESSION["allow_waCli"] && NEED_WA) {
            include_once RUTA_APP . 'Sesiones.php';
            $sal = array();
            $url = RUTA_WA . "/GrupoTelefonos/select";
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])));
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);
            if ($resultados->Estado === "ok") {
                $sal["GrupoTelefonos"] = $resultados->Registros;
                $url = RUTA_WA . "/listaNegra/select";
                $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])));
                $options = array(
                    'http' => array(
                        'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                        'method' => 'POST',
                        'content' => http_build_query($data),
                    ),
                );
                $context = stream_context_create($options);
                $result = file_get_contents($url, false, $context);
                $resultados = json_decode($result);
                if ($resultados->Estado === "ok") {
                    $sal["ListaNegra"] = $resultados->Registros;
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
            }
            $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 getcampaignconfigWa()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"]) && ((strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) && $_SESSION["allow_waCli"] && NEED_WA) {
            include_once RUTA_APP . 'Sesiones.php';
            $sal = array();
            $url = RUTA_WA . "/GrupoTelefonos/select";
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])));
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);
            if ($resultados->Estado === "ok") {
                $sal["GrupoTelefonos"] = $resultados->Registros;
                $url = RUTA_WA . "/listaNegra/select";
                $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])));
                $options = array(
                    'http' => array(
                        'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                        'method' => 'POST',
                        'content' => http_build_query($data),
                    ),
                );
                $context = stream_context_create($options);
                $result = file_get_contents($url, false, $context);
                $resultados = json_decode($result);
                if ($resultados->Estado === "ok") {
                    $sal["ListaNegra"] = $resultados->Registros;
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
            }
            $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 downloadCSVWhatsApp()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || (strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) && NEED_WA && $_SESSION["allow_waCli"]) {
            $url = RUTA_WA . "/Campana/getOne";
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "id" => $_GET["campana"]);
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);

            if ($resultados->Estado === "ok") {
                $fechaInicio = explode("/", $resultados->Campana->fechaInicio);
                $fechaFin = explode("/", $resultados->Campana->fechaFin);
                ob_start();
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=Reporte mixto-" . $resultados->Campana->fechaInicio . " - " . $resultados->Campana->fechaFin . ".csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');
                $in = fopen(RUTA_WA . "/Reportes/blendedCSV?usuarioAPI=" . $_SESSION["user_wa"] . "&passwordAPI=" . base64_encode(base64_encode($_SESSION["pass_wa"])) . "&id=" . $_GET["campana"] . "&yearIni=" . urlencode($fechaInicio[2]) . "&yearFin=" . urlencode($fechaFin[2]) . "&monthIni=" . urlencode($fechaInicio[0]) . "&monthFin=" . urlencode($fechaFin[0]) . "&dayIni=" . urlencode($fechaInicio[1]) . "&dayFin=" . urlencode($fechaFin[1]), "r");
                while (!feof($in)) {
                    fwrite($out, fread($in, 8192));
                }
                fclose($out);
                fclose($in);
                $str = ob_get_contents();
                ob_end_clean();
                $this->output->set_output($str);
            } else {

                $this->output->set_status_header('404');
            }
        } else {
            $this->output->set_status_header('403');
        }
    }

    public function downloadFileWhatsApp()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || (strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) && NEED_WA && $_SESSION["allow_waCli"]) {
            $url = RUTA_WA . "/Campana/getOne";
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "id" => $_GET["campana"]);
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);

            if ($resultados->Estado === "ok") {
                $fechaInicio = explode("/", $resultados->Campana->fechaInicio);
                $fechaFin = explode("/", $resultados->Campana->fechaFin);
                ob_start();
                header("Content-type: application/zip");
                header("Content-Disposition: attachment; filename=Archivos -" . $resultados->Campana->fechaInicio . " - " . $resultados->Campana->fechaFin . ".zip");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');
                $in = fopen(RUTA_WA . "/Mensaje/download?usuarioAPI=" . $_SESSION["user_wa"] . "&passwordAPI=" . base64_encode(base64_encode($_SESSION["pass_wa"])) . "&campana=" . $_GET["campana"] . "&yearIni=" . urlencode($fechaInicio[2]) . "&yearFin=" . urlencode($fechaFin[2]) . "&monthIni=" . urlencode($fechaInicio[0]) . "&monthFin=" . urlencode($fechaFin[0]) . "&dayIni=" . urlencode($fechaInicio[1]) . "&dayFin=" . urlencode($fechaFin[1]) . "&tipos=audio/.*,image/.*,text/plain|application/vnd.openxmlformats-officedocument.presentationml.presentation|application/ms-powerpoint|application/mspowerpoint|application/powerpoint|application/ppt|application/vnd-mspowerpoint|application/vnd_ms-powerpoint|application/x-mspowerpoint|application/x-powerpoint|application/vnd.ms-powerpoint|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet|application/excel|application/msexcel|application/msexcell|application/x-dos_ms_excel|application/x-excel|application/x-ms-excel|application/x-msexcel|application/x-xls|application/xls|application/vnd.ms-excel|application/vnd.ms-word|application/doc|application/msword|application/msword-doc|application/vnd.msword|application/winword|application/word|application/x-msw6|application/x-msword|application/x-msword-doc|application/pdf|application/vnd.openxmlformats-officedocument.wordprocessingml.document|application/vnd.ms-word.document.12|application/vnd.openxmlformats-officedocument.word,video/.*,*", "r");
                while (!feof($in)) {
                    fwrite($out, fread($in, 8192));
                }
                fclose($out);
                fclose($in);
                $str = ob_get_contents();
                ob_end_clean();
                $this->output->set_output($str);
            } else {

                $this->output->set_status_header('404');
            }
        } else {
            $this->output->set_status_header('403');
        }
    }
    public function uploadMeesagesToWhatsApp()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || (strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) && NEED_WA && $_SESSION["allow_waCli"]) {
            $sal = array();
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "registros" => json_decode($_POST["registros"]), "mensaje" => $_POST["mensaje"]);
            $url = RUTA_WA . "/Campana/sendMessages";
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);

            if ($resultados->Estado === "ok") {
                //archivoAdjunto.append("Registros", JSON.stringify(res.mensajes))
                $post = array();
                $post = array("Registros" => json_encode($resultados->mensajes), 'usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "campana" => $_POST["campana"]);

                if (isset($_FILES["adjunto"])) {
                    $post["adjunto"] = new CURLFile($_FILES["adjunto"]["tmp_name"], $_FILES["adjunto"]["type"], $_FILES["adjunto"]["name"]);
                }
                // URL to upload to
                $url = RUTA_WA . "/Mensaje/sendManual";

                $curl = curl_init();

                curl_setopt_array($curl, array(
                    CURLOPT_URL => $url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POSTFIELDS => $post,
                ));

                $result = curl_exec($curl);
                $resultados = json_decode($result);
                curl_close($curl);
                if ($resultados->Estado === "ok") {
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                }
                $this->output->set_output(json_encode($sal));
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                $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 getCRMFromWhatsApp()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || (strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) && NEED_WA && $_SESSION["allow_waCli"]) {
            $campana = $_POST["campana"];
            $telefono = $_POST["telefono"];
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "campana" => $campana, "telefono" => $telefono);
            $url = RUTA_WA . "/CRM/find";
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);
            if ($resultados->Estado === "ok") {
                $sal["Registros"] = $resultados->Registros;
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
            }
            $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 deleteCRMFromWhatsApp()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) && NEED_WA && $_SESSION["allow_waCli"]) {
            $campana = $_POST["campana"];
            $telefono = $_POST["telefono"];
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "campana" => $campana, "telefono" => $telefono);
            $url = RUTA_WA . "/CRM/delete";
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);
            if ($resultados->Estado === "ok") {
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
            }
            $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 uploadCRMToWhatsApp()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) && NEED_WA && $_SESSION["allow_waCli"]) {
            $arreglo = $_POST["campos"];
            $campana = $_POST["campana"];
            $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "campos" => $arreglo, "campana" => $campana);
            $url = RUTA_WA . "/CRM/uploadData";
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $resultados = json_decode($result);
            if ($resultados->Estado === "ok") {
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
            }
            $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 updateCampaign()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sal = array();
            $con = getConnection();
            $id = limpia($_POST["idCampana"]);
            $and = "";
            if ($_SESSION["Cliente"] != -1) {
                $and = "AND user_group = '" . $_SESSION["Cliente"] . "'";
            }
            $query = "SELECT campaign_id,user_group from vicidial_campaigns where campaign_id = '$id' $and limit 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $nombre = limpia($_POST["nombreCampana"]);
                $descripcion = limpia($_POST["descripcionCampana"]);
                $grupo = $row["user_group"];
                $activa = limpia($_POST["activa"]);
                $web_form_address = limpia($_POST["web_form"]);
                $web_form_address_two = limpia($_POST["web_form_address_two"]);
                $drop_percentage_limit = limpia($_POST["drop_percentage_limit"]);
                $use_auto_hopper = limpia($_POST["use_auto_hopper"]);
                $hopper_level = limpia($_POST["hopper_level"]);
                $lead_order_randomize = limpia($_POST["lead_order_randomize"]);
                $adaptive_dl_diff_target = limpia($_POST["adaptive_dl_diff_target"]);

                $adaptive_intensity = limpia($_POST["adaptive_intensity"]);

                $adaptive_maximum_level = limpia($_POST["adaptive_maximum_level"]);
                $lead_order = limpia($_POST["lead_order"]);
                $auto_dial_level = limpia($_POST["auto_dial_level"]);
                $metodo = limpia($_POST["dial_method"]);
                $ventana = limpia($_POST["ventanas"]);
                $tiempoDispo = limpia($_POST["tiempoDispo"]);
                $allow_beep = limpia($_POST["allow_beep"]);
                $time_beep = limpia($_POST["time_beep"]);
                $time_repeat = limpia($_POST["time_repeat"]);
                $campaign_allow_inbound = isset($_POST["BLENDED"]) ? limpia($_POST["BLENDED"]) : "N";
                $tiempo_DEAD = limpia($_POST["DEAD"]);
                $defaul_xfer = limpia($_POST["defaul_xfer"]);
                $campaign_recording = limpia($_POST["campaign_recording"]);
                $list_id = limpia($_POST["list_id"]);
                $dead_to_dispo = "DISABLED";
                $dead_max = 0;
                $manual_dial_search_filter = "CAMPLISTS_ALL";

                // Campaign caller id
                $campaign_cid = limpia($_POST["campaign_cid"]);

                if ($tiempo_DEAD != 0) {
                    $dead_to_dispo = "ENABLED";
                    $dead_max = $tiempo_DEAD;
                }
                if ($metodo == "MANUAL") {
                    $campaign_allow_inbound = "N";
                }
                if ($metodo == "INBOUND_MAN") {
                    $campaign_allow_inbound = "Y";
                }
                $query = "SELECT count(campaign_id) from vicidial_campaigns where campaign_id='$id';";
                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                $allow_wa = 0;

                if ($row[0] <= 0) {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = array_key_exists("Descripcion", $sal) ? $sal["Descripcion"] : $this->lang->line("desc_campanaInvalida");
                } else {
                    if ((strlen($id) < 2) or (strlen($id) > 8) or (strlen($nombre) < 6) or (strlen($nombre) > 40)) {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_nombreInvalido");
                    } else {
                        $carrier = limpia($_POST["carrier"]);
                        $and = "";
                        if ($_SESSION["Cliente"] != -1) {
                            $and = "AND user_group = '" . $_SESSION["Cliente"] . "'";
                        }
                        $query = "SELECT carrier_id,carrier_name FROM vicidial_server_carriers WHERE carrier_id = '$carrier' $and 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_campaigns SET dial_prefix = '$carrier', manual_dial_prefix = '$carrier', dial_method = '$metodo',campaign_name = '$nombre',campaign_description = '$descripcion',active = '$activa',lead_order = '$lead_order',web_form_address = '$web_form_address',hopper_level = '$hopper_level',auto_dial_level = '$auto_dial_level',campaign_changedate=NOW(),web_form_address_two = '$web_form_address_two',user_group = '$grupo',adaptive_dropped_percentage ='$drop_percentage_limit',use_auto_hopper='$use_auto_hopper',lead_order_randomize='$lead_order_randomize',adaptive_dl_diff_target='$adaptive_dl_diff_target',adaptive_intensity='$adaptive_intensity',adaptive_maximum_level='$adaptive_maximum_level',campaign_allow_inbound='$campaign_allow_inbound',default_xfer_group='$defaul_xfer',campaign_recording='$campaign_recording',dead_max='$dead_max',dead_to_dispo='$dead_to_dispo', campaign_cid='$campaign_cid',manual_dial_list_id='$list_id', manual_dial_search_filter='$manual_dial_search_filter' WHERE campaign_id = '$id' LIMIT 1";
                            sv_mysqli_query($con, $query);
                            $query = "UPDATE vicidial_tables_windows SET windows_check = '$ventana',allow_wa='$allow_wa', max_time_dispo='$tiempoDispo', time_beep='$time_beep',allow_beep='$allow_beep',time_repeat='$time_repeat'  WHERE campaign_id = '$id' LIMIT 1";
                            sv_mysqli_query($con, $query);

                            // ? RESOLVES: Autopausa


                            $campana_autopausa = $id;
                            if (isset($_POST["isAutopausa"])) {
                                $query_autopausa = "SELECT CodigoPausa,Tono FROM dialvox_campana_autopausa WHERE Campana='$campana_autopausa' LIMIT 1";
                                $result_autopausa = sv_mysqli_query($con, $query_autopausa);

                                $actualizar_autopausa = false;
                                if ($result_autopausa) {
                                    $row_autopausa = sv_mysqli_fetch_array($result_autopausa);

                                    if ($row_autopausa) {
                                        $actualizar_autopausa = true;
                                    }
                                }

                                $codigoPausa_autopausa = "DAUTO";
                                $tono_autopausa = $_POST["autoPausaTono"];
                                $volumen_autopausa = $_POST["autoPausaVolumen"];
                                $metodo_autopausa = $_POST["autoPausaMetodo"];
                                $tiempo_autopausa = $_POST["autoPausaTiempo"];


                                if ($actualizar_autopausa) {
                                    $query_autopausa = "UPDATE dialvox_campana_autopausa SET Tono='$tono_autopausa',CodigoPausa='$codigoPausa_autopausa',Volumen='$volumen_autopausa',MetodoDistribucion='$metodo_autopausa',TiempoTimbrado='$tiempo_autopausa' WHERE Campana='$campana_autopausa'";
                                } else {
                                    $query_autopausa = "INSERT INTO dialvox_campana_autopausa(Campana,CodigoPausa,Tono,Volumen,MetodoDistribucion,TiempoTimbrado) VALUES ('$campana_autopausa','$codigoPausa_autopausa','$tono_autopausa','$volumen_autopausa','$metodo_autopausa','$tiempo_autopausa')";
                                }

                                sv_mysqli_query($con, $query_autopausa);
                            } else {
                                $query_autopausa = "DELETE FROM dialvox_campana_autopausa WHERE Campana='$campana_autopausa'";
                                sv_mysqli_query($con, $query_autopausa);
                            }

                            if (NEED_WA && $_SESSION["allow_waCli"]) {

                                if ($allow_wa == 1) {
                                    $cliente = $_SESSION["idclient_wa"];
                                    $idCampana = limpia($_POST["idCampanaWA"]);
                                    $grupoTelefonos = limpia($_POST["grupoTelefono"]);
                                    $fechaInicio = limpia($_POST["fechaInicio"]);
                                    $fechaFin = limpia($_POST["fechaFin"]);
                                    $horaInicio = limpia($_POST["horaInicio"]);
                                    $horaFin = limpia($_POST["horaFin"]);
                                    $autoRespuesta = limpia($_POST["autoRespuesta"]);
                                    $mensaje = limpia($_POST["mensaje"]);
                                    $nombre = limpia($_POST["nombre"]);
                                    $listaNegra = limpia($_POST["listaNegra"]);

                                    $modoChat = $_POST["modoChat"] == 1;
                                    $tiempoChat = limpia($_POST["tiempoChat"]);
                                    $limiteChat = limpia($_POST["limiteChat"]);

                                    $llamada = $_POST["activarLlamada"] == 1 ? $_POST["llamada"] : null;

                                    if ($idCampana === "") {

                                        $data = array(
                                            'usuarioAPI' => $_SESSION["user_wa"],
                                            'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])),
                                            "nombre" => $nombre,
                                            "fechaInicio" => $fechaInicio,
                                            "fechaFin" => $fechaFin,
                                            "listaNegra" => $listaNegra,
                                            "grupoTelefonos" => $grupoTelefonos,
                                            "horaInicio" => $horaInicio,
                                            "horaFin" => $horaFin,
                                            "autoRespuesta" => $mensaje === "" ? null : $mensaje,
                                            "mensaje" => $mensaje,
                                            "verAgente" => false,
                                            "modo" => $modoChat,
                                            "tiempo" => $tiempoChat,
                                            "limiteChats" => $limiteChat,
                                            "llamada" => $llamada,
                                            "encuesta" => false,
                                        );

                                        $url = RUTA_WA . "/Campana/add";
                                        $options = array(
                                            'http' => array(
                                                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                                'method' => 'POST',
                                                'content' => http_build_query($data),
                                            ),
                                        );
                                        $context = stream_context_create($options);
                                        $result = file_get_contents($url, false, $context);
                                        $resultados = json_decode($result);
                                        if ($resultados->Estado !== "ok") {
                                            $sal["Estado"] = "error";
                                            $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                                        } else {
                                            $query = "UPDATE vicidial_tables_windows SET idcampaign_wa ='$resultados->idCampana' WHERE campaign_id = '$id'";
                                            sv_mysqli_query($con, $query);
                                            $sal["Estado"] = "ok";
                                        }
                                    } else {
                                        $data = array(
                                            'usuarioAPI' => $_SESSION["user_wa"],
                                            'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])),
                                            "nombre" => $nombre,
                                            "fechaInicio" => $fechaInicio,
                                            "fechaFin" => $fechaFin,
                                            "listaNegra" => $listaNegra,
                                            "grupoTelefonos" => $grupoTelefonos,
                                            "horaInicio" => $horaInicio,
                                            "horaFin" => $horaFin,
                                            "autoRespuesta" => $autoRespuesta,
                                            "mensaje" => $mensaje,
                                            "verAgente" => false,
                                            "modo" => $modoChat,
                                            "tiempo" => $tiempoChat,
                                            "limiteChats" => $limiteChat,
                                            "llamada" => $llamada,
                                            "encuesta" => false,
                                            "id" => $idCampana,
                                        );

                                        $url = RUTA_WA . "/Campana/edit";
                                        $options = array(
                                            'http' => array(
                                                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                                'method' => 'POST',
                                                'content' => http_build_query($data),
                                            ),
                                        );
                                        $context = stream_context_create($options);
                                        $result = file_get_contents($url, false, $context);
                                        $resultados = json_decode($result);
                                        if ($resultados->Estado !== "ok") {
                                            $sal["Estado"] = "error";
                                            $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                                        } else {
                                            $sal["Estado"] = "ok";
                                        }
                                    }
                                } else {
                                    $sal["Estado"] = "ok";
                                }
                            } else {
                                $sal["Estado"] = "ok";
                            }
                        } else {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_carrierInvalido");
                        }
                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditarCampana");
            }
            $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 addCampaign()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $sal = array();
            $con = getConnection();
            $and = "";
            $carrier = limpia($_POST["carrier"]);
            if ($_SESSION["Cliente"] != -1) {
                $and = "AND user_group = '" . $_SESSION["Cliente"] . "'";
            }

            $query = "SELECT carrier_id,carrier_name FROM vicidial_server_carriers WHERE carrier_id = '$carrier' $and LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            $cliente = $_SESSION["Cliente"];
            $esBlaster = false;
            if ($row = sv_mysqli_fetch_array($result)) {
                $nombre = limpia($_POST["nombreCampana"]);
                $descripcion = limpia($_POST["descripcionCampana"]);
                $grupo = "---ALL---";
                if ($cliente != -1) {
                    $grupo = $cliente;
                }

                //ESTADOS QUE SE PIDEN AL USUARIO
                $activa = limpia($_POST["activa"]);
                $web_form_address = limpia($_POST["web_form"]);
                $web_form_address_two = limpia($_POST["web_form_address_two"]);
                $drop_percentage_limit = limpia($_POST["drop_percentage_limit"]);
                $use_auto_hopper = limpia($_POST["use_auto_hopper"]);
                $hopper_level = limpia($_POST["hopper_level"]);
                $lead_order_randomize = limpia($_POST["lead_order_randomize"]);
                $adaptive_dl_diff_target = limpia($_POST["adaptive_dl_diff_target"]);

                $adaptive_intensity = limpia($_POST["adaptive_intensity"]);

                $adaptive_maximum_level = limpia($_POST["adaptive_maximum_level"]);
                $lead_order = limpia($_POST["lead_order"]);
                $auto_dial_level = limpia($_POST["auto_dial_level"]);
                $metodo = limpia($_POST["dial_method"]);
                $tiempo_DEAD = limpia($_POST["DEAD"]);
                $dead_to_dispo = "DISABLED";
                $dead_max = 0;

                if ($tiempo_DEAD != 0) {
                    $dead_to_dispo = "ENABLED";
                    $dead_max = $tiempo_DEAD;
                }
                //ESTADOS DEFAULT
                $dial_timeout = '';
                $alt_number_dialing = '';
                $display_dialable_count = '';
                $drop_call_seconds = '';
                $auto_alt_dial = '';
                $disable_alter_custdata = 'N';
                $auto_dial_level_threshold = "WAITING_AGENTS";
                $am_message_exten = 'vm-goodbye';
                $campaign_allow_inbound = isset($_POST["BLENDED"]) ? limpia($_POST["BLENDED"]) : "N";
                if ($metodo == 'MANUAL' || $metodo == "INBOUND_MAN") {
                    if ($metodo == "INBOUND_MAN") {
                        $campaign_allow_inbound = "Y";
                    } else {
                        $campaign_allow_inbound = "N";
                    }

                    $hopper_level = 1;
                    $auto_dial_level = 0;
                    $dial_timeout = '250';
                    $alt_number_dialing = 'SELECTED'; ////
                    $drop_call_seconds = '5';
                    $display_dialable_count = 'N';
                    $auto_alt_dial = 'ALT_AND_ADDR3';
                    $disable_alter_custdata = 'Y';
                    $auto_dial_level_threshold = "DISABLED";
                } else if ($metodo == "BLASTER") {
                    $hopper_level = 10;
                    $auto_dial_level = 8;
                    $metodo = "RATIO";
                    $clienteCampanaBlaster = ClienteDatos::getClienteById($_SESSION["Cliente"]);
                    $audioCampanaBlaster = AudioDatos::getAudioById($_POST["audio"]);
                    if ($clienteCampanaBlaster->getId() == -1 || $audioCampanaBlaster->getCliente()->getId() == $clienteCampanaBlaster->getId()) {
                        $am_message_exten = $audioCampanaBlaster->getHash();
                        AudioDatos::saveAudio($audioCampanaBlaster);
                    }
                    $esBlaster = true;
                    $dial_timeout = 1;
                } else {
                    $dial_timeout = '75';
                    $alt_number_dialing = 'N';
                    $drop_call_seconds = '10';
                    $display_dialable_count = 'Y';
                    $auto_alt_dial = 'ALT_AND_ADDR3';
                    $disable_alter_custdata = 'N';
                    $auto_dial_level_threshold = "WAITING_AGENTS";
                }
                $manual_dial_override = "ALLOW_ALL";

                $agents_threshold = 4;
                $available_dial_level = 'N';
                $available_only_threshold = 'DISABLED';
                $agents_only = 0;
                $latest_server = 2100;
                $dial_level_target = "ADAPT_CALC_ONLY";
                $concurrent_transfer = "AUTO";
                $auto_alt_dial = 'ALT_AND_ADDR3';
                $drop_rate_group = "DISABLED";
                $inbound_queue = "DISABLED";
                $inbound_no_agents = "DISABLED";
                $inbound_no_agents_no_dial_threshold = 0;
                $agent_pause_codes_active = 'FORCE';
                $campaign_stats_refresh = 'N';
                $manual_dial_search_filter = "CAMPLISTS_ALL";
                $dial_status_a = '';
                $dial_status_b = '';
                $dial_status_c = '';
                $dial_status_d = '';
                $dial_status_e = '';
                $park_ext = '';
                $park_file_name = '';
                $allow_closers = 'Y';
                $next_agent_call = 'longest_wait_time';
                $local_call_time = '24hours';
                $voicemail_ext = '';

                $dial_prefix = $manual_dial_prefix = limpia($_POST["carrier"]);
                $campaign_cid = limpia($_POST["campaign_cid"]);
                $campaign_vdad_exten = '8368';
                $campaign_rec_exten = '8309';
                $campaign_recording = limpia($_POST["campaign_recording"]);
                $campaign_rec_filename = 'OUT_AGENT_CAMPAIGN_FULLDATE_CUSTPHONE_' . $cliente;
                $campaign_script = 'PRUEBA';
                $get_call_launch = 'WEBFORM';
                $amd_send_to_vmx = 'N';
                $xferconf_a_dtmf = '';
                $xferconf_a_number = '';
                $xferconf_b_dtmf = '';
                $xferconf_b_number = '';
                $scheduled_callbacks = 'N';
                $lead_filter_id = 'NONE';

                $drop_action = 'AUDIO';
                $safe_harbor_exten = '8307';

                $wrapup_seconds = '0';
                $wrapup_message = 'Wrapup Call';
                $closer_campaigns = '';
                $use_internal_dnc = 'Y';
                $allcalls_delay = '0';
                $omit_phone_code = 'Y';
                $adaptive_latest_server_time = '2100';
                $disable_alter_custdata = 'N';
                $no_hopper_leads_logins = 'N';
                $list_order_mix = 'DISABLED';

                $default_xfer_group = limpia($_POST["defaul_xfer"]);
                $xfer_groups = '';
                $queue_priority = '50';
                $timer_action_seconds = '1';
                $timer_alt_seconds = '180';
                $agent_xfer_validation = 'Y';
                $inbound_no_agents_no_dial_container = '';
                $web_form_target = "ferp";
                $id = 10;
                $query = "SELECT (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id REGEXP '^[0-9]+$' ORDER BY CAST(campaign_id AS INT) DESC LIMIT 1) AS Campa, (SELECT campaign_id FROM vicidial_lists WHERE campaign_id REGEXP '^[0-9]+$' ORDER BY CAST(campaign_id as INT) DESC LIMIT 1) AS List";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $max_id = max($row["Campa"], $row["List"]);
                    $id = $max_id + 1;
                    if (strlen($id) < 2) {
                        $id = 10;
                    }
                }
                while(true){
                    $query = "SELECT count(*) from vicidial_inbound_groups where group_id='$id'";
                    $result = sv_mysqli_query($con, $query);
                    $row = sv_mysqli_fetch_array($result);
                    if ($row[0] > 0) {
                        $id += 1;
                    }else{
                        break;
                    }
                }
                $query = "SELECT count(*) from vicidial_inbound_groups where group_id='$id'";
                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                if ($row[0] > 0) {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_campanaPrevAgregada");
                } else {
                    if ((strlen($id) < 1) or (strlen($id) > 8) or (strlen($nombre) < 6) or (strlen($nombre) > 40)) {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_nombreInvalido");
                    } else {
                        $hoy = getdate();
                        if ($hoy["mday"] < 10) {
                            $hoy["mday"] = "0" . $hoy["mday"];
                        }

                        if ($hoy["mon"] < 10) {
                            $hoy["mon"] = "0" . $hoy["mon"];
                        }

                        if ($hoy["mday"] < 10) {
                            $hoy["mday"] = "0" . $hoy["mday"];
                        }

                        if ($hoy["hours"] < 10) {
                            $hoy["hours"] = "0" . $hoy["hours"];
                        }

                        if ($hoy["minutes"] < 10) {
                            $hoy["minutes"] = "0" . $hoy["minutes"];
                        }

                        if ($hoy["seconds"] < 10) {
                            $hoy["seconds"] = "0" . $hoy["seconds"];
                        }

                        $list_id = $hoy["year"] . $hoy["mon"] . $hoy["mday"] . $hoy["hours"] . $hoy["minutes"] . $hoy["seconds"];
                        $list_name = "Lista default";
                        $active = "Y";
                        $manual_dial_list_id = "$list_id";
                        $list_description = "Lista default para la campania $nombre";
                        $stmt = "SELECT count(list_id) from vicidial_lists where list_id='$list_id'";
                        $rslt = sv_mysqli_query($con, $stmt);
                        $row = sv_mysqli_fetch_array($rslt);
                        if ($row[0] > 0) {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_listaIdExistente");
                        } else {
                            if ((strlen($list_name) < 2) or ($list_id < 100) or (strlen($list_id) > 19)) {
                                $sal["Estado"] = "error";
                                $sal["Descripcion"] = $this->lang->line("desc_idCampanaIdListaNombreInvalido");
                            } else {
                                $stmt = "INSERT INTO vicidial_lists (list_id,list_name,campaign_id,active,list_description,list_changedate) values('$list_id','$list_name','$id','$active','$list_description',NOW())";
                                $rslt = sv_mysqli_query($con, $stmt);
                                $SQL_log = "$stmt|";
                                $SQL_log = preg_replace('/;/', '', $SQL_log);
                                $SQL_log = addslashes($SQL_log);
                                $ip = $_SERVER["REMOTE_ADDR"];
                                $stmt = "INSERT INTO vicidial_admin_log set event_date=NOW(), user='$usuario', ip_address='$ip', event_section='LISTS', event_type='ADD', record_id='$list_id', event_code='ADMIN ADD LIST', event_sql=\"$SQL_log\", event_notes=''";
                                $rslt = sv_mysqli_query($con, $stmt);
                                $sal["Estado"] = "ok";
                            }
                        }

                        $query = "INSERT INTO vicidial_campaigns (campaign_id,campaign_name,campaign_description,user_group,active,web_form_address,web_form_address_two,adaptive_dropped_percentage,use_auto_hopper,hopper_level,lead_order_randomize,adaptive_dl_diff_target,adaptive_intensity,adaptive_maximum_level,lead_order,campaign_changedate,auto_dial_level,dial_method,dial_level_threshold,dial_level_threshold_agents,available_only_ratio_tally,available_only_tally_threshold,available_only_tally_threshold_agents,adaptive_latest_server_time,dl_diff_target_method,concurrent_transfers,auto_alt_dial,drop_rate_group,inbound_queue_no_dial,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,manual_dial_override,agent_pause_codes_active,campaign_stats_refresh,dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,park_ext,park_file_name,allow_closers,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,disable_alter_custdata,no_hopper_leads_logins,list_order_mix,campaign_allow_inbound,manual_dial_list_id,default_xfer_group,xfer_groups,queue_priority,timer_action_seconds,manual_dial_prefix,timer_alt_seconds,agent_xfer_validation,web_form_target,dead_to_dispo,dead_max,manual_dial_search_filter) values('$id','$nombre','$descripcion','$grupo','$activa','$web_form_address','$web_form_address_two','$drop_percentage_limit','$use_auto_hopper','$hopper_level','$lead_order_randomize','$adaptive_dl_diff_target','$adaptive_intensity','$adaptive_maximum_level','$lead_order',NOW(),'$auto_dial_level','$metodo','$auto_dial_level_threshold','$agents_threshold','$available_dial_level','$available_only_threshold','$agents_only','$latest_server','$dial_level_target','$concurrent_transfer','$auto_alt_dial','$drop_rate_group','$inbound_queue','$inbound_no_agents','$inbound_no_agents_no_dial_threshold','$manual_dial_override','$agent_pause_codes_active','$campaign_stats_refresh','$dial_status_a','$dial_status_b','$dial_status_c','$dial_status_d','$dial_status_e','$park_ext','$park_file_name','$allow_closers','$next_agent_call','$local_call_time','$voicemail_ext','$dial_timeout','$dial_prefix','$campaign_cid','$campaign_vdad_exten','$campaign_rec_exten','$campaign_recording','$campaign_rec_filename','$campaign_script','$get_call_launch','$am_message_exten','$amd_send_to_vmx','$xferconf_a_dtmf','$xferconf_a_number','$xferconf_b_dtmf','$xferconf_b_number','$scheduled_callbacks','$lead_filter_id','$drop_call_seconds','$drop_action','$safe_harbor_exten','$display_dialable_count','$wrapup_seconds','$wrapup_message','$closer_campaigns','$use_internal_dnc','$allcalls_delay','$omit_phone_code','$disable_alter_custdata','$no_hopper_leads_logins','$list_order_mix','$campaign_allow_inbound','$manual_dial_list_id','$default_xfer_group','$xfer_groups','$queue_priority','$timer_action_seconds','$manual_dial_prefix','$timer_alt_seconds','$agent_xfer_validation','$web_form_target','$dead_to_dispo','$dead_max','$manual_dial_search_filter')";
                        sv_mysqli_query($con, $query);
                        $sal["ASD"] = $query;
                        $sal["ERRRR"] = mysqli_error($con);
                        $stmtA = "INSERT INTO vicidial_campaign_stats (campaign_id) values('$id');";
                        $rslt = sv_mysqli_query($con, $stmtA);
                        $stmtA = "INSERT INTO vicidial_campaign_stats_debug (campaign_id) values('$id');";
                        $rslt = sv_mysqli_query($con, $stmtA);
                        sv_mysqli_query($con, "INSERT INTO vicidial_campaign_statuses (campaign_id,status,status_name,selectable,human_answered,category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,answering_machine) VALUES ('$id','NOCAL','" . $this->lang->line("NOCAL_desc") . "','Y','N','','N','N','N','N','N','N','N','N')");
                        if ($esBlaster) {
                            //Falta verificar el numero de lineas disponibles
                            $query = "SELECT user FROM vicidial_users WHERE user REGEXP '^[0-9]+$' ORDER BY user DESC LIMIT 1";
                            $result = sv_mysqli_query($con, $query);
                            $idAgenteRemoto = 101;
                            if ($row = sv_mysqli_fetch_array($result)) {
                                $idAgenteRemoto = $row["user"] + 1;
                            }
                            $url = URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . USER_API . "&pass=" . PASS_API . "&function=add_user&agent_user=" . $idAgenteRemoto . "&agent_pass=" . urlencode("testPassword") . "&agent_user_level=2&agent_full_name=" . $idAgenteRemoto . "&agent_user_group=" . urlencode($_SESSION["Cliente"] . "_" . GRUPO_AGENTES) . "&phone_login=test&phone_pass=test";
                            file_get_contents($url);
                            $sal["url"] = $url;
                            $remoteAgent = new RemoteAgent(null, $idAgenteRemoto, $id, $_POST["lineas"], "ACTIVE", "666" . $id);
                            $sal["queyr"] = RemoteAgentDatos::addRemoteAgent($remoteAgent);
                        }

                        $tiempoDispo = 30;
                        $allow_beep = 0;
                        $time_beep = 0;
                        $time_repeat = 0;
                        $windows_check = 0;
                        if (limpia($_POST["ventanas"]) == 1) {
                            $windows_check = 1;
                        }
                        if (limpia($_POST["allow_beep"]) == 1) {
                            $allow_beep = 1;
                            $time_beep = intval(limpia($_POST["time_beep"]));
                            $time_repeat = intval(limpia($_POST["time_repeat"]));
                        }
                        $query = "INSERT INTO vicidial_tables_windows(campaign_id,windows_check,max_time_dispo,allow_beep,time_beep,time_repeat,allow_wa) VALUES('$id','$windows_check','$tiempoDispo','$allow_beep','$time_beep','$time_repeat','0')";
                        $allow_wa = limpia(isset($_POST["allow_wa"]) ? $_POST["allow_wa"] : "0");
                        if (NEED_WA && $_SESSION['allow_waCli'] && $allow_wa == 1) {

                            if ($allow_wa) {
                                $cliente = $_SESSION["idclient_wa"];
                                $idCampana = limpia($_POST["idCampanaWA"]);
                                $grupoTelefonos = limpia($_POST["grupoTelefono"]);
                                $fechaInicio = limpia($_POST["fechaInicio"]);
                                $fechaFin = limpia($_POST["fechaFin"]);
                                $horaInicio = limpia($_POST["horaInicio"]);
                                $horaFin = limpia($_POST["horaFin"]);
                                $autoRespuesta = limpia($_POST["autoRespuesta"]);
                                $mensaje = limpia($_POST["mensaje"]);
                                $nombre = limpia($_POST["nombre"]);
                                $listaNegra = limpia($_POST["listaNegra"]);

                                $encuesta = false;
                                $modoChat = $_POST["modoChat"] == 1;
                                $tiempoChat = limpia($_POST["tiempoChat"]);
                                $limiteChat = limpia($_POST["limiteChat"]);
                                $llamada = $_POST["activarLlamada"] == 1 ? $_POST["llamada"] : null;
                                $data = array(
                                    'usuarioAPI' => $_SESSION["user_wa"],
                                    'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])),
                                    "nombre" => $nombre,
                                    "fechaInicio" => $fechaInicio,
                                    "fechaFin" => $fechaFin,
                                    "listaNegra" => $listaNegra,
                                    "grupoTelefonos" => $grupoTelefonos,
                                    "horaInicio" => $horaInicio,
                                    "horaFin" => $horaFin,
                                    "autoRespuesta" => $mensaje === "" ? null : $mensaje,
                                    "mensaje" => $mensaje,
                                    "verAgente" => false,
                                    "encuesta" => $encuesta,
                                    "modo" => $modoChat,
                                    "tiempo" => $tiempoChat,
                                    "limiteChats" => $limiteChat,
                                    "llamada" => $llamada,
                                );
                                $url = RUTA_WA . "/Campana/add";
                                $options = array(
                                    'http' => array(
                                        'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                        'method' => 'POST',
                                        'content' => http_build_query($data),
                                    ),
                                );
                                $context = stream_context_create($options);
                                $result = file_get_contents($url, false, $context);
                                $resultados = json_decode($result);
                                if ($resultados->Estado !== "ok") {
                                    $sal["Estado"] = "error";
                                    $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                                    $this->output->set_output(json_encode($sal));
                                    sv_mysqli_close($con);
                                    return;
                                } else {
                                    $query = "INSERT INTO vicidial_tables_windows(campaign_id,windows_check,max_time_dispo,allow_beep,time_beep,time_repeat,allow_wa,idcampaign_wa) VALUES('$id','$windows_check','$tiempoDispo','$allow_beep','$time_beep','$time_repeat','$allow_wa','$resultados->idCampana')";
                                }
                            }
                        }
                        if (limpia($_POST["tiempoDispo"]) > 0) {
                            $tiempoDispo = limpia($_POST["tiempoDispo"]);
                        }

                        sv_mysqli_query($con, $query);
                        $sal["Estado"] = "ok";
                        $sal["idCampana"] = $id;

                        // ? RESOLVES: Autopausa
                        if (isset($_POST["isAutopausa"])) {
                            $campana = $id;
                            $codigoPausa = "DAUTO";
                            $tono = $_POST["autoPausaTono"];
                            $volumen = $_POST["autoPausaVolumen"];
                            $metodo = $_POST["autoPausaMetodo"];
                            $tiempo = $_POST["autoPausaTiempo"];

                            $query_autopausa = "INSERT INTO dialvox_campana_autopausa(Campana,CodigoPausa,Tono,Volumen,MetodoDistribucion,TiempoTimbrado) VALUES ('$campana','$codigoPausa','$tono','$volumen','$metodo','$tiempo')";
                            sv_mysqli_query($con, $query_autopausa);
                        }
                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_carrierInvalido");
            }
            $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 getCampaigns()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $registros = 10;
            $pagina = $_POST["pagina"] - 1;
            $skip = $registros * $pagina;
            $cliente = $_SESSION["Cliente"];
            $xD = "user_group = '$cliente' AND ";
            if ($cliente == -1) {
                $xD = "";
            }
            $textoBusqueda = "";
            if (isset($_POST["texto"])) {
                $textoBusqueda = limpia($_POST["texto"]);
            }
            $query = "SELECT campaign_id,campaign_name,active,user_group,dial_method,auto_dial_level,lead_order,campaign_allow_inbound FROM vicidial_campaigns WHERE $xD (campaign_name LIKE '%$textoBusqueda%' OR campaign_id LIKE '%$textoBusqueda%') ORDER BY campaign_name ASC LIMIT $skip,$registros";
            $result = sv_mysqli_query($con, $query);
            $sal["Campanas"] = array();
            $donde = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Campanas"][$donde]["id"] = $row["campaign_id"];
                $sal["Campanas"][$donde]["nombre"] = $row["campaign_name"];
                $sal["Campanas"][$donde]["activo"] = $row["active"];
                $sal["Campanas"][$donde]["grupo"] = $row["user_group"];
                $sal["Campanas"][$donde]["metodo"] = $row["dial_method"];
                $sal["Campanas"][$donde]["nivel"] = $row["auto_dial_level"];
                $sal["Campanas"][$donde]["orden"] = $row["lead_order"];
                $sal["Campanas"][$donde]["campaign_allow_inbound"] = $row["campaign_allow_inbound"];
                $query = "SELECT allow_wa,idcampaign_wa FROM vicidial_tables_windows WHERE campaign_id='{$row["campaign_id"]}'";
                if (NEED_WA && $_SESSION['allow_waCli']) {
                    $result2 = sv_mysqli_query($con, $query);
                    if ($ras = sv_mysqli_fetch_array($result2)) {
                        $sal["Campanas"][$donde]["haveWA"] = $ras["allow_wa"];
                        $sal["Campanas"][$donde]["idWA"] = $ras["idcampaign_wa"];
                    }
                }

                // ? RESOLVES: Autopausa
                $campana_autopausa = $row["campaign_id"];
                $query_autopausa = "SELECT CodigoPausa FROM dialvox_campana_autopausa WHERE Campana='$campana_autopausa' LIMIT 1";
                $result_autopausa = sv_mysqli_query($con, $query_autopausa);

                $sal["Campanas"][$donde]["tieneAutopausa"] = false;
                if ($result_autopausa) {
                    $row_autopausa = sv_mysqli_fetch_array($result_autopausa);

                    if ($row_autopausa) {
                        $sal["Campanas"][$donde]["tieneAutopausa"] = true;
                    }
                }

                $donde++;
            }
            $sal["Estado"] = "ok";
            $query = "SELECT COUNT(campaign_id) FROM vicidial_campaigns WHERE $xD (campaign_name LIKE '%$textoBusqueda%' OR campaign_id LIKE '%$textoBusqueda%')";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $sal["Cuenta"] = $row[0];
            sv_mysqli_close($con);
            $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 getBlackList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $campana = $_POST["campana"];
            $query = "SELECT idblacklist FROM vicidial_tables_windows WHERE campaign_id = '$campana'";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            if ($row[0] == null) {
                $sal["idLista"] = -1;
            } else {
                $sal["idLista"] = $row[0];
            }

            $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_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getCampaignsSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $and = "";
            if ($_SESSION["Cliente"] != -1) {
                $and = "WHERE user_group = '" . $_SESSION["Cliente"] . "'";
            }
            $query = "SELECT campaign_id,campaign_name FROM vicidial_campaigns $and";
            $result = sv_mysqli_query($con, $query);
            $sal["Estado"] = "ok";
            $sal["Campanas"] = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Campanas"][] = $row;
            }
            sv_mysqli_close($con);
            $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 getInboundGroups()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $query = "SELECT group_id,group_name FROM vicidial_inbound_groups ORDER BY group_id";
            $result = sv_mysqli_query($con, $query);
            $sal["Grupos"] = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Grupos"][] = $row;
            }
            sv_mysqli_close($con);
            $sal["Estado"] = "ok";
            $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 getCampaignDetails()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false || strpos($_SESSION["Grupo"], GRUPO_SUPERVISORES) !== false)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $campana = $_POST["campana"];
            $and = "";
            if ($_SESSION["Cliente"] != -1) {
                $and = "AND user_group = '" . $_SESSION["Cliente"] . "'";
            }
            $query = "SELECT * FROM vicidial_campaigns WHERE campaign_id = '$campana' $and LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $sal["Campana"] = $row;
                $am_message_exten = $row["am_message_exten"];
                $sal["Estado"] = "ok";
                $query = "SELECT status,status_name FROM vicidial_statuses WHERE selectable = 'Y' UNION SELECT status,status_name FROM vicidial_campaign_statuses WHERE selectable = 'Y' AND campaign_id = '$campana'";
                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                $sal["Status"] = $row;
                $query = "SELECT windows_check,idcampaign_wa, max_time_dispo,allow_beep,time_beep,time_repeat,allow_wa FROM vicidial_tables_windows WHERE campaign_id = '$campana'";
                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                $sal["pestana"] = $row["windows_check"];
                $sal["tiempoDispo"] = $row["max_time_dispo"];
                $sal["allow_beep"] = $row["allow_beep"];
                $sal["time_beep"] = $row["time_beep"];
                $sal["time_repeat"] = $row["time_repeat"];
                $query = "SELECT number_of_lines FROM vicidial_remote_agents WHERE campaign_id = '" . $campana . "' LIMIT 1";
                if ($resultLineas = sv_mysqli_query($con, $query)) {
                    if ($rowLineas = sv_mysqli_fetch_array($resultLineas)) {
                        $sal["lineas"] = $rowLineas["number_of_lines"];
                        $sal["audio"] = AudioDatos::getAudioByHash($am_message_exten);
                        if ($sal["audio"] != null) {
                            $sal["audio"] = $sal["audio"]->toJSON();
                        }
                    }
                }
                if (NEED_WA && $_SESSION["allow_waCli"]) {
                    $sal["allow_wa"] = $row["allow_wa"];
                    if ($row["idcampaign_wa"] !== "") {
                        $url = RUTA_WA . "/Campana/getOne";
                        $data = array('usuarioAPI' => $_SESSION["user_wa"], 'passwordAPI' => base64_encode(base64_encode($_SESSION["pass_wa"])), "id" => $row["idcampaign_wa"]);
                        $options = array(
                            'http' => array(
                                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                                'method' => 'POST',
                                'content' => http_build_query($data),
                            ),
                        );
                        $context = stream_context_create($options);
                        $result = file_get_contents($url, false, $context);
                        $resultados = json_decode($result);
                        if ($resultados->Estado === "ok") {
                            $sal["WA"] = $resultados->Campana;
                            $sal["MensajeWAM"] = $resultados->Mensaje;
                        } else {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $resultados->Descripcion . "<br>" . $resultados->CodigoError;
                        }
                    }
                }

                // ? RESOLVES: Autopausa
                $campana_autopausa = $campana;
                $query_autopausa = "SELECT CodigoPausa,Tono,Volumen,MetodoDistribucion,TiempoTimbrado FROM dialvox_campana_autopausa WHERE Campana='$campana_autopausa' LIMIT 1";
                $result_autopausa = sv_mysqli_query($con, $query_autopausa);

                if ($result_autopausa) {
                    $row_autopausa = sv_mysqli_fetch_array($result_autopausa);

                    if ($row_autopausa) {
                        $sal["Autopausa"] = array(
                            "tono" => $row_autopausa["Tono"],
                            "volumen" => $row_autopausa["Volumen"],
                            "metodo" => $row_autopausa["MetodoDistribucion"],
                            "tiempo" => $row_autopausa["TiempoTimbrado"]
                        );
                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_campanaInvalida");
            }
            sv_mysqli_close($con);
            $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 changeCampaignStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $and = "";
            $id = limpia($_POST["idCampana"]);
            if ($_SESSION["Cliente"] != -1) {
                $and = "AND user_group = '" . $_SESSION["Cliente"] . "'";
            }
            $query = "SELECT campaign_id from vicidial_campaigns WHERE campaign_id = '$id' $and limit 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $result = sv_mysqli_query($con, "SELECT active FROM vicidial_campaigns WHERE campaign_id = '$id' LIMIT 1");
                $row = sv_mysqli_fetch_array($result);
                $nuevo = 'Y';
                if ($row[0] == 'Y') {
                    $nuevo = 'N';
                }
                sv_mysqli_query($con, "UPDATE vicidial_campaigns SET active = '$nuevo' WHERE campaign_id = '$id' LIMIT 1");
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditarCampana");
            }
            $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 agregarCampana()
    {
        $this->load->view('campanas/head');
        $this->load->view('campanas/vw_agregar');
        $this->load->view('campanas/foot');
    }
    public function index()
    {
        $this->load->view('campanas/head');
        $this->load->view('campanas/vw_campanas');
        $this->load->view('campanas/foot');
    }
    public function estadosCalificacion()
    {
        $this->load->view('estadosCalificacion/head');
        $this->load->view('estadosCalificacion/vw_estadosCalificacion');
        $this->load->view('estadosCalificacion/foot');
    }

    /*

    Metodos para administrar los frame extreas de un agente.

     */
    // =================================================================

    public function agregarFrame()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        header('Content-type: application/json');
        $res = array();
        if (!empty($_SESSION["Usuario"])) {
            $cliente = ClienteDatos::getClienteById($_SESSION["Cliente"]);

            $frame_res = FrameAgenteDatos::insertAgentFrame(new FrameAgente(
                $_POST["url"],
                $_POST["campana"],
                $_POST["titulo"],
                $cliente,
                "",
                $_POST["estatico"]
            ));

            if (isset($frame_res["result"])) {
                $res = array(
                    "Estado" => "ok",
                    "Id" => $frame_res["id"],
                );
            } else {
                $res = array(
                    "Estado" => "Error",
                    "Descripcion" => $this->lang->line($frame_res["error"]),
                );
            }
        } else {
            $res = array(
                "Estado" => "Error",
                "Descripcion" => $this->lang->line("desc_sinSesionActiva"),
            );
        }
        $this->output->set_output(json_encode($res));
    }

    public function editarFrame()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        header('Content-type: application/json');
        $res = array();
        if (!empty($_SESSION["Usuario"])) {
            $cliente = ClienteDatos::getClienteById($_SESSION["Cliente"]);
            $frame_res = FrameAgenteDatos::getById($_POST["id"]);
            if (isset($frame_res["result"])) {
                $agentFrame = $frame_res["result"];
                $agentFrame->setURL($_POST["url"]);
                $agentFrame->setTitulo($_POST["titulo"]);
                $agentFrame->setEstatico($_POST["estatico"]);
                $frame_res = FrameAgenteDatos::updateAgentFrame($agentFrame, $cliente);
                if (isset($frame_res["result"])) {
                    $res = array(
                        "Estado" => "ok",
                    );
                } else {
                    $res = array(
                        "Estado" => "Error",
                        "Descripcion" => $this->lang->line($frame_res["error"]),
                    );
                }
            } else {
                $res = array(
                    "Estado" => "Error",
                    "Descripcion" => $this->lang->line($frame_res["error"]),
                );
            }
        } else {
            $res = array(
                "Estado" => "Error",
                "Descripcion" => $this->lang->line("desc_sinSesionActiva"),
            );
        }
        $this->output->set_output(json_encode($res));
    }

    public function borrarFrame()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        header('Content-type: application/json');
        $res = array();
        if (!empty($_SESSION["Usuario"])) {
            $cliente = ClienteDatos::getClienteById($_SESSION["Cliente"]);
            $frame_res = FrameAgenteDatos::deleteAgentFrame($cliente, $_POST["id"]);
            if (isset($frame_res["result"])) {
                $res = array(
                    "Estado" => "ok",
                );
            } else {
                $res = array(
                    "Estado" => "Error",
                    "Descripcion" => $this->lang->line($frame_res["error"]),
                );
            }
        } else {
            $res = array(
                "Estado" => "Error",
                "Descripcion" => $this->lang->line("desc_sinSesionActiva"),
            );
        }
        $this->output->set_output(json_encode($res));
    }

    public function listarFrames()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanas', "spanish");
                break;
            case "en":
                $this->lang->load('campanas', "english");
                break;
            default:
                $this->lang->load('campanas', "spanish");
                break;
        }
        header('Content-type: application/json');
        $res = array();
        if (!empty($_SESSION["Usuario"])) {
            $cliente = ClienteDatos::getClienteById($_SESSION["Cliente"]);
            $frame_res = FrameAgenteDatos::getFramesByCampaign($_POST["campana"], $cliente->getId());
            if (isset($frame_res["result"])) {
                $framesRaw = $frame_res["result"];
                $framesJSON = array();
                foreach ($framesRaw as $i => $value) {
                    array_push($framesJSON, $value->toJSON());
                }
                $res = array(
                    "Estado" => "ok",
                    "Frames" => $framesJSON,
                );
            } else {
                $res = array(
                    "Estado" => "Error",
                    "Descripcion" => $this->lang->line($frame_res["error"]),
                );
            }
        } else {
            $res = array(
                "Estado" => "Error",
                "Descripcion" => $this->lang->line("desc_sinSesionActiva"),
            );
        }
        $this->output->set_output(json_encode($res));
    }
}
