<?php

require_once "BASEPATH.php";

require_once 'Clases/ClienteDatos.php';
require_once 'Clases/FrameAgenteDatos.php';

require_once 'Clases/ListaDatos.php';
require_once 'Clases/CRM/CampoDatos.php';
require_once 'Clases/CRM/GestionDatos.php';
require_once 'Clases/CRM/RespuestaDatos.php';

class HomeAgente extends MY_Controller
{
    public function setPauseStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $pausa = $_POST["codigo"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=pause_code&value=" . $pausa;
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getDispoSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $con = getConnection();
            $query = "SELECT status,status_name,scheduled_callback FROM vicidial_statuses WHERE selectable = 'Y' UNION SELECT status,status_name,scheduled_callback FROM vicidial_campaign_statuses WHERE selectable = 'Y' AND campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = sv_mysqli_query($con, $query);
            $sal = array();
            $sal["Registros"] = array();
            $cuenta = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Registros"][] = $row;
            }
            $query = "SELECT local_call_time FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $sal["Horario"] = $row["local_call_time"];
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        }
    }
    public function commentLead()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $con = getConnection();
            $query = "UPDATE vicidial_list SET comments='" . limpia($_POST["comment"]) . "' WHERE lead_id = '" . limpia($_POST["lead_id"]) . "' ";
            $result = sv_mysqli_query($con, $query);
            $sal = array();
            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        }
    }
    public function checkBlackList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $con = getConnection();
            $campana = limpia($_POST["campana"]);
            $telefono = limpia($_POST["numero"]);
            $calificacion = limpia($_POST["calificacion"]);
            $vendor_lead_code = limpia($_POST["vendor_lead_code"]);
            $result = sv_mysqli_query($con, "SELECT blackPhone,blackLead FROM dialvox_campaign_statuses where campaign_id='$campana' AND status='$calificacion' LIMIT 1");
            $sal = array();
            if ($row = sv_mysqli_fetch_array($result)) {
                $blackPhone = $row["blackPhone"];
                $blackLead = $row["blackLead"];
                if ($blackPhone) {
                    $result = sv_mysqli_query($con, "SELECT idblacklist FROM vicidial_tables_windows WHERE campaign_id='$campana' LIMIT 1");
                    if ($row = sv_mysqli_fetch_array($result)) {
                        $listaNegra = $row["idblacklist"];
                        if ($listaNegra == null) {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_campanaSinListaNegra");
                            $this->output->set_output(json_encode($sal));
                            sv_mysqli_close($con);
                            return;
                        } else {
                            sv_mysqli_query($con, "INSERT INTO blacklisted_numbers(idblacklist,number) VALUES('$listaNegra','$telefono')");
                            $result = sv_mysqli_query($con, "SELECT campaign_id FROM vicidial_tables_windows where idblacklist='$listaNegra'");
                            $cambios = array();
                            while ($row = sv_mysqli_fetch_array($result)) {
                                $result2 = sv_mysqli_query($con, "SELECT dial_statuses FROM vicidial_campaigns WHERE campaign_id = {$row["campaign_id"]}");
                                while ($row2 = sv_mysqli_fetch_array($result2)) {
                                    $statusDial = trim(substr($row2["dial_statuses"], 0, -1));
                                    $result3 = sv_mysqli_query($con, "SELECT list_id FROM vicidial_lists WHERE campaign_id = {$row["campaign_id"]}");
                                    while ($row3 = sv_mysqli_fetch_array($result3)) {
                                        $cambios[] = array("statuses" => $statusDial, "list_id" => $row3["list_id"]);
                                    }
                                }
                            }
                            foreach ($cambios as $cambio) {
                                $statusArray = explode(" ", $cambio["statuses"]);
                                foreach ($statusArray as $status) {
                                    foreach ($phone_numbers as $numero) {
                                        sv_mysqli_query($con, "UPDATE vicidial_list SET status='DNC' WHERE list_id='{$cambio["list_id"]}' AND status='$status' AND phone_number='$telefono'");
                                    }
                                }
                            }
                        }
                    } else {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_noSe");
                        $this->output->set_output(json_encode($sal));
                        sv_mysqli_close($con);
                        return;
                    }
                }
                if ($blackLead) {
                    $result = sv_mysqli_query($con, "SELECT idblacklist FROM vicidial_tables_windows WHERE campaign_id='$campana' LIMIT 1");
                    if ($row = sv_mysqli_fetch_array($result)) {
                        $listaNegra = $row["idblacklist"];
                        if ($listaNegra == null) {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_campanaSinListaNegra");

                            $this->output->set_output(json_encode($sal));
                            sv_mysqli_close($con);
                            return;
                        } else {
                            sv_mysqli_query($con, "INSERT INTO blacklisted_lead_code(idblacklist,vendor_lead_code) VALUES('$listaNegra','$vendor_lead_code')");
                            $result = sv_mysqli_query($con, "SELECT campaign_id FROM vicidial_tables_windows where idblacklist='$listaNegra'");
                            $cambios = array();
                            while ($row = sv_mysqli_fetch_array($result)) {
                                $result2 = sv_mysqli_query($con, "SELECT dial_statuses FROM vicidial_campaigns WHERE campaign_id = {$row["campaign_id"]}");
                                while ($row2 = sv_mysqli_fetch_array($result2)) {
                                    $statusDial = trim(substr($row2["dial_statuses"], 0, -1));
                                    $result3 = sv_mysqli_query($con, "SELECT list_id FROM vicidial_lists WHERE campaign_id = {$row["campaign_id"]}");
                                    while ($row3 = sv_mysqli_fetch_array($result3)) {
                                        $cambios[] = array("statuses" => $statusDial, "list_id" => $row3["list_id"]);
                                    }
                                }
                            }
                            foreach ($cambios as $cambio) {
                                $statusArray = explode(" ", $cambio["statuses"]);
                                foreach ($statusArray as $status) {
                                    foreach ($phone_numbers as $numero) {
                                        sv_mysqli_query($con, "UPDATE vicidial_list SET status='DNC' WHERE list_id='{$cambio["list_id"]}' AND status='$status' AND vendor_lead_code='$vendor_lead_code'");
                                    }
                                }
                            }
                        }
                    } else {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_noSe");
                        $this->output->set_output(json_encode($sal));
                        sv_mysqli_close($con);
                        return;
                    }
                }
            } else {
                $sal["Estado"] = "ok";
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        }
    }

    // ================================================
    // Metodos para generar las ventanas del agente
    public function getFrames()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $con = getConnection();
            $vicidialStatus = file_get_contents(URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status");
            $vicidialStatus = explode("|", $vicidialStatus);
            $vicidialStatusHeaders = ["status", "call_id", "lead_id", "campaign_id", "calls_today", "full_name", "user_group", "user_level", "pause_code", "real_time_sub_status", "phone_number", "vendor_lead_code", "session_id"];
            $vicidialAssocStatus = array();

            for ($i = 0; $i < count($vicidialStatusHeaders); $i++) {
                if (isset($vicidialStatus[$i])) {
                    $vicidialAssocStatus[$vicidialStatusHeaders[$i]] = $vicidialStatus[$i];
                } else {
                    $vicidialAssocStatus[$vicidialStatusHeaders[$i]] = "";
                }
            }

            $leadId = isset($vicidialStatus[2]) ? $vicidialStatus[2] : -1;
            $campaignId = isset($vicidialStatus[3]) ? $vicidialStatus[3] : '-1';
            $res = array(
                "webForm" => true,
                "webFormTwo" => true,
            );
            $query = "SELECT * FROM vicidial_list WHERE lead_id = '" . $leadId . "' LIMIT 1";
            $query_result = sv_mysqli_query($con, $query);

            $row = array();
            if ($row1 = sv_mysqli_fetch_array($query_result)) {
                $row = $row1;
                $row["phone_number"] = $vicidialAssocStatus["phone_number"];
                $row["call_id"] = $vicidialAssocStatus["call_id"];
                $row["lead_id"] = $vicidialAssocStatus["lead_id"];
                $fechaLeadId = date("Y-m-d");
                $timeLeadId = date("H:i");
                $row["lead_id_date"] = $fechaLeadId;
                $row["lead_id_time"] = $timeLeadId;
                $row["lead_id_timestamp"] = $vicidialAssocStatus["lead_id"]
                    . str_replace("-", "", $fechaLeadId)
                    . str_replace(":", "", $timeLeadId);

                $lista = ListaDatos::getListaByLeadId($row["lead_id"]);
                $crm = null;
                if ($lista != null) {
                    $crm = $lista->getCRM();
                }

                if ($crm != null) {
                    $gestion = GestionDatos::getLastestGestionByCRMAndLead($crm, $row["lead_id"]);
                    if ($gestion != null) {
                        $respuestas = RespuestaDatos::getRespuestasByGestion($gestion);
                        for ($i = 0; $i < count($respuestas); $i++) {
                            $respuesta = $respuestas[$i];
                            $campo = $respuesta->getCampo();
                            $row[$campo->getNombre() . "_" . $campo->getId()] = $respuesta->getRespuesta();
                        }
                    }
                }
            } else {
                $row = array();
            }

            $query_ingroup = "SELECT campaign_id FROM vicidial_closer_log WHERE lead_id ='" . $leadId . "' ORDER BY closecallid DESC LIMIT 1";

            $query_ingroup_result = sv_mysqli_query($con, $query_ingroup);

            $row["ingroup_id"] = "none";
            if ($row2 = sv_mysqli_fetch_array($query_ingroup_result)) {
                $row["ingroup_id"] = $row2["campaign_id"];
            }

            $queryInbounds = "SELECT comments FROM vicidial_live_agents WHERE user='$usuario'";
            // "SELECT web_form_address FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'"
            // "SELECT web_form_address_two FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'"
            $queryWebForms = "SELECT web_form_address,web_form_address_two FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'";
            $query_result_inbounds = sv_mysqli_query($con, $queryInbounds);
            $query_result_webforms = sv_mysqli_query($con, $queryWebForms);

            if ($rowInbounds = sv_mysqli_fetch_array($query_result_inbounds)) {
                $typeCall = $rowInbounds["comments"];
                if ($typeCall === "INBOUND") {
                    $typeCall = "Inbound";
                } else {
                    $typeCall = "Outbound";
                    $row["ingroup_id"] = $campaignId;
                }
                $row["dialvox_call_type"] = $typeCall;
            }
            if ($rowWebForms = sv_mysqli_fetch_array($query_result_webforms)) {
                $res["webForm"] = $rowWebForms["web_form_address"] != "";
                $res["webFormTwo"] = $rowWebForms["web_form_address_two"] != "";
            }
            $agentFrames = FrameAgenteDatos::getFramesByCampaign(
                $_SESSION["Campana"],
                $_SESSION["Cliente"]
            );
            if (isset($agentFrames["result"])) {
                $rawFrames = $agentFrames["result"];
                $jsonFrames = array();
                foreach ($rawFrames as $key => $value) {
                    array_push(
                        $jsonFrames,
                        $value->produceURL($row)->toJSON()
                    );
                }
                $res["Frames"] = $jsonFrames;
            } else {
                $res = $agentFrames;
            }

            $res["INFO"] = $row;

            sv_mysqli_close($con);
            $this->output->set_output(json_encode($res));
        } else {
            $res = array(
                "Estado" => "error",
                "Descripcion" => $this->lang->line("desc_sinSesion"),
            );
            $this->output->set_output(json_encode($res));
        }
    }
    // ================================================

    public function getUrl()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $con = getConnection();
            $query = "SELECT web_form_address FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = sv_mysqli_query($con, $query);
            $url = "";
            if ($row = sv_mysqli_fetch_array($result)) {
                $url = $row["web_form_address"];
            }

            $strA = "--A--";
            $strB = "--B--";
            $sal = array();
            $x = file_get_contents(URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status");
            $array = ["status", "call_id", "lead_id", "campaign_id", "calls_today", "full_name", "user_group", "user_level", "pause_code", "real_time_sub_status", "phone_number", "vendor_lead_code", "session_id"];
            $actual = array();
            for ($i = 0; $i < sizeof($array); $i++) {
                $actual[$i] = "";
            }

            array_push($array, "lead_id_timestamp", "lead_id_time", "lead_id_date");

            $j = 0;
            $urlNueva = "";
            $index = 0;
            if (substr($url, 0, 3) == "VAR") {
                $sal["esVariable"] = true;
                $index = 3;
            } else {
                $sal["esVariable"] = false;
                $urlNueva = $url;
            }
            for ($i = 0; $i < strlen($x); $i++) {
                $a = $x[$i];
                if ($a == "|") {
                    $j++;
                } else {
                    $actual[$j] .= $a;
                }
            }

            $fechaLeadId = date("Y-m-d");
            $timeLeadId = date("h:i");

            array_push(
                $actual,
                $actual[2]
                    . str_replace("-", "", $fechaLeadId)
                    . str_replace(":", "", $timeLeadId)
            );
            array_push($actual, $timeLeadId);
            array_push($actual, $fechaLeadId);

            $query = "SELECT * FROM vicidial_list WHERE lead_id = '" . $actual[2] . "' LIMIT 1";
            $result = sv_mysqli_query($con, $query, MYSQLI_ASSOC);
            if ($row = sv_mysqli_fetch_array($result)) {
                $array = array_values($array);
                $claves = array_keys($row);
                $claves = array_values($claves);
                $ts = array_merge($array, $claves);
                $array = $ts;
                $actual = array_values($actual);
                $row = array_values($row);
                $ts2 = array_merge($actual, $row);
                $actual = $ts2;
            }
            for ($i = 0; $i < count($array); $i++) {
                if (!is_null($actual[$i])) {
                    $actual[$i] = str_replace("\n", "", $actual[$i] ?? "");
                } else {
                    $actual[$i] = "";
                }
            }
            $urlNueva = substr($url, 3);
            if ($sal["esVariable"]) {
                for ($i = 0; $i < count($array); $i++) {
                    $strxD = "--A--" . $array[$i] . "--B--";
                    if (!is_null($actual[$i]))
                        $urlNueva = str_replace($strxD, $actual[$i], $urlNueva);
                }
            }
            //echo($actual[array_search("campaign_id",$array)]);
            /*while ($index < strlen($url) && $index > 1) {
            if (substr($url, $index, strlen($strA)) == $strA) {
            $index += strlen($strA);
            $vara = "";
            while (substr($url, $index, strlen($strB)) != $strB) {
            $vara .= $url[$index];
            $index += 1;
            }
            $urlNueva .= $actual[array_search($vara, $array)];
            $index += strlen($strB);
            } else {
            $urlNueva .= $url[$index];
            $index += 1;
            }
            }*/
            $sal["Estado"] = "ok";
            $sal["url"] = $urlNueva;
            $this->output->set_output(json_encode($sal));
        }
    }
    public function espera()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $val = $_POST["Val"];
            if ($val == 1) {
                $val = "PARK_CUSTOMER";
            } else {
                $val = "GRAB_CUSTOMER";
            }
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=park_call&value=$val";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getUrl2()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $con = getConnection();
            $query = "SELECT web_form_address_two FROM vicidial_campaigns WHERE campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = sv_mysqli_query($con, $query);
            $url = "";
            if ($row = sv_mysqli_fetch_array($result)) {
                $url = $row["web_form_address_two"];
            }

            $strA = "--A--";
            $strB = "--B--";
            $x = file_get_contents(URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status");

            $array = ["status", "call_id", "lead_id", "campaign_id", "calls_today", "full_name", "user_group", "user_level", "pause_code", "real_time_sub_status", "phone_number", "vendor_lead_code", "session_id"];
            $actual = array();
            for ($i = 0; $i < sizeof($array); $i++) {
                $actual[$i] = "";
            }

            array_push($array, "lead_id_timestamp", "lead_id_time", "lead_id_date");

            $j = 0;
            $urlNueva = "";
            $index = 0;
            $sal = array();
            if (substr($url, 0, 3) == "VAR") {
                $index = 3;
                $sal["esVariable"] = true;
            } else {
                $urlNueva = $url;
                $sal["esVariable"] = false;
            }
            for ($i = 0; $i < strlen($x); $i++) {
                $a = $x[$i];
                if ($a == "|") {
                    $j++;
                } else {
                    $actual[$j] .= $a;
                }
            }

            $fechaLeadId = date("Y-m-d");
            $timeLeadId = date("h:i");

            array_push(
                $actual,
                $actual[2]
                    . str_replace("-", "", $fechaLeadId)
                    . str_replace(":", "", $timeLeadId)
            );
            array_push($actual, $timeLeadId);
            array_push($actual, $fechaLeadId);

            $sal["array"] = $array;
            $sal["actual"] = $actual;
            $query = "SELECT * FROM vicidial_list WHERE lead_id = '" . $actual[2] . "' LIMIT 1";
            $result = sv_mysqli_query($con, $query, MYSQLI_ASSOC);
            if ($row = sv_mysqli_fetch_array($result)) {
                $array = array_values($array);
                $claves = array_keys($row);
                $claves = array_values($claves);
                $ts = array_merge($array, $claves);
                $array = $ts;
                $actual = array_values($actual);
                $row = array_values($row);
                $ts2 = array_merge($actual, $row);
                $actual = $ts2;
            }
            for ($i = 0; $i < count($array); $i++) {
                if (!is_null($actual[$i])) {
                    $actual[$i] = str_replace("\n", "", $actual[$i] ?? "");
                } else {
                    $actual[$i] = "";
                }
            }
            $urlNueva = substr($url, 3);
            if ($sal["esVariable"]) {
                for ($i = 0; $i < count($array); $i++) {
                    $strxD = "--A--" . $array[$i] . "--B--";
                    if (!is_null($actual[$i])) {
                        $urlNueva = str_replace($strxD, $actual[$i], $urlNueva);
                    }
                }
            }

            $sal["Estado"] = "ok";
            $sal["url"] = $urlNueva;
            $this->output->set_output(json_encode($sal));
        }
    }
    public function logout()
    {
        if (!empty($_SESSION["Usuario"])) {
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=logout&value=LOGOUT";
            echo (file_get_contents($url));
        }
        if (!empty($_SESSION["Usuario"])) {
            session_destroy();
        }
        header('Location: ' . MODULOS . 'login');
    }
    public function index()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        $this->load->helper("language");

        if (!empty($_SESSION["Usuario"])) {
            $this->load->view('homeAgente/head');
            $this->load->view('homeAgente/top_nav_agent');
            $this->load->view('homeAgente/vw_home');
            $this->load->view('homeAgente/foot');
        } else {
            $this->logout();
        }
    }
    public function llamadaInicial()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=call_agent&value=CALL";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function sendDTMF()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $dtmf = $_POST["dtmf"];
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=send_dtmf&value=$dtmf";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function pause()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_pause&value=PAUSE";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function play()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_pause&value=RESUME";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
                $sal["URL"] = $url;
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function manualDial()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = "";
            if (isset($_POST["MAN"])) {
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_dial&value=MANUALNEXT&phone_code=52&search=YES&preview=NO&focus=NO";
            } else {
                $telefono = $_POST["numero"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_dial&value=$telefono&phone_code=52&search=YES&preview=NO&focus=NO";
            }

            $text = file_get_contents($url);
            $sal = array();
            $sal["url"] = $url;
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function localCloserTransfer()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $tipo = 1;
            if (isset($_POST["tipo"])) {
                $tipo = $_POST["tipo"];
            }

            $url = "";
            if ($tipo == 1) {
                $value = $_POST["valor"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=LOCAL_CLOSER&ingroup_choices=$value";
            } elseif ($tipo == 2) {
                $value = $_POST["valor"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=LOCAL_CLOSER&ingroup_choices=AGENTDIRECT&phone_number=$value";
            } else {

                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=LOCAL_CLOSER&ingroup_choices=DEFAULTINGROUP";
            }
            $text = file_get_contents($url);
            $sal = array();
            $sal["url"] = $url;
            $sal["text"] = $text;
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function rate()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = $_SESSION["Campana"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $valor = urlencode($_POST["valor"]);
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_status&value=$valor";
            if ($_POST["tieneCallBack"] == 1) {
                $callback_datetime = urlencode($_POST["callback"]);
                $callback_comments = urlencode($_POST["comentarios"]);
                $callback_type = urlencode($_POST["tipo"]);
                $url .= "&callback_type=$callback_type&callback_datetime=$callback_datetime&callback_comments=$callback_comments";
            }
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
                $con = getConnection();
                $result = sv_mysqli_query($con, "SELECT * FROM vicidial_callbacks WHERE STRCMP('" . date("Y-m-d G:i:s") . "',callback_time)>=0 AND user='$usuario' AND recipient='USERONLY' AND campaign_id='$campana' AND callback_id NOT IN (SELECT callback_id FROM vicidial_callbacks_showed WHERE vicidial_callbacks_showed.callback_id=vicidial_callbacks.callback_id) ORDER BY callback_time ASC LIMIT 1");
                $sal["URL"] = "SELECT * FROM vicidial_callbacks WHERE STRCMP('" . date("Y-m-d G:i:s") . "',callback_time)>=0 AND user='$usuario' AND recipient='USERONLY' AND campaign_id='$campana' AND callback_id NOT IN (SELECT callback_id FROM vicidial_callbacks_showed WHERE vicidial_callbacks_showed.callback_id=vicidial_callbacks.callback_id) ORDER BY callback_time ASC LIMIT 1";
                if (sv_mysqli_num_rows($result)) {
                    $sal["Callback"] = sv_mysqli_fetch_array($result);
                    $result = sv_mysqli_query($con, "SELECT phone_number FROM vicidial_list WHERE lead_id='" . $sal["Callback"]["lead_id"] . "'");
                    $row = sv_mysqli_fetch_array($result);
                    $sal["Callback"]["numero"] = $row["phone_number"];
                    sv_mysqli_query($con, "INSERT INTO vicidial_callbacks_showed(callback_id) VALUES('" . $sal["Callback"]["callback_id"] . "')");
                    $sal["conCall"] = true;
                } else {
                    $sal["conCall"] = false;
                }
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function agentesParaTransferir()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $campana = $_SESSION["Campana"];
            $cliente = $_SESSION["Cliente"];
            $con = getConnection();
            $query = "SELECT V.user FROM vicidial_live_agents AS V,vicidial_users AS U WHERE V.user!='$usuario' AND V.user=U.user AND U.user_group LIKE '%$cliente%'";
            $sal = array();
            $sal["Registros"] = array();
            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["Registros"][] = $row["user"];
            }
            $sal["Estado"] = "ok";
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function cuelga()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_hangup&value=1";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    //Esto fue pedido porque los agentes de GDJ son unos inutiles y pidieron esto
    public function ayudaSoyUnInutil()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $query = "INSERT INTO ayuda(usuario) VALUES('$usuario')";
            if (sv_mysqli_query($con, $query)) {
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = mysqli_error($con);
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        }
    }
    /*public function status(){
    if(!empty($_SESSION["Usuario"])){

    $usuario = $_SESSION["Usuario"];
    $apiUser = USER_API;
    $apiPass = PASS_API;
    $url = URL_DIALVOX."/agc/api.php?source=cli&user=".$apiUser."&pass=".$apiPass."&agent_user=".$usuario."&function=external_hangup&value=1&phone_code=55&search=YES&preview=NO&focus=YES";
    echo(file_get_contents($url));
    }
    }*/
    public function createPauseReport()
    {
        require_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = limpia($_SESSION["Usuario"]);
            $pauseCode = limpia($_POST["pauseCode"]);
            $con = getConnection();
            $sal = array();
            $query = "SELECT esGlobal FROM dialvox_pausa_report WHERE pause_code = '$estado' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                if (!$row["esGlobal"]) {
                    sv_mysqli_query($con, "INSERT INTO dialvox_pausa_report(agente,pause_code) VALUES('$usuario','$pauseCode')");
                }
            }

            $sal["Estado"] = "ok";
            $sal["idReport"] = mysqli_insert_id($con);
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function checkSupervisor()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        require_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = limpia($_POST["usuario"]);
            $password = limpia($_POST["password"]);
            $idReport = limpia($_POST["idReport"]);
            $con = getConnection();
            $sal = array();
            $query = "SELECT user_level FROM vicidial_users WHERE user='$usuario' AND pass='$password' LIMIT 1";
            $results = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($results)) {
                if ($row["user_level"] == 8) {
                    sv_mysqli_query($con, "UPDATE dialvox_pausa_report SET supervisor='$usuario' WHERE id_report='$idReport'");
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_noSupervisor");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_usuarioInexistente");
            }

            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function dejaGrabar()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=recording&value=STOP&phone_code=55&search=YES&preview=NO&focus=NO";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function graba()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=recording&value=START&phone_code=55&search=YES&preview=NO&focus=NO";
            $text = file_get_contents($url);
            $sal = array();
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        require_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $idReportePausa = $_POST["idReportePausa"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status";
            $sal = array();
            $text = file_get_contents($url);
            $keys = ["status", "call_id", "lead_id", "campaign_id", "calls_today", "full_name", "user_group", "user_level", "pause_code", "real_time_sub_status", "phone_number", "vendor_lead_code", "session_id"];
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $keys = ["Descripcion", "otro"];
            } else {
                $sal["Estado"] = "ok";
            }
            $actual = [];
            for ($i = 0; $i < sizeof($keys); $i++) {
                $actual[$i] = "";
            }

            $j = 0;
            for ($i = 0; $i < strlen($text); $i++) {
                $a = $text[$i];
                if ($a == "|") {
                    $sal[$keys[$j]] = $actual[$j];
                    $j++;
                } else {
                    $actual[$j] .= $a;
                }
            }

            if ($sal["Estado"] == "ok") {
                $campana = $_SESSION["Campana"];

                $query = "SELECT closer_campaigns FROM vicidial_campaigns WHERE campaign_id='$campana'";

                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                $ingroups = $row["closer_campaigns"];
                $ingroups = explode(" ", $ingroups);

                $query = "SELECT closer_campaigns FROM vicidial_users WHERE user='$usuario'";

                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                $userIngroups = $row["closer_campaigns"];
                $userIngroups = explode(" ", $userIngroups);
                $userIngroups = array_intersect($userIngroups, $ingroups);
                $userIngroups = implode("','", $userIngroups);

                $query = "SELECT comments, TIMESTAMPDIFF(SECOND,vicidial_live_agents.last_state_change,NOW()) as dif,(SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) as nomCampa,(SELECT active FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) AS campActiva,(SELECT COUNT(*) FROM vicidial_auto_calls WHERE campaign_id IN('$userIngroups', '$campana') AND (campaign_id <> 'AGENTDIRECT' OR agent_only = '$usuario') AND status='LIVE' AND call_type='IN') as llamadasSonando,(SELECT phone_number FROM vicidial_auto_calls WHERE campaign_id IN('$userIngroups', '$campana') AND (campaign_id <> 'AGENTDIRECT' OR agent_only = '$usuario') AND status='LIVE' AND call_type='IN' ORDER BY queue_priority ASC,queue_position ASC LIMIT 1) as primerLlamadaSonando FROM vicidial_live_agents WHERE user = '$usuario' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                $sal["Tiempo"] = $row["dif"];
                $sal["Campana"] = $row["nomCampa"];
                $sal["campActiva"] = $row["campActiva"];

                // ? Distribucion de autopausa ========================
                $llamadasSonando = 0;

                // ! TODO: Cambiando query de las llamadas pendientes
                $queryAutopausa = "SELECT phone_number,auto_call_id as id, TIMESTAMPDIFF(SECOND,call_time,NOW()) AS segundos,agent_only as agente FROM vicidial_auto_calls WHERE campaign_id IN('$userIngroups', '$campana') AND (campaign_id <> 'AGENTDIRECT' OR agent_only = '$usuario') AND status='LIVE' AND call_type='IN' ORDER BY call_time ASC";
                $resultAutopausa = sv_mysqli_query($con, $queryAutopausa);
                $autopausaAutocalls = array();
                $autocallsConAsignacion = array();
                $autocallsSinAsignacion = array();
                $autocallsTransferenciaAgente = false;
                $autocallsTransferenciaAgenteSonando = "";

                while ($rowAutopausa = sv_mysqli_fetch_array($resultAutopausa)) {
                    $autopausaAutocalls[] = $rowAutopausa["id"];
                    if (isset($rowAutopausa["agente"]) && $rowAutopausa["agente"] != $usuario) {
                        $autocallsSinAsignacion[$rowAutopausa["id"]] = $rowAutopausa;
                    } else {
                        $autocallsTransferenciaAgente = true;
                        $autocallsTransferenciaAgenteSonando = $rowAutopausa["phone_number"];
                        // ? ! TODO: Ver si esto permite ignorar las llamadas que son transferencia
                    }
                }

                $llamadasSonando = count($autopausaAutocalls);

                $sal["llamadasSonando"] = $llamadasSonando; // $row["llamadasSonando"];

                $sal["primerLlamadaSonando"] = "";
                $sal["multiplesLlamadas"] = false;
                $sal["transferenciaAlAgente"] = false;
                if ($llamadasSonando > 0) {
                    if (isset($_SESSION["autopausa_Activa"])) {
                        if ($_SESSION["autopausa_Activa"]) {
                            $sal["autopausaTimbrar"] = false;

                            $tiempoTimbrado = $_SESSION["autopausa_TiempoTimbrado"];
                            $metodoDistribucion = $_SESSION["autopausa_MetodoDistribucion"];

                            if ($autocallsTransferenciaAgente) {
                                $sal["transferenciaAlAgente"] = true;
                                if (isset($sal["status"]) && isset($sal["pause_code"])) {
                                    if ($sal["status"] == "PAUSED" && $sal["pause_code"] == "DAUTO") {
                                        $sal["autopausaTimbrar"] = true;
                                    }
                                }
                            } else if ($metodoDistribucion != 'none') {
                                $orderAutopausa = "";

                                switch ($metodoDistribucion) {
                                    case 'menor_llamadas':
                                        $orderAutopausa = "ORDER BY calls_today ASC, last_state_change ASC";
                                        break;

                                    case 'mayor_tiempo':
                                        $orderAutopausa = "ORDER BY last_state_change ASC, calls_today ASC";
                                        break;
                                }

                                $queryAutopausa = "SELECT user FROM vicidial_live_agents WHERE status='PAUSED' AND pause_code='DAUTO' AND campaign_id=$campana $orderAutopausa";
                                $resultAutopausa = sv_mysqli_query($con, $queryAutopausa);
                                $agentesDisponibles = array();
                                $mapaAgentesIndices = array();

                                $selfAgenteIndice = 0;
                                $indiceAgentes = 0;
                                while ($rowAutopausa = sv_mysqli_fetch_array($resultAutopausa)) {
                                    $agente = $rowAutopausa["user"];

                                    $agentesDisponibles[] = array(
                                        "agente" => $agente,
                                        "asignado" => false
                                    );

                                    $mapaAgentesIndices[$agente] = $indiceAgentes;

                                    if ($agente == $usuario) {
                                        $selfAgenteIndice = $indiceAgentes;
                                    }

                                    $indiceAgentes++;
                                }

                                $conteoAgentes = count($agentesDisponibles);
                                $conteoLlamadas = count($autocallsSinAsignacion);

                                if ($conteoLlamadas > 1) {
                                    $sal["multiplesLlamadas"] = false;
                                }

                                if ($conteoLlamadas >= $conteoAgentes) {
                                    if (isset($sal["status"]) && isset($sal["pause_code"])) {
                                        if ($sal["status"] == "PAUSED" && $sal["pause_code"] == "DAUTO") {
                                            $sal["autopausaTimbrar"] = true;
                                        }
                                    }
                                } else {
                                    $asignacionesSobrantes = false;

                                    $queryAutopausa = "SELECT id,Autocall,Agente,TIMESTAMPDIFF(SECOND,Fecha,NOW()) AS Segundos FROM dialvox_autopausa_asignacion WHERE Campana=$campana ORDER BY Fecha ASC";
                                    $resultAutopausa = sv_mysqli_query($con, $queryAutopausa);

                                    while ($rowAutopausa = sv_mysqli_fetch_array($resultAutopausa)) {
                                        $id_autocall = $rowAutopausa["Autocall"];
                                        $agente_autocall = $rowAutopausa["Agente"];

                                        if (isset($autocallsSinAsignacion[$id_autocall])) {
                                            $autocallsConAsignacion[$id_autocall] = $rowAutopausa;
                                            unset($autocallsSinAsignacion[$id_autocall]);

                                            if (isset($mapaAgentesIndices[$agente_autocall])) {
                                                $agentesDisponibles[$mapaAgentesIndices[$agente_autocall]]["asignado"] = true;
                                            }
                                        } else {
                                            // ? Si no existe, significa que es una llamada que ya se resolvió
                                            $asignacionesSobrantes = true;
                                        }
                                    }

                                    // ! Primero, revisar cuales de las llamadas actuales no tienen asignacion
                                    if (count(($autocallsSinAsignacion)) > 0) {
                                        foreach ($autocallsSinAsignacion as $id_autocall => $autocall) {
                                            // ? Si no tiene asignacion, buscar por el primer agente sin asignacion
                                            foreach ($agentesDisponibles as $i => $agente) {
                                                if (!$agente["asignado"]) {
                                                    // ? Asignalo
                                                    $agente_user = $agente["agente"];

                                                    // TODO: Query de asignacion
                                                    $queryAutopausa = "INSERT INTO dialvox_autopausa_asignacion(Autocall,Agente,Campana) VALUES ($id_autocall,'$agente_user','$campana')";
                                                    $sal["InsercionAsignacionQuery"] = $queryAutopausa;
                                                    sv_mysqli_query($con, $queryAutopausa);

                                                    $sal["InsertadaAsignacion"] = true;

                                                    $agentesDisponibles[$i]["asignado"] = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    // ! Despues, revisar llamadas actuales con asignacion
                                    if (count($autocallsConAsignacion) > 0) {
                                        foreach ($autocallsConAsignacion as $id_autocall => $autocall) {
                                            $a_segundos = $autocall["Segundos"];
                                            $a_agente = $autocall["Agente"];

                                            // ? Si la asignacion expiro, busca el siguiente a partir de la posicion del agente

                                            if ($tiempoTimbrado > 0 && $a_segundos >= $tiempoTimbrado) {

                                                $posicion_actual = isset($mapaAgentesIndices[$a_agente]) ? $mapaAgentesIndices[$a_agente] : -1;

                                                //      ? Si la posicion esta fuera de limites, iniciar desde el 0
                                                $posicion_nueva = 0;
                                                if ($posicion_actual < 0) {
                                                    $posicion_nueva = 0;
                                                } else {
                                                    $posicion_nueva = ($posicion_actual + 1) % $conteoAgentes;
                                                }
                                                $indice_inicial = $posicion_nueva;


                                                // ? Validar que no este asignado ya, o que no sea el mismo
                                                while (
                                                    $agentesDisponibles[$posicion_nueva]["asignado"] || $agentesDisponibles[$posicion_nueva]["agente"] == $a_agente
                                                ) {
                                                    $posicion_nueva = ($posicion_nueva + 1) % $conteoAgentes;

                                                    if ($posicion_nueva == $indice_inicial) {
                                                        // ? Romper si se recorren todo y no puede ser asignado
                                                        break;
                                                    }
                                                }

                                                //       ? Asigna
                                                if ($agentesDisponibles[$posicion_nueva]["agente"] != $a_agente) {
                                                    // TODO: Query para actualizar
                                                    $agente_seleccionado = $agentesDisponibles[$posicion_nueva];

                                                    $agente_user = $agente_seleccionado["agente"];

                                                    $queryAutopausa = "UPDATE dialvox_autopausa_asignacion SET Agente = '$agente_user' WHERE Agente = '$a_agente' AND Autocall = $id_autocall";
                                                    sv_mysqli_query($con, $queryAutopausa);

                                                    $sal["ActualizadaAsignacion"] = true;

                                                    $agentesDisponibles[$posicion_nueva]["asignado"] = true;
                                                    if (isset($mapaAgentesIndices[$a_agente])) {
                                                        $agentesDisponibles[$mapaAgentesIndices[$a_agente]]["asignado"] = false;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    // TODO: Eliminar asignaciones de llamadas que no existen 
                                    // TODO: Decidir si hay cambios en las autocalls para ejecutar limpieza
                                    if ($asignacionesSobrantes) {
                                        $autocallsIds = implode(",", $autopausaAutocalls);
                                        $queryAutopausa = "DELETE FROM dialvox_autopausa_asignacion WHERE Autocall NOT IN ($autocallsIds)";
                                        sv_mysqli_query($con, $queryAutopausa);
                                    }

                                    // $sal["AgentesDisponiblesInfo"] = $agentesDisponibles;
                                    // $sal["LlamadasConAsignacion"] = $autocallsConAsignacion;
                                    // $sal["LlamadasSinAsignacion"] = $autocallsSinAsignacion;


                                    // ? Si el mismo usuario esta asignado, timbrar
                                    if ($agentesDisponibles[$selfAgenteIndice]["asignado"]) {
                                        if (isset($sal["status"]) && isset($sal["pause_code"])) {
                                            if ($sal["status"] == "PAUSED" && $sal["pause_code"] == "DAUTO") {
                                                $sal["autopausaTimbrar"] = true;
                                            }
                                        }
                                    }
                                }
                            } else {
                                if (isset($sal["status"]) && isset($sal["pause_code"])) {
                                    if ($sal["status"] == "PAUSED" && $sal["pause_code"] == "DAUTO") {
                                        $sal["autopausaTimbrar"] = true;
                                    }
                                }
                            }

                            $sal["primerLlamadaSonando"] = $row["primerLlamadaSonando"];
                            if ($autocallsTransferenciaAgente) {
                                $sal["primerLlamadaSonando"] = $autocallsTransferenciaAgenteSonando;
                            }
                        }
                    }
                }
                // ? ==================================================


                if ($row["comments"] === "INBOUND") {
                    $sal["tipoLlamada"] = "Inbound";
                } else {
                    $sal["tipoLlamada"] = "Outbound ";
                }
                $query = "SELECT count(*) AS CUENTA from vicidial_auto_calls where callerid='" . $sal["call_id"] . "'";
                $rslt = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($rslt);
                $AcalleridCOUNT = $row["CUENTA"];
                if ($AcalleridCOUNT < 1 && $sal["status"] == "INCALL") {
                    $sal["Cuelga"] = false;
                } else {
                    $sal["Cuelga"] = false;
                }

                $query_ingroup = "SELECT campaign_id FROM vicidial_closer_log WHERE lead_id ='" . $sal["lead_id"] . "' ORDER BY closecallid DESC LIMIT 1";

                $query_ingroup_result = sv_mysqli_query($con, $query_ingroup);
                if ($row2 = sv_mysqli_fetch_array($query_ingroup_result)) {
                    $sal["ingroup_id"] = $row2["campaign_id"];
                    $query_ingroup = "SELECT group_name FROM vicidial_inbound_groups WHERE group_id='" . $sal["ingroup_id"] . "'";
                    $query_ingroup_result = sv_mysqli_query($con, $query_ingroup);
                    if ($row2 = sv_mysqli_fetch_array($query_ingroup_result)) {
                        $sal["ingroup_name"] = $row2["group_name"];
                    } else {
                        $sal["ingroup_name"] = "";
                    }
                } else {
                    $sal["ingroup_id"] = "";
                    $sal["ingroup_name"] = "";
                }

                $queryInbounds = "SELECT comments FROM vicidial_live_agents WHERE user='$usuario'";
                $query_result_inbounds = sv_mysqli_query($con, $queryInbounds);

                if ($rowInbounds = sv_mysqli_fetch_array($query_result_inbounds)) {
                    $sal["actual_call_type"] = $rowInbounds["comments"];
                } else {
                    $sal["actual_call_type"] = "";
                }
                if ($idReportePausa && is_numeric($idReportePausa)) {
                    $idReportePausa = intval(limpia($idReportePausa));
                    $queryPauseCode = "SELECT resuelto FROM dialvox_pausa_report WHERE id_report=$idReportePausa";
                    $result2 = sv_mysqli_query($con, $queryPauseCode);
                    if ($row2 = sv_mysqli_fetch_array($result2)) {
                        $sal["reportePausa"] = $row2["resuelto"];
                    }
                }
            }
            $sal[$keys[$j]] = $actual[$j];
            $this->output->set_output(json_encode($sal));
        }
    }
    public function makeLOG()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $file = fopen($_SESSION["Usuario"] . "-" . date("d-m-Y-H-i-s") . ".csv", "w");
            $sal = array();
            $sal["Estado"] = "ok";
            if ($file === false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_guardarLog");
            } else {
                fputcsv($file, explode(",", "TiempoDispo,ventanas,allow_beep,Manual,btnActual,time_beep,time_repeat,salio,otraFlag,puedoPoner,flag,flagStatus,banderitaCRM,vuelveCheck,aPasado,dialvoxCRM,Usuario,statusCalificacion,cronometro,TiempoTot,statusPausa,enGrabacion,enLlamada,puedoEnviarDTMF,otraFlag,enEspera,enTransferido,aTransferir,banderaCRM,banderaCRM2,status,real_time_sub_status,URL1,URL2,Fecha y Hora"));
                $tamano = count($_POST["logs"]);
                for ($i = 0; $i < $tamano; $i++) {
                    $sal["POST"] = $_POST;
                    if ($i == 0) {
                        array_push($_POST["logs"][$i], $_POST["texto"]);
                    }
                    fputcsv($file, $_POST["logs"][$i]);
                }
            }
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
            if ($file !== false) {
                fclose($file);
            }
        }
    }
    public function transferir()
    {
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $value = $_POST["value"];
            $url = "";
            if (isset($_POST["phone_number"])) {
                $phone_number = $_POST["phone_number"];
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=$value&phone_number=$phone_number";
            } else {
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=transfer_conference&value=$value";
            }

            $text = file_get_contents($url);
            $sal = array();
            $sal["url"] = $url;
            if (strpos($text, "ERROR") !== false) {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = str_replace("ERROR: ", "", $text);
            } else {
                $sal["Estado"] = "ok";
            }
            $sal["text"] = $text;
            header('Content-type: application/json');
            $this->output->set_output(json_encode($sal));
        }
    }

    public function saveCallback()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        $response = array(
            "Estado" => "error",
            "Mensaje" => $this->lang->line("desc_sinSesion"),
        );
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';
            $user = $_SESSION["Usuario"];
            $group = $_SESSION["Grupo"];
            $campaign = $_SESSION["Campana"];

            $con = getConnection();

            $callback_time = date("Y-m-d H:i:s", strtotime($_POST["callback_time"]));
            $comments = limpia($_POST["comments"]);
            $recipient = limpia($_POST["recipient"]);
            $lead_id = limpia($_POST["lead_id"]);

            if ($recipient === "ANYONE") {
                $user = "";
            }

            $query = "SELECT list_id FROM vicidial_list WHERE lead_id=$lead_id";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $list_id = $row["list_id"];

            $query = "INSERT INTO vicidial_callbacks (lead_id,list_id,campaign_id,status,entry_time,callback_time,user,recipient,comments,user_group) VALUES ($lead_id, $list_id, $campaign,'INACTIVE', current_timestamp(),'$callback_time','$user','$recipient','$comments','$group')";

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

            if ($result === false) {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } else {
                $response = array(
                    "Estado" => "ok",
                    "Mensaje" => $this->lang->line("desc_callbackRegistrado"),
                );
                $response["CallbackId"] = (string) mysqli_insert_id($con);
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    public function deleteCallback()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        $response = array(
            "Estado" => "error",
            "Mensaje" => $this->lang->line("desc_sinSesion"),
        );
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';

            $con = getConnection();

            $callback_id = $_POST["id"];

            $query = "DELETE FROM vicidial_callbacks WHERE callback_id=$callback_id";

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

            if ($result === false) {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } else {
                $response["Estado"] = "ok";
                $response["Mensaje"] = $this->lang->line("desc_callbackEliminado");
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    public function assignCallback()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        $response = array(
            "Estado" => "error",
            "Mensaje" => $this->lang->line("desc_sinSesion"),
        );
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';
            $user = $_SESSION["Usuario"];

            $con = getConnection();
            $query = "SELECT callback_id,comments,lead_id,callback_time,(SELECT phone_number FROM vicidial_list WHERE lead_id=vicidial_callbacks.lead_id) as phone_number FROM vicidial_callbacks WHERE user='' AND status='INACTIVE' LIMIT 1";

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

            if ($result === false) {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } else if (sv_mysqli_num_rows($result) === 0) {
                $response["Estado"] = "ok";
                $response["Mensaje"] = $this->lang->line("desc_sinCallbacks");
                $response["CallbackId"] = "none";
            } else {
                $row = sv_mysqli_fetch_array($result);
                $CallbackId = (string) $row["callback_id"];
                $CallbackComments = $row["comments"];
                $CallbackPhoneNumber = $row["phone_number"];
                $CallbackLead = $row["lead_id"];
                $CallbackTime = $row["callback_time"];

                $query = "UPDATE vicidial_callbacks SET user='$user' WHERE callback_id=$CallbackId";
                $result = sv_mysqli_query($con, $query);

                if ($result === false) {
                    $response["Mensaje"] = mysqli_error($con);
                    $response["Query"] = $query;
                } else {
                    $response = array(
                        "Estado" => "ok",
                        "CallbackId" => $CallbackId,
                        "CallbackComments" => $CallbackComments,
                        "CallbackPhoneNumber" => $CallbackPhoneNumber,
                        "CallbackLead" => $CallbackLead,
                        "CallbackTime" => $CallbackTime,
                        "Mensaje" => $this->lang->line("men_callbackAsignado"),
                    );
                }
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    public function getCallbacks()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('homeagente', "spanish");
                break;
            case "en":
                $this->lang->load('homeagente', "english");
                break;
            default:
                $this->lang->load('homeagente', "spanish");
                break;
        }
        $response = array(
            "Estado" => "error",
            "Mensaje" => $this->lang->line("desc_sinSesion"),
        );
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';
            $user = $_SESSION["Usuario"];

            $con = getConnection();
            $query = "SELECT callback_id,comments,lead_id,callback_time,(SELECT phone_number FROM vicidial_list WHERE lead_id=vicidial_callbacks.lead_id) as phone_number FROM vicidial_callbacks WHERE user='$user' AND status='INACTIVE' LIMIT 1";

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

            if ($result === false) {
                $response["Mensaje"] = mysqli_error($con);
                $response["Query"] = $query;
            } else if (sv_mysqli_num_rows($result) === 0) {
                $response["Estado"] = "ok";
                $response["Mensaje"] = $this->lang->line("desc_sinCallbacks");
                $response["Callbacks"] = array();
            } else {
                $response["Estado"] = "ok";
                $response["Callbacks"] = array();
                $array_count = 0;
                while ($row = sv_mysqli_fetch_array($result)) {
                    $response["Callbacks"][] = array();
                    $response["Callbacks"][$array_count]["Id"] = (string) $row["callback_id"];
                    $response["Callbacks"][$array_count]["Comments"] = $row["comments"];
                    $response["Callbacks"][$array_count]["PhoneNumber"] = $row["phone_number"];
                    $response["Callbacks"][$array_count]["Lead"] = $row["lead_id"];
                    $response["Callbacks"][$array_count]["Time"] = $row["callback_time"];
                    $array_count++;
                }
                $response["Mensaje"] = $this->lang->line("men_callbacksObtenidos");
            }
            sv_mysqli_close($con);
        }
        header('Content-type: application/json');
        $this->output->set_output(json_encode($response));
    }

    // Funciones para la reconexion
    public function actualizarConferencia() {
        $sal = array(
            "Estado" => "error",
            "Descripcion" => "No tienes permiso para realizar esta acción"
        );
        
        require_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];

            $con = getConnection();

            $query = "SELECT conf_exten FROM vicidial_conferences WHERE extension LIKE '%$usuario%' AND extension NOT LIKE '%3WAY%'";

            $result = sv_mysqli_query($con, $query);
            $conf_exten = "-1";

            if ($row = sv_mysqli_fetch_array($result)) {
                $conf_exten = $row["conf_exten"];
                $session_conf_exten = "-1";

                $query = "SELECT conf_exten FROM vicidial_session_data WHERE user='$usuario'";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $session_conf_exten = $row["conf_exten"];

                    if ($conf_exten != $session_conf_exten) {
                        $query = "
                        UPDATE 
                            vicidial_session_data 
                        SET 
                            conf_exten='$conf_exten',
                            agent_login_call=REPLACE(
                                agent_login_call,
                                '$session_conf_exten',
                                '$conf_exten'
                            ) 
                        WHERE 
                            user='$usuario'";
                        $result = sv_mysqli_query($con, $query);
                        if ($result) {
                            $sal["Estado"] = "ok";
                            $sal["Descripcion"] = "Conferencia corregida";
                        } else {
                            $sal["Descripcion"] = "No fue posible corregir su conferencia";
                        }
                    } else {
                        $sal["Estado"] = "ok";
                        $sal["Descripcion"] = "Conferencia correcta";
                    }
                } else {
                    $sal["Descripcion"] = "No se encontró su registro de sesión";
                }
            } else {
                $sal["Descripcion"] = "No se encontró su conferencia";
            }
        }

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