<?php

require_once "BASEPATH.php";

include_once "Clases/ListaDatos.php";
include_once "Clases/CRM/CRMDatos.php";
include_once "Clases/CRM/CampoDatos.php";
include_once "Clases/CRM/RespuestaDatos.php";
include_once "Clases/CRM/GestionDatos.php";
class Listas extends MY_Controller
{
    public function trata(&$out, $arreglo, &$lastLinePrinted)
    {
        $llaves = array_keys($arreglo);
        //fputcsv($out,array_values($llaves));
        $llavesNoArreglos = array();
        for ($i = 0; $i < count($llaves); $i++) {
            if (!is_array($arreglo[$llaves[$i]])) {
                //$this->trata($out,$arreglo[$llaves[$i]]);
                $llavesNoArreglos[] = $llaves[$i];
            }
        }
        $temp = array();
        for ($i = 0; $i < count($llaves); $i++) {
            if (!is_array($arreglo[$llaves[$i]])) {
                $temp[] = $arreglo[$llaves[$i]];
            }
        }
        if (count($temp) > 0) {
            if ($llavesNoArreglos != $lastLinePrinted) {
                fputcsv($out, array_values($llavesNoArreglos));
                $lastLinePrinted = $llavesNoArreglos;
            }
            fputcsv($out, array_values($temp));
        }
        for ($i = 0; $i < count($llaves); $i++) {
            if (is_array($arreglo[$llaves[$i]])) {
                $temp2 = array();
                $temp2[0] = $llaves[$i];
                if (!is_numeric($temp2[0])) {
                    fputcsv($out, array_values($temp2));
                }

                $this->trata($out, $arreglo[$llaves[$i]], $lastLinePrinted);
            }
        }
    }
    public function resetList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $list_id = limpia($_POST["lista"]);
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT list_id,campaign_id FROM vicidial_lists WHERE list_id = '$list_id' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $donde) LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $campana = $row["campaign_id"];
                $andReset = "";
                $sePuede = true;
                if (isset($_POST["status"])) {
                    $status = $_POST["status"];
                    $queryStatus = "SELECT campaign_id,dial_statuses FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde LIMIT 1";
                    $result = sv_mysqli_query($con, $queryStatus);
                    $row = sv_mysqli_fetch_array($result);
                    $estatus = $row["dial_statuses"];
                    if (strpos($estatus, $status) === false) {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_estadoRemarcable");
                        $sePuede = false;
                    } else {
                        $andReset = "AND status = '$status'";
                    }
                }
                if ($sePuede) {
                    $query = "SELECT dial_statuses FROM vicidial_campaigns WHERE campaign_id = '$campana'";
                    $result = sv_mysqli_query($con, $query);
                    $status = "";
                    if ($row2 = sv_mysqli_fetch_array($result)) {
                        $status = "'" . str_replace(" ", "','", trim(substr(trim($row2["dial_statuses"]), 0, -1))) . "'";

                    } else {
                        $sePuede = false;
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_sinEstadosMarcables");
                    }
                    if ($sePuede) {
                        $query = "SELECT list_id FROM vicidial_lists WHERE list_id = '$list_id' LIMIT 1";
                        $result = sv_mysqli_query($con, $query);
                        if ($row = sv_mysqli_fetch_array($result)) {
                            if (isset($_POST["status"])) {
                                $query = "SELECT COUNT(lead_id) FROM vicidial_list where list_id='$list_id' AND called_since_last_reset='N' AND status IN ($status)";
                                $result = sv_mysqli_query($con, $query);
                                $row = sv_mysqli_fetch_array($result);
                                if ($row[0] > 0) {
                                    $sePuede = false;
                                    $sal["Estado"] = "error";
                                    $sal["Descripcion"] = $this->lang->line("desc_conEstadosMarcables");
                                }
                            }
                            if ($sePuede) {
                                $stmtB = "UPDATE vicidial_list set called_since_last_reset='N'  where list_id='$list_id' AND status IN ($status) $andReset";
                                $rslt = sv_mysqli_query($con, $stmtB);
                                $cuantos = mysqli_affected_rows($con);
                                $sal["Cuantos"] = $cuantos;
                                $SQL_log = "$stmtB|";
                                $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='RESET', record_id='$list_id', event_code='ADMIN RESET LIST', event_sql=\"$SQL_log\", event_notes=''";
                                $rslt = sv_mysqli_query($con, $stmt);
                                $sal["Estado"] = "ok";
                            }
                        } else {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_listaInexistente");
                        }

                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosReinicio");
            }
            $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 completeLeads($dial_statuses, $camp_lists, $call_count_limit, $single_status, $campaign_id, $con)
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        if (isset($camp_lists)) {
            if (strlen($camp_lists) > 1) {
                if (strlen($dial_statuses) > 2) {
                    $dial_statuses = preg_replace("/ -$/", "", $dial_statuses);
                    $Dstatuses = explode(" ", $dial_statuses);
                    $Ds_to_print = (count($Dstatuses) - 0);
                    $Dsql = '';
                    $o = 0;
                    while ($Ds_to_print > $o + 1) {
                        $o++;
                        $Dsql .= "'$Dstatuses[$o]',";
                    }
                    $Dsql = preg_replace("/,$/", "", $Dsql);
                    if (strlen($Dsql) < 2) {
                        $Dsql = "''";
                    }
                    $CCLsql = "(called_count < 0) or";
                    if ($call_count_limit > 0) {
                        $CCLsql = "(called_count >= $call_count_limit) or";
                    }
                    $complete_statuses = '';
                    $stmt = "SELECT status from vicidial_statuses where completed='Y';";
                    $rslt = sv_mysqli_query($con, $stmt);
                    $statuses_to_print = sv_mysqli_num_rows($rslt);
                    $q = 0;
                    while ($statuses_to_print > $q) {
                        $rowx = sv_mysqli_fetch_array($rslt);
                        $complete_statuses .= "'$rowx[0]',";
                        $q++;
                    }
                    $stmt = "SELECT status from vicidial_campaign_statuses where completed='Y' and campaign_id = '$campaign_id';";
                    $rslt = sv_mysqli_query($con, $stmt);
                    $statuses_to_print = sv_mysqli_num_rows($rslt);
                    $q = 0;
                    while ($statuses_to_print > $q) {
                        $rowx = sv_mysqli_fetch_array($rslt);
                        $complete_statuses .= "'$rowx[0]',";
                        $q++;
                    }
                    $complete_statuses = preg_replace("/,$/", "", $complete_statuses);
                    if (strlen($complete_statuses) < 2) {
                        $complete_statuses = "''";
                    }
                    $CSsql = "status IN($complete_statuses)";
                    $stmt = "SELECT count(*) FROM vicidial_list where ( (status IN($Dsql)) and (list_id IN($camp_lists)) and ( $CCLsql ($CSsql) ) );";
                    $rslt = sv_mysqli_query($con, $stmt);
                    $rslt_rows = sv_mysqli_num_rows($rslt);
                    if ($rslt_rows) {
                        $rowx = sv_mysqli_fetch_array($rslt);
                        $complete_leads = $rowx[0];
                    } else {
                        $complete_leads = '0';
                    }
                    if ($single_status > 0) {
                        return $complete_leads;
                    } else {
                        echo "There are $complete_leads completed leads in those lists\n";
                    }
                } else {
                    echo _QXZ("no dial statuses selected for this campaign") . "\n";
                }
            } else {
                echo _QXZ("no active lists selected for this campaign") . "\n";
            }
        } else {
            echo _QXZ("no active lists selected for this campaign") . "\n";
        }
    }
    public function getListDetails()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $lista = $_POST["lista"];
            $query = "SELECT * FROM vicidial_lists WHERE list_id = $lista LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $sal["Estado"] = "ok";
            $sal["Lista"] = $row;
            $list_id = $lista;
            $query = "SELECT vicidial_lists.list_id,list_name,campaign_id,active,list_description,list_changedate,list_lastcalldate,reset_time,agent_script_override,campaign_cid_override,am_message_exten_override,drop_inbound_group_override,xferconf_a_number,xferconf_b_number,xferconf_c_number,xferconf_d_number,xferconf_e_number,web_form_address,web_form_address_two,time_zone_setting,inventory_report,IFNULL(audit_comments,0),expiration_date,DATE_FORMAT(expiration_date,'%Y%m%d') from vicidial_lists left outer join vicidial_lists_custom on vicidial_lists.list_id=vicidial_lists_custom.list_id where vicidial_lists.list_id='$list_id'";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $list_name = $row[1];
            $campaign_id = $row[2];
            $active = $row[3];
            $list_description = $row[4];
            $list_changedate = $row[5];
            $list_lastcalldate = $row[6];
            $reset_time = $row[7];
            $agent_script_override = $row[8];
            $campaign_cid_override = $row[9];
            $am_message_exten_override = $row[10];
            $drop_inbound_group_override = $row[11];
            $xferconf_a_number = $row[12];
            $xferconf_b_number = $row[13];
            $xferconf_c_number = $row[14];
            $xferconf_d_number = $row[15];
            $xferconf_e_number = $row[16];
            $web_form_address = $row[17];
            $web_form_address_two = $row[18];
            $time_zone_setting = $row[19];
            $inventory_report = $row[20];
            $audit_comments = $row[21];
            $expiration_date = $row[22];
            $expiration_dateINT = $row[23];
            $stmt = "SELECT status,status_name,selectable,human_answered,category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed from vicidial_statuses order by status";
            $rslt = sv_mysqli_query($con, $stmt);
            $statuses_to_print = sv_mysqli_num_rows($rslt);
            $o = 0;
            $statuses_list = array();
            $statuses_complete_list = array();
            while ($statuses_to_print > $o) {
                $rowx = sv_mysqli_fetch_array($rslt);
                $statuses_list[$rowx[0]] = $rowx[1];
                $statuses_complete_list[$rowx[0]] = $rowx[11];
                $o++;
            }
            //echo("1\n");
            $stmt = "SELECT status,status_name,selectable,campaign_id,human_answered,category,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed from vicidial_campaign_statuses where campaign_id='$campaign_id' order by status";
            $rslt = sv_mysqli_query($con, $stmt);
            $Cstatuses_to_print = sv_mysqli_num_rows($rslt);
            $o = 0;
            while ($Cstatuses_to_print > $o) {
                $rowx = sv_mysqli_fetch_array($rslt);
                $statuses_list[$rowx[0]] = $rowx[1];
                $statuses_complete_list[$rowx[0]] = $rowx[12];
                $o++;
            }
            //echo("2\n");
            $dialable_total = 0;
            $complete_total = 0;
            $fSQL = '';
            $stmt = "SELECT dial_statuses,local_call_time,lead_filter_id,drop_lockout_time,call_count_limit from vicidial_campaigns where campaign_id='$campaign_id'";
            $rslt = sv_mysqli_query($con, $stmt);
            $row = sv_mysqli_fetch_array($rslt);
            $dial_statuses = $row[0];
            $local_call_time = $row[1];
            $lead_filter_id = $row[2];
            $drop_lockout_time = $row[3];
            $call_count_limit = $row[4];
            $stmt = "SELECT lead_filter_sql from vicidial_lead_filters where lead_filter_id='$lead_filter_id'";
            $rslt = sv_mysqli_query($con, $stmt);
            $filters_to_print = sv_mysqli_num_rows($rslt);
            if ($filters_to_print > 0) {
                $rowx = sv_mysqli_fetch_array($rslt);
                $filterSQL = $rowx[0];
                $filterSQL = preg_replace("/\\\\/", "", $filterSQL);
                $filterSQL = preg_replace('/^and|and$|^or|or$/i', '', $filterSQL);
                if (strlen($filterSQL) > 4) {
                    $fSQL = "and ($filterSQL)";
                } else {
                    $fSQL = '';
                }
            }
            //echo("3\n");
            $leads_in_list = 0;
            $leads_in_list_N = 0;
            $leads_in_list_Y = 0;
            $stmt = "SELECT status,called_since_last_reset,count(*) from vicidial_list where list_id='$list_id' group by status,called_since_last_reset order by status,called_since_last_reset";
            $rslt = sv_mysqli_query($con, $stmt);
            $statuses_to_print = sv_mysqli_num_rows($rslt);
            $o = 0;
            $lead_list = array();
            $lead_list['count'] = 0;
            $lead_list['Y_count'] = 0;
            $lead_list['N_count'] = 0;
            $lead_list['Y'] = array();
            $lead_list['N'] = array();
            while ($statuses_to_print > $o) {
                $rowx = sv_mysqli_fetch_array($rslt);
                $lead_list['count'] = ($lead_list['count'] + $rowx[2]);
                if ($rowx[1] == 'N') {
                    $since_reset = 'N';
                    $since_resetX = 'Y';
                } else {
                    $since_reset = 'Y';
                    $since_resetX = 'N';
                }
                if (!array_key_exists($rowx[0], $lead_list[$since_reset])) {
                    $lead_list[$since_reset][$rowx[0]] = 0;
                }
                $lead_list[$since_reset][$rowx[0]] = ($lead_list[$since_reset][$rowx[0]] + $rowx[2]);
                $lead_list[$since_reset . '_count'] = ($lead_list[$since_reset . '_count'] + $rowx[2]);
                if (!isset($lead_list[$since_resetX][$rowx[0]])) {
                    $lead_list[$since_resetX][$rowx[0]] = 0;
                }
                $o++;
            }
            //echo("4\n");
            $o = 0;
            $sal["Tabla1"]["Registros"] = array();
            $SSexpanded_list_stats = 1;
            if ($lead_list['count'] > 0) {
                //while (list($dispo) = each($lead_list[$since_reset])) {
                foreach ($lead_list[$since_reset] as $dispo => $dispoName) {
                    if ($SSexpanded_list_stats > 0) {
                        if (!array_key_exists($dispo, $lead_list['N'])) {
                            $lead_list['N'][$dispo] = 0;
                        }

                        if (!array_key_exists($dispo, $lead_list['Y'])) {
                            $lead_list['Y'][$dispo] = 0;
                        }

                        ### call function to calculate dialable leads
                        $single_status = 1;
                        $dial_statuses = " $dispo -";
                        $camp_lists = $list_id;
                        if (array_key_exists($dispo, $statuses_complete_list) && $statuses_complete_list[$dispo] == 'Y') {
                            $Xdialable_count = 0;
                        } else {
                            $query = "SELECT COUNT(lead_id) AS CUENTA FROM vicidial_list WHERE list_id = $list_id AND status = '$dispo' AND status = 'NEW'";
                            $result = sv_mysqli_query($con, $query);
                            $rowSum = sv_mysqli_fetch_array($result);
                            $Xdialable_count = $rowSum["CUENTA"];
                        }
                        $dialable_total = ($dialable_total + $Xdialable_count);
                        ### get number of complete calls of this status for penetration calculations
                        /*$query = "SELECT COUNT(lead_id) AS CUENTA FROM vicidial_list WHERE list_id = $list_id AND status = '$dispo'";
                        $result = sv_mysqli_query($con, $query);
                        $rowSum = sv_mysqli_fetch_array($result);
                        $Xcomplete_count = $rowSum["CUENTA"];*/
                        $Xcomplete_count = $this->completeLeads($dial_statuses, $camp_lists, $call_count_limit, $single_status, $campaign_id, $con);
                        $complete_total = ($complete_total + $Xcomplete_count);
                        $dispo_total = ($lead_list['Y'][$dispo] + $lead_list['N'][$dispo]);
                        if (($Xcomplete_count < 1) or ($dispo_total < 1)) {
                            $complete_pct = "0";
                        } else {
                            $complete_pct = intval(($Xcomplete_count / $dispo_total) * 100);
                        }
                        if (!array_key_exists($dispo, $statuses_list)) {
                            $statuses_list[$dispo] = " ";
                        }
                        $sal["Tabla1"]["Registros"][$o]["status"] = $dispo;
                        $sal["Tabla1"]["Registros"][$o]["penetracion"] = $complete_pct;
                        $sal["Tabla1"]["Registros"][$o]["marcable"] = $Xdialable_count;
                        $sal["Tabla1"]["Registros"][$o]["noLlamado"] = $lead_list['N'][$dispo];
                        $sal["Tabla1"]["Registros"][$o]["llamado"] = $lead_list['Y'][$dispo];
                        $sal["Tabla1"]["Registros"][$o]["nombreStatus"] = $statuses_list[$dispo];
                        $o++;
                    }
                }
            }
            //echo("5\n");
            if ($SSexpanded_list_stats > 0) {
                if (($complete_total < 1) or ($lead_list['count'] < 1)) {
                    $total_complete_pct = "0";
                } else {
                    $total_complete_pct = intval(($complete_total / $lead_list['count']) * 100);
                }
                $sal["Tabla1"]["subtotales"]["llamado"] = $lead_list['Y_count'];
                $sal["Tabla1"]["subtotales"]["noLlamado"] = $lead_list['N_count'];
                $sal["Tabla1"]["totales"]["llamado"] = $lead_list['count'];
                //$sal["Tabla1"]["totales"]["noLlamado"] = $lead_list['count'];
                $sal["Tabla1"]["totales"]["marcable"] = $dialable_total;
                $sal["Tabla1"]["totales"]["penetracion"] = $total_complete_pct;
            }
            //echo("6\n");
            unset($lead_list);
            $sal["Tabla2"] = array();
            $stmt = "SELECT gmt_offset_now,called_since_last_reset,count(*) from vicidial_list where list_id='$list_id' group by gmt_offset_now,called_since_last_reset order by gmt_offset_now,called_since_last_reset";
            $rslt = sv_mysqli_query($con, $stmt);
            $statuses_to_print = sv_mysqli_num_rows($rslt);
            $o = 0;
            $plus = '+';
            $lead_list['count'] = 0;
            $lead_list['Y_count'] = 0;
            $lead_list['N_count'] = 0;
            $lead_list['Y'] = array();
            $lead_list['N'] = array();
            while ($statuses_to_print > $o) {
                $rowx = sv_mysqli_fetch_array($rslt);
                $lead_list['count'] = ($lead_list['count'] + $rowx[2]);
                if ($rowx[1] == 'N') {
                    $since_reset = 'N';
                    $since_resetX = 'Y';
                } else {
                    $since_reset = 'Y';
                    $since_resetX = 'N';
                }
                if (!array_key_exists($rowx[0], $lead_list[$since_reset])) {
                    $lead_list[$since_reset][$rowx[0]] = 0;
                }
                $lead_list[$since_reset][$rowx[0]] = ($lead_list[$since_reset][$rowx[0]] + $rowx[2]);
                $lead_list[$since_reset . '_count'] = ($lead_list[$since_reset . '_count'] + $rowx[2]);
                #If opposite side is not set, it may not in the future so give it a value of zero
                if (!isset($lead_list[$since_resetX][$rowx[0]])) {
                    $lead_list[$since_resetX][$rowx[0]] = 0;
                }
                $o++;
            }
            $donde = 0;
            $sal["Tabla2"]["Registros"] = array();
            if ($lead_list['count'] > 0) {
                //while (list($tzone) = each($lead_list[$since_reset])) {
                foreach ($lead_list[$since_reset] as $tzone => $tzoneName) {
                    if (!array_key_exists($tzone, $lead_list['N'])) {
                        $lead_list['N'][$tzone] = 0;
                    }

                    if (!array_key_exists($tzone, $lead_list['Y'])) {
                        $lead_list['Y'][$tzone] = 0;
                    }

                    $LOCALzone = 3600 * $tzone;
                    $LOCALdate = gmdate("D j M Y H:i", time() + $LOCALzone);
                    if ($tzone >= 0) {
                        $DISPtzone = "$plus$tzone";
                    } else {
                        $DISPtzone = "$tzone";
                    }
                    $sal["Tabla2"]["Registros"][$donde]["GTM"] = $DISPtzone . "(" . $LOCALdate . ")";
                    $sal["Tabla2"]["Registros"][$donde]["llamado"] = $lead_list['Y'][$tzone];
                    $sal["Tabla2"]["Registros"][$donde++]["noLlamado"] = $lead_list['N'][$tzone];
                }
            }
            //echo("7\n");
            $sal["Tabla2"]["subtotales"]["llamado"] = $lead_list['Y_count'];
            $sal["Tabla2"]["subtotales"]["noLlamado"] = $lead_list['N_count'];
            $sal["Tabla2"]["total"] = $lead_list['count'];
            unset($lead_list);
            $SSuser_territories_active = 1;
            if ($SSuser_territories_active > 0) {
                $sal["Tabla3"] = array();
                $leads_in_list = 0;
                $leads_in_list_N = 0;
                $leads_in_list_Y = 0;
                $stmt = "SELECT owner,called_since_last_reset,count(*) from vicidial_list where list_id='$list_id' group by owner,called_since_last_reset order by owner,called_since_last_reset;";
                $rslt = sv_mysqli_query($con, $stmt);
                $owners_to_print = sv_mysqli_num_rows($rslt);
                $o = 0;
                $lead_list['count'] = 0;
                $lead_list['Y_count'] = 0;
                $lead_list['N_count'] = 0;
                $lead_list['Y'] = array();
                $lead_list['N'] = array();
                while ($owners_to_print > $o) {
                    $rowx = sv_mysqli_fetch_array($rslt);
                    $lead_list['count'] = ($lead_list['count'] + $rowx[2]);
                    if ($rowx[1] == 'N') {
                        $since_reset = 'N';
                        $since_resetX = 'Y';
                    } else {
                        $since_reset = 'Y';
                        $since_resetX = 'N';
                    }
                    if (!array_key_exists($rowx[0], $lead_list[$since_reset])) {
                        $lead_list[$since_reset][$rowx[0]] = 0;
                    }
                    $lead_list[$since_reset][$rowx[0]] = ($lead_list[$since_reset][$rowx[0]] + $rowx[2]);
                    $lead_list[$since_reset . '_count'] = ($lead_list[$since_reset . '_count'] + $rowx[2]);
                    #If opposite side is not set, it may not in the future so give it a value of zero
                    if (!isset($lead_list[$since_resetX][$rowx[0]])) {
                        $lead_list[$since_resetX][$rowx[0]] = 0;
                    }
                    $o++;
                }
                $o = 0;
                if ($lead_list['count'] > 0) {
                    //while (list($owner) = each($lead_list[$since_reset])) {
                    foreach ($lead_list[$since_reset] as $owner => $ownerName) {
                        if (!array_key_exists($owner, $lead_list['N'])) {
                            $lead_list['N'][$owner] = 0;
                        }

                        if (!array_key_exists($owner, $lead_list['Y'])) {
                            $lead_list['Y'][$owner] = 0;
                        }

                        $sal["Tabla3"]["Registros"][$o]["dueno"] = $owner;
                        $sal["Tabla3"]["Registros"][$o]["llamado"] = $lead_list['Y'][$owner];
                        $sal["Tabla3"]["Registros"][$o]["noLlamado"] = $lead_list['N'][$owner];
                        $o++;
                    }
                }
                $sal["Tabla3"]["subtotales"]["llamado"] = $lead_list['Y_count'];
                $sal["Tabla3"]["subtotales"]["noLlamado"] = $lead_list['N_count'];
                $sal["Tabla3"]["total"] = $lead_list['count'];
            }
            //echo("8\n");
            unset($lead_list);
            $leads_in_list = 0;
            $leads_in_list_N = 0;
            $leads_in_list_Y = 0;
            $stmt = "SELECT rank,called_since_last_reset,count(*) from vicidial_list where list_id='$list_id' group by rank,called_since_last_reset order by rank,called_since_last_reset";
            $rslt = sv_mysqli_query($con, $stmt);
            $ranks_to_print = sv_mysqli_num_rows($rslt);
            $o = 0;
            $lead_list['count'] = 0;
            $lead_list['Y_count'] = 0;
            $lead_list['N_count'] = 0;
            $lead_list['Y'] = array();
            $lead_list['N'] = array();
            while ($ranks_to_print > $o) {
                $rowx = sv_mysqli_fetch_array($rslt);
                $lead_list['count'] = ($lead_list['count'] + $rowx[2]);
                if ($rowx[1] == 'N') {
                    $since_reset = 'N';
                    $since_resetX = 'Y';
                } else {
                    $since_reset = 'Y';
                    $since_resetX = 'N';
                }
                if (!array_key_exists($rowx[0], $lead_list[$since_reset])) {
                    $lead_list[$since_reset][$rowx[0]] = 0;
                }
                $lead_list[$since_reset][$rowx[0]] = ($lead_list[$since_reset][$rowx[0]] + $rowx[2]);
                $lead_list[$since_reset . '_count'] = ($lead_list[$since_reset . '_count'] + $rowx[2]);
                #If opposite side is not set, it may not in the future so give it a value of zero
                if (!isset($lead_list[$since_resetX][$rowx[0]])) {
                    $lead_list[$since_resetX][$rowx[0]] = 0;
                }
                $o++;
            }
            //echo("9\n");
            $o = 0;
            $sal["Tabla4"] = array();
            if ($lead_list['count'] > 0) {
                //while (list($rank) = each($lead_list[$since_reset])) {
                foreach ($lead_list[$since_reset] as $rank => $rankName) {
                    if (!array_key_exists($rank, $lead_list['N'])) {
                        $lead_list['N'][$rank] = 0;
                    }

                    if (!array_key_exists($rank, $lead_list['Y'])) {
                        $lead_list['Y'][$rank] = 0;
                    }

                    $sal["Tabla4"]["Registros"][$o]["rango"] = $rank;
                    $sal["Tabla4"]["Registros"][$o]["llamados"] = $lead_list['Y'][$rank];
                    $sal["Tabla4"]["Registros"][$o]["noLlamados"] = $lead_list['N'][$rank];
                    $o++;
                }
            }
            //echo("10\n");
            $sal["Tabla4"]["subtotales"]["llamados"] = $lead_list['Y_count'];
            $sal["Tabla4"]["subtotales"]["noLlamados"] = $lead_list['N_count'];
            $sal["Tabla4"]["total"] = $lead_list['count'];
            unset($lead_list);
            $leads_in_list = 0;
            $leads_in_list_N = 0;
            $leads_in_list_Y = 0;
            $stmt = "SELECT status, if(called_count >= 100, 100, called_count), count(*) from vicidial_list where list_id='$list_id' group by status, if(called_count >= 100, 100, called_count) order by status,called_count";
            $rslt = sv_mysqli_query($con, $stmt);
            $status_called_to_print = sv_mysqli_num_rows($rslt);
            $o = 0;
            $sts = 0;
            $first_row = 1;
            $all_called_first = 1000;
            $all_called_last = 0;
            $leads_in_sts = array();
            $status = array();
            $all_called_count = array();
            while ($status_called_to_print > $o) {
                $rowx = sv_mysqli_fetch_array($rslt);
                $leads_in_list = ($leads_in_list + $rowx[2]);
                $count_statuses[$o] = $rowx[0];
                $count_called[$o] = $rowx[1];
                $count_count[$o] = 0;
                $count_count[$o] = $rowx[2];

                if (!array_key_exists($rowx[1], $all_called_count)) {
                    $all_called_count[$rowx[1]] = 0;
                }
                $all_called_count[$rowx[1]] = ($all_called_count[$rowx[1]] + $rowx[2]);
                if (!array_key_exists($sts, $status) or (strlen($status[$sts]) < 1) or ($status[$sts] != "$rowx[0]")) {
                    if ($first_row) {
                        $first_row = 0;
                    } else {
                        $sts++;
                    }

                    $status[$sts] = "$rowx[0]";
                    $status_called_first[$sts] = "$rowx[1]";
                    if ($status_called_first[$sts] < $all_called_first) {
                        $all_called_first = $status_called_first[$sts];
                    }
                }
                if (!array_key_exists($sts, $leads_in_sts)) {
                    $leads_in_sts[$sts] = 0;
                }
                $leads_in_sts[$sts] = ($leads_in_sts[$sts] + $rowx[2]);
                $status_called_last[$sts] = "$rowx[1]";
                if ($status_called_last[$sts] > $all_called_last) {
                    $all_called_last = $status_called_last[$sts];
                }

                $o++;
            }
            //echo("11\n");
            $first = $all_called_first;
            $sal["Tabla5"] = array();
            $donde = 0;
            $sts = 0;
            $sal["Tabla5"]["Registros"] = array();
            $statuses_called_to_print = count($status);
            while ($statuses_called_to_print > $sts) {
                $Pstatus = $status[$sts];
                //Codigo del status
                $codigoStatus = $Pstatus;
                //Se valida que no sea nulo
                if ($Pstatus != " " && $Pstatus != null && $Pstatus != "") {
                    //Nombre del Status
                    $nombreStatus = $statuses_list[$Pstatus];
                    $sal["Tabla5"]["Registros"][$donde]["Status"] = $codigoStatus;
                    $sal["Tabla5"]["Registros"][$donde]["NombreStatus"] = $nombreStatus;
                    $sal["Tabla5"]["Registros"][$donde]["Pasadas"] = array();
                    //$sal["Tabla5"]["Registros"][$donde][$Pstatus] = $statuses_list[$Pstatus];
                    $first = $all_called_first;
                    while ($first <= $all_called_last) {
                        $called_printed = 0;
                        $o = 0;
                        while ($status_called_to_print > $o) {
                            if (($count_statuses[$o] == "$Pstatus") and ($count_called[$o] == "$first")) {
                                $called_printed++;
                                $sal["Tabla5"]["Registros"][$donde]["Pasadas"][] = $count_count[$o];
                                //$sal["Tabla5"]["Registros"][$donde][$called_printed - 1] = $count_count[$o];
                            } else {
                                //$sal["Tabla5"]["Registros"][$donde]["Pasadas"][$p] = 0;
                            }
                            $o++;
                        }
                        if (!$called_printed) {
                            $sal["Tabla5"]["Registros"][$donde]["Pasadas"][] = 0;
                        }

                        $first++;
                    }
                    $sal["Tabla5"]["Registros"][$donde]["subtotal"] = $leads_in_sts[$sts];
                    $donde++;
                }
                $sts++;
                $sal["Tabla5"]["cuantos"] = $donde;
            }
            //echo("12\n");
            $first = $all_called_first;
            $donde = 0;
            while ($first <= $all_called_last) {
                if (!array_key_exists($first, $all_called_count)) {
                    $all_called_count[$first] = 0;
                }

                $sal["Tabla5"]["total"]["Registros"][$donde++] = $all_called_count[$first];
                $first++;
            }
            //echo("13\n");
            $sal["Tabla5"]["total"]["total"] = $leads_in_list;

            $crm = CRMDatos::getCRMByLista($lista);

            if ($crm != null) {
                $sal["CRM"] = $crm->toJSON();
            }

            //$this->output->set_output(json_encode($sal,JSON_UNESCAPED_UNICODE ));
            sv_mysqli_close($con);
            $this->output->set_output(json_encode($sal, JSON_UNESCAPED_UNICODE));
            //echo(json_encode($sal,JSON_UNESCAPED_UNICODE ));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getLists()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $pagina = $_POST["pagina"] - 1;
            $registros = 10;
            $campana = "campaign_id";
            $skip = $registros * $pagina;
            if (isset($_POST["campana"]) && $_POST["campana"] != -1) {
                $campana = "'" . limpia($_POST["campana"]) . "'";
            }
            $and = "AND user_group = '" . $_SESSION["Cliente"] . "'";
            if ($_SESSION["Cliente"] == -1) {
                $and = "";
            }

            $textoBusqueda = "";
            if (isset($_POST["texto"])) {
                $textoBusqueda = limpia($_POST["texto"]);
            }
            $query = "SELECT active, list_id,list_name,list_description,list_lastcalldate,(SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id LIMIT 1) AS campaign_id FROM vicidial_lists WHERE campaign_id = $campana AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $and) AND list_name LIKE '%$textoBusqueda%' ORDER BY list_id DESC LIMIT $skip,$registros";
            $result = sv_mysqli_query($con, $query);
            $sal["Estado"] = "ok";
            $sal["Listas"] = array();
            $sal["Query"] = $query;
            $sal["Error"] = mysqli_error($con);
            while ($row = $result->fetch_assoc()) {
                $objeto = array();
                $objeto["active"] = $row["active"];
                $objeto["list_id"] = $row["list_id"];
                $objeto["list_name"] = $row["list_name"];
                $objeto["list_description"] = $row["list_description"];
                $objeto["list_lastcalldate"] = $row["list_lastcalldate"];
                $objeto["campaign_id"] = $row["campaign_id"];
                $objeto["Status"] = array();
                $queryInterno = "SELECT DISTINCT status AS estado,(SELECT COUNT(lead_id) FROM vicidial_list WHERE list_id='" . $row["list_id"] . "' AND status=estado) AS cuenta FROM vicidial_list WHERE list_id = '" . $row["list_id"] . "' ORDER BY FIELD(estado,'NEW') ASC,cuenta DESC";
                $resultInterno = sv_mysqli_query($con, $queryInterno);
                while ($rowInterno = sv_mysqli_fetch_array($resultInterno)) {
                    $objeto["Status"][] = $rowInterno;
                }
                $sal["Listas"][] = $objeto;
            }
            $query = "SELECT count(list_id) AS Cuenta FROM vicidial_lists WHERE campaign_id = $campana AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $and) AND list_name LIKE '%$textoBusqueda%' ";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $sal["Cuenta"] = $row["Cuenta"];
            $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 getListsSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        $tiempoPeticion = time();
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $campana = "campaign_id";
            if (isset($_POST["campana"]) && $_POST["campana"] != -1) {
                $campana = "'" . limpia($_POST["campana"]) . "'";
            }
            $and = "";
            if ($_SESSION["Cliente"] != -1) {
                //$and = "AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '".$_SESSION["Cliente"]."')";
                $campanasXD = "";
                $query = "SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '" . $_SESSION["Cliente"] . "'";
                $result = sv_mysqli_query($con, $query);
                while ($row = sv_mysqli_fetch_array($result)) {
                    $campanasXD = $campanasXD . "'" . $row["campaign_id"] . "',";
                }
                if ($campanasXD != "") {
                    $campanasXD = substr($campanasXD, 0, -1);
                    $and = "AND campaign_id IN ($campanasXD)";
                } else {
                    $and = "AND 1 = 2";
                }
            }
            $query = "SELECT list_id,list_name FROM vicidial_lists WHERE campaign_id = $campana $and AND active = 'Y' ORDER BY list_name";
            $result = sv_mysqli_query($con, $query);
            $sal["Estado"] = "ok";
            $sal["Listas"] = array();
            while ($row = $result->fetch_assoc()) {
                $sal["Listas"][] = $row;
            }
            $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 getLeadsSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $lista = limpia($_POST["lista"]);
            $query = "SELECT list_name FROM vicidial_lists WHERE list_id = '$lista' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            $sal = array();
            if ($row = sv_mysqli_fetch_array($result)) {
                $list_name = $row["list_name"];
                $query = "SELECT * FROM vicidial_list WHERE list_id = '$lista'";
                $result = sv_mysqli_query($con, $query);
                $sal["Estado"] = "ok";
                $sal["Registros"] = array();
                while ($row1 = sv_mysqli_fetch_array($result)) {
                    $sal["Registros"][] = $row1;
                }
            } else {
                $sal["Estado"] = "error";
            }
            $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 getLeads()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $lista = limpia($_GET["lista"]);
            $sal = array();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $andStatus = "";
            if (isset($_GET["status"])) {
                $andStatus = "AND status = '" . limpia($_GET["status"]) . "'";
            }
            $query = "SELECT list_id,list_name FROM vicidial_lists WHERE list_id = '$lista' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $donde)  LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $list_name = $row["list_name"];
                $csv = false;
                if (isset($_GET["csv"])) {
                    $csv = true;
                }
                $queryFecha = "";
                if (isset($_GET["fechaIni"])) {
                    $fechaIni = limpia($_GET["fechaIni"]);
                    $fechaFin = $fechaIni;
                    if (isset($_GET["fechaFin"])) {
                        $fechaFin = limpia($_GET["fechaFin"]);
                    }

                    $queryFecha = "AND entry_date BETWEEN '$fechaIni 00:00:00' AND '$fechaFin 23:59:59'";

                }
                $query = "SELECT * FROM vicidial_list WHERE list_id = '$lista' $andStatus $queryFecha";
                $result = sv_mysqli_query($con, $query, MYSQLI_ASSOC);
                $out = "";
                $sal["Registros"] = array();
                $stmtNombres = "SELECT '{$this->lang->line('header_uploadLeads_label_lead_id')}' AS label_lead_id, '{$this->lang->line('header_uploadLeads_label_entry_date')}' AS label_entry_date, '{$this->lang->line('header_uploadLeads_label_modify_date')}' AS label_modify_date, '{$this->lang->line('header_uploadLeads_label_status')}' AS label_status, '{$this->lang->line('header_uploadLeads_label_user')}' AS label_user, '{$this->lang->line('header_uploadLeads_label_list_id')}' AS label_list_id, '{$this->lang->line('header_uploadLeads_label_called_since_last_reset')}' AS label_called_since_last_reset, '{$this->lang->line('header_uploadLeads_label_gmt_offset_now')}' AS label_gmt_offset_now, '{$this->lang->line('header_uploadLeads_label_phone_code')}' AS label_phone_code, '{$this->lang->line('header_uploadLeads_label_date_of_birth')}' AS label_date_of_birth,'{$this->lang->line('header_uploadLeads_label_called_count')}' AS label_called_count, '{$this->lang->line('header_uploadLeads_label_last_local_call_time')}' AS label_last_local_call_time,'{$this->lang->line('header_uploadLeads_label_label_country_code')}' AS label_country_code,'{$this->lang->line('header_uploadLeads_label_label_rank')}' AS label_rank,'' AS source_id ,'{$this->lang->line('header_uploadLeads_label_owner')}' AS label_owner,'{$this->lang->line('header_uploadLeads_label_title')}' AS label_title,'{$this->lang->line('header_uploadLeads_label_first_name')}' AS label_first_name,'{$this->lang->line('header_uploadLeads_label_middle_initial')}' AS label_middle_initial,'{$this->lang->line('header_uploadLeads_label_last_name')}' AS label_last_name,'{$this->lang->line('header_uploadLeads_label_address1')}' AS label_address1,'{$this->lang->line('header_uploadLeads_label_address2')}' AS label_address2,'{$this->lang->line('header_uploadLeads_label_address3')}' AS label_address3,'{$this->lang->line('header_uploadLeads_label_city')}' AS label_city,'{$this->lang->line('header_uploadLeads_label_state')}' AS label_state,'{$this->lang->line('header_uploadLeads_label_province')}' AS label_province,'{$this->lang->line('header_uploadLeads_label_postal_code')}' AS label_postal_code,label_vendor_lead_code,'{$this->lang->line('header_uploadLeads_label_gender')}' AS label_gender,'{$this->lang->line('header_uploadLeads_label_phone_number')}' AS label_phone_number,'{$this->lang->line('header_uploadLeads_label_alt_phone')}' AS label_alt_phone,label_security_phrase,'{$this->lang->line('header_uploadLeads_label_email')}' AS label_email,'{$this->lang->line('header_uploadLeads_label_comments')}' AS label_comments 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 (isset($nombre["Usuario"]) && $nombre["Usuario"] == "VDAD") {
                        $nombre["Usuario"] = "SISTEMA";
                    }
                    if (isset($nombre["User"]) && $nombre["User"] == "VDAD") {
                        $nombre["User"] = "SYSTEM";
                    }
                }
                if ($csv) {
                    header("Content-type: text/csv");
                    header("Content-Disposition: attachment; filename=\"Leads de la lista $list_name.csv\"");
                    header("Pragma: no-cache");
                    header("Expires: 0");
                    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"] = "ok";
                    $this->output->set_output(json_encode($sal));
                }
            } else {
                $sal["Estado"] = "error";
                $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 getStrings()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $stmt = "SELECT label_title,label_first_name,label_middle_initial,label_last_name,label_address1,label_address2,label_address3,label_city,label_state,label_province,label_postal_code,label_vendor_lead_code,label_gender,label_phone_number,label_alt_phone,label_security_phrase,label_email,label_comments from system_settings;";
            $result = sv_mysqli_query($con, $stmt);
            $row = sv_mysqli_fetch_array($result);
            $sal["estado"] = "ok";
            $sal["estados"] = $row;
            $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 deleteList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $linea = 0;
            $list_id = $_POST["lista"];
            $sal = array();
            $con = getConnection();
            $and = "WHERE user_group = '" . $_SESSION["Cliente"] . "'";
            if ($_SESSION["Cliente"] == -1) {
                $and = "";
            }
            $query = "SELECT list_id FROM vicidial_lists WHERE list_id = '$list_id' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns $and) LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                if (strlen($list_id) >= 2) {
                    $stmt = "DELETE from vicidial_lists where list_id='$list_id' limit 1";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_hopper where list_id='$list_id'";
                    sv_mysqli_query($con, $stmt);
                    $stmt = "DELETE from vicidial_list where list_id='$list_id'";
                    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='DELETE', record_id='$list_id', event_code='ADMIN DELETE LIST', event_sql=\"$SQL_log\", event_notes=''";
                    sv_mysqli_query($con, $stmt);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_idLista2");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEliminar");
            }
            $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 analizeFile()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $listaMVC = ListaDatos::getListaById($_POST["lista"]);
            if ($listaMVC->getCRM() == null) {
                $stmt = "SELECT '{$this->lang->line('header_uploadLeads_label_label_country_code')}' AS label_country_code,'{$this->lang->line('header_uploadLeads_label_label_rank')}' AS label_rank,'' AS source_id ,'{$this->lang->line('header_uploadLeads_label_owner')}' AS label_owner,'{$this->lang->line('header_uploadLeads_label_title')}' AS label_title,'{$this->lang->line('header_uploadLeads_label_first_name')}' AS label_first_name,'{$this->lang->line('header_uploadLeads_label_middle_initial')}' AS label_middle_initial,'{$this->lang->line('header_uploadLeads_label_last_name')}' AS label_last_name,'{$this->lang->line('header_uploadLeads_label_address1')}' AS label_address1,'{$this->lang->line('header_uploadLeads_label_address2')}' AS label_address2,'{$this->lang->line('header_uploadLeads_label_address3')}' AS label_address3,'{$this->lang->line('header_uploadLeads_label_city')}' AS label_city,'{$this->lang->line('header_uploadLeads_label_state')}' AS label_state,'{$this->lang->line('header_uploadLeads_label_province')}' AS label_province,'{$this->lang->line('header_uploadLeads_label_postal_code')}' AS label_postal_code,label_vendor_lead_code,'{$this->lang->line('header_uploadLeads_label_gender')}' AS label_gender,'{$this->lang->line('header_uploadLeads_label_phone_number')}' AS label_phone_number,'{$this->lang->line('header_uploadLeads_label_alt_phone')}' AS label_alt_phone,label_security_phrase,'{$this->lang->line('header_uploadLeads_label_email')}' AS label_email,'{$this->lang->line('header_uploadLeads_label_comments')}' AS label_comments from system_settings";
                $result = sv_mysqli_query($con, $stmt, MYSQLI_ASSOC);
                $row = sv_mysqli_fetch_array($result);
                $claves = array_keys($row);
            } else {
                $claves = CampoDatos::getCamposByCRM($listaMVC->getCRM());
            }
            if (($gestor = fopen($_FILES['csv']['tmp_name'], "r")) !== false) {
                $datos = fgetcsv($gestor, 100000, ",");
                $sal["cabezeras"] = $datos;
                $sal["Estado"] = "ok";
                $sal["estados"] = array();
                for ($i = 0; $i < count($claves); $i++) {
                    if ($listaMVC->getCRM() == null) {
                        if ($row[$claves[$i]] == "") {
                            $temp = $claves[$i];
                            $temp = str_replace("label_", "", $temp);
                            $temp = str_replace("_", " ", $temp);
                            $sal["estados"][$i]["Estado"] = $temp;
                        } else {
                            $sal["estados"][$i]["Estado"] = $row[$claves[$i]];
                        }
                        $sal["estados"][$i]["Nombre"] = str_replace("label_", "", $claves[$i]);
                        $sal["estados"][$i]["Equivalencia"] = null;
                        for ($j = 0; $j < count($datos); $j++) {
                            if (
                                strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                                strtolower($datos[$j]) == strtolower($row[$claves[$i]]) ||
                                strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"]) ||
                                strtolower($datos[$j]) == strtolower(str_replace("label_", "", str_replace("_", " ", $claves[$i]))) ||
                                strtolower($datos[$j]) == strtolower(str_replace("label_", "", $claves[$i])) ||
                                strtolower(str_replace(" ", "_", $datos[$j])) == strtolower($row[$claves[$i]])
                            ) {
                                $sal["estados"][$i]["Equivalencia"] = $j;
                            }
                        }
                    } else {
                        $sal["estados"][$i]["Nombre"] = $claves[$i]->getId();
                        $sal["estados"][$i]["Estado"] = str_replace("label_", "", $claves[$i]->getNombre());
                        $sal["estados"][$i]["Equivalencia"] = null;
                        for ($j = 0; $j < count($datos); $j++) {
                            if (
                                strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                                strtolower($datos[$j]) == strtolower($claves[$i]->getId()) ||
                                strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"]) ||
                                strtolower(str_replace(" ", "_", $datos[$j])) == strtolower($claves[$i]->getNombre())
                            ) {
                                $sal["estados"][$i]["Equivalencia"] = $j;
                            }
                        }
                    }
                }
                if ($listaMVC->getCRM() != null) {
                    $i = count($claves);
                    $sal["estados"][$i]["Nombre"] = "vendor_lead_code";
                    $sal["estados"][$i]["Estado"] = "Vendor lead code";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "first_name";
                    $sal["estados"][$i]["Estado"] = "Nombre";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "last_name";
                    $sal["estados"][$i]["Estado"] = "Apellidos";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "email";
                    $sal["estados"][$i]["Estado"] = "Correo";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "address1";
                    $sal["estados"][$i]["Estado"] = "Direccion";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "postal_code";
                    $sal["estados"][$i]["Estado"] = "Codigo postal";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "phone_number";
                    $sal["estados"][$i]["Estado"] = "Telefono";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "alt_phone";
                    $sal["estados"][$i]["Estado"] = "Telefono alterno";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "address3";
                    $sal["estados"][$i]["Estado"] = "Telefono alterno 2";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                    $sal["estados"][$i]["Nombre"] = "rank";
                    $sal["estados"][$i]["Estado"] = "Rango";
                    for ($j = 0; $j < count($datos); $j++) {
                        if (
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Nombre"]) ||
                            strtolower($datos[$j]) == strtolower($sal["estados"][$i]["Estado"])
                        ) {
                            $sal["estados"][$i]["Equivalencia"] = $j;
                        }
                    }
                    $i++;
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_archivoInvalido");
            }

            $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 deleteLeads()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $list_id = limpia($_POST["lista"]);
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }

            $query = "SELECT list_id,campaign_id FROM vicidial_lists WHERE list_id = '$list_id' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $donde) LIMIT 1";
            $result = sv_mysqli_query($con, $query, MYSQLI_ASSOC);
            $sal["Estado"] = "ok";
            $sal["Errores"] = array();
            if ($row = sv_mysqli_fetch_array($result)) {
                $gestor = fopen($_FILES["csv"]["tmp_name"], "r");
                if ($encabezado = fgetcsv($gestor)) {
                    $telefonoInd = -1;
                    $fila = 2;
                    foreach ($encabezado as $key => $val) {
                        if (strtolower($val) == "telefono") {
                            $telefonoInd = $key;
                        }
                    }
                    if ($telefonoInd != -1) {
                        while ($datos = fgetcsv($gestor)) {
                            $telefono = $datos[$telefonoInd];
                            $query = "DELETE FROM vicidial_list WHERE (phone_number='$telefono' OR alt_phone='$telefono' OR address3='$telefono') AND list_id='$list_id'";
                            sv_mysqli_query($con, $query);
                            if (mysqli_affected_rows($con) == 0) {
                                $sal["Errores"][] = array("Fila" => $fila, "Telefono" => $telefono);
                            }
                            $fila++;
                        }

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

                    }
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_archivoVacio");
                }
                fclose($gestor);
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosAgregarRegistros");
            }
            $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 uploadLeads()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $list_id = limpia($_POST["lista"]);
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $sinDuplicados = limpia($_POST["duplicado"]);
            $modoEstricto = limpia($_POST["estricto"]);
            if ($modoEstricto == "Y") {
                $modoEstricto = true;
            } else {
                $modoEstricto = false;
            }

            $query = "SELECT list_id,campaign_id FROM vicidial_lists WHERE list_id = '$list_id' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $donde) LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            $linea = 0;
            $querys = array();
            $idblacklist = null;
            $sal["Estado"] = "ok";
            if ($row = sv_mysqli_fetch_array($result)) {
                $listaMVC = ListaDatos::getListaById($list_id);
                $respuestas = $estadosPendejos = array();
                $fechaMysql = GestionDatos::getFecha();
                if ($listaMVC->getCRM() != null) {
                    $gestionDummy = new Gestion(null, $listaMVC->getCRM(), "1111", $fechaMysql, "9999999999", UsuarioDatos::getUsuarioByUsuario($_SESSION["Usuario"]), "NEW");
                    $campos = CampoDatos::getCamposByCRM($listaMVC->getCRM());
                }
                $query = "SELECT idblacklist FROM vicidial_tables_windows WHERE campaign_id={$row["campaign_id"]} LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($result !== false) {
                    $row = sv_mysqli_fetch_array($result);
                    $idblacklist = $row["idblacklist"];
                }
                if (($gestor = fopen($_FILES['csv']['tmp_name'], "r")) !== false) {
                    if ($listaMVC->getCRM() == null) {
                        $comments = limpia($_POST["comments"]);
                        $source_id = limpia($_POST["source_id"]);
                        $title = limpia($_POST["title"]);
                        $owner = limpia($_POST["owner"]);
                        $address2 = limpia($_POST["address2"]);
                        $state = limpia($_POST["state"]);
                        $province = limpia($_POST["province"]);
                        $middle_initial = limpia($_POST["middle_initial"]);
                        $country_code = limpia($_POST["country_code"]);
                        $security = limpia($_POST["security_phrase"]);
                        $owner = limpia($_POST["owner"]);
                        $city = limpia($_POST["city"]);
                    } else {
                        $comments = $source_id = $title = $owner = $address2 = $state = $province = $middle_initial = $country_code = $security = $owner = $city = -1;
                    }
                    $alt_phone = limpia($_POST["alt_phone"]);
                    $email = limpia($_POST["email"]);
                    $address3 = limpia($_POST["address3"]);
                    $postal_code = limpia($_POST["postal_code"]);
                    $vendor_lead_code = limpia($_POST["vendor_lead_code"]);
                    $phone_number = limpia($_POST["phone_number"]);
                    $first_name = limpia($_POST["first_name"]);
                    $last_name = limpia($_POST["last_name"]);
                    $address1 = limpia($_POST["address1"]);
                    $rank = limpia($_POST["rank"]);
                    $sal["erroneos"] = array();
                    $status = "NEW";
                    $inserts = "";
                    while (($datos = fgetcsv($gestor, 100000, ",")) !== false) {
                        $fallo = false;
                        $status = "NEW";
                        if ($linea != 0) {
                            if (array_key_exists($phone_number, $datos)) {
                                $sal["TELEFONO_LIMITE"] = TELEFONO_LIMITE;
                                $sal["TELEFONO"] = $datos[$phone_number];
                                if (
                                    $phone_number != -1 &&
                                    (strlen($datos[$phone_number]) >= 1 &&
                                        strlen($datos[$phone_number]) <= TELEFONO_LIMITE) &&
                                    preg_match('/^[0-9]{1,' . TELEFONO_LIMITE . '}$/', $datos[$phone_number])
                                ) {
                                    if ($sinDuplicados == 1) {
                                        $query = "SELECT lead_id FROM vicidial_list WHERE phone_number='" . $datos[$phone_number] . "' AND list_id='$list_id'";
                                        $result = sv_mysqli_query($con, $query);
                                    } else {
                                        $result = null;
                                    }
                                    if (!($sinDuplicados == 1 && $result !== null && sv_mysqli_num_rows($result) >= 1)) {
                                        if ($idblacklist == null) {
                                            $query = "INSERT INTO vicidial_list(status,title,source_id,first_name,middle_initial,last_name,address1,address2,address3,city,state,province,postal_code,country_code,alt_phone,phone_number,phone_code,email,security_phrase,comments,rank,owner,vendor_lead_code,entry_date,modify_date,date_of_birth,gmt_offset_now,list_id) VALUES (
                                            '$status','" .
                                                (($title != -1) ? limpia($datos[$title]) : " ") . "',
                                                '" . (($source_id != -1) ? limpia($datos[$source_id]) : " ") . "',
                                                '" . (($first_name != -1) ? limpia($datos[$first_name]) : " ") . "',
                                                '" . (($middle_initial != -1) ? limpia($datos[$middle_initial]) : " ") . "',
                                                '" . (($last_name != -1) ? limpia($datos[$last_name]) : " ") . "',
                                                '" . (($address1 != -1) ? limpia($datos[$address1]) : " ") . "',
                                                '" . (($address2 != -1) ? limpia($datos[$address2]) : " ") . "',
                                                '" . (($address3 != -1) ? limpia($datos[$address3]) : " ") . "',
                                                '" . (($city != -1) ? limpia($datos[$city]) : " ") . "',
                                                '" . (($state != -1) ? limpia($datos[$state]) : " ") . "',
                                                '" . (($province != -1) ? limpia($datos[$province]) : " ") . "',
                                                '" . (($postal_code != -1) ? limpia($datos[$postal_code]) : " ") . "',
                                                '" . (($country_code != -1) ? limpia($datos[$country_code]) : " ") . "',
                                                '" . (($alt_phone != -1) ? limpia($datos[$alt_phone]) : " ") . "',
                                                '" . (($phone_number != -1) ? limpia($datos[$phone_number]) : " ") . "',
                                                '52',
                                                '" . (($email != -1) ? limpia($datos[$email]) : " ") . "',
                                                '" . (($security != -1) ? limpia($datos[$security]) : " ") . "',
                                                '" . (($comments != -1) ? limpia($datos[$comments]) : " ") . "',
                                                '" . (($rank != -1) ? limpia($datos[$rank]) : "0") . "',
                                                '" . (($owner != -1) ? limpia($datos[$owner]) : " ") . "',
                                                '" . (($vendor_lead_code != -1) ? limpia($datos[$vendor_lead_code]) : " ") . "',
                                                NOW(),
                                                '0000-00-00 00:00:00',
                                                '0000-00-00 00:00:00',
                                                -6,
                                                '" . $list_id . "')";

                                            if ($modoEstricto || $listaMVC->getCRM() != null) {
                                                $querys[] = $query;
                                                if ($listaMVC->getCRM() != null) {
                                                    $estadosPendejos[] = $status;
                                                    $gestionDummy->setCalificacion($status);
                                                    $arregloPendejo = array();
                                                    for ($z = 0; $z < count($campos); $z++) {
                                                        $valorCRM = ($_POST[$campos[$z]->getId()] == -1 ? $campos[$z]->getValor() : $datos[$_POST[$campos[$z]->getId()]]);
                                                        $arregloPendejo[] = new Respuesta(null, $gestionDummy, $campos[$z], $valorCRM);
                                                    }
                                                    $respuestas[] = $arregloPendejo;
                                                }
                                            } else {
                                                $inserts .= "('$status','" .
                                                    (($title != -1) ? limpia($datos[$title]) : " ") . "',
                                                    '" . (($source_id != -1) ? limpia($datos[$source_id]) : " ") . "',
                                                    '" . (($first_name != -1) ? limpia($datos[$first_name]) : " ") . "',
                                                    '" . (($middle_initial != -1) ? limpia($datos[$middle_initial]) : " ") . "',
                                                    '" . (($last_name != -1) ? limpia($datos[$last_name]) : " ") . "',
                                                    '" . (($address1 != -1) ? limpia($datos[$address1]) : " ") . "',
                                                    '" . (($address2 != -1) ? limpia($datos[$address2]) : " ") . "',
                                                    '" . (($address3 != -1) ? limpia($datos[$address3]) : " ") . "',
                                                    '" . (($city != -1) ? limpia($datos[$city]) : " ") . "',
                                                    '" . (($state != -1) ? limpia($datos[$state]) : " ") . "',
                                                    '" . (($province != -1) ? limpia($datos[$province]) : " ") . "',
                                                    '" . (($postal_code != -1) ? limpia($datos[$postal_code]) : " ") . "',
                                                    '" . (($country_code != -1) ? limpia($datos[$country_code]) : " ") . "',
                                                    '" . (($alt_phone != -1) ? limpia($datos[$alt_phone]) : " ") . "',
                                                    '" . (($phone_number != -1) ? limpia($datos[$phone_number]) : " ") . "',
                                                    '52',
                                                    '" . (($email != -1) ? limpia($datos[$email]) : " ") . "',
                                                    '" . (($security != -1) ? limpia($datos[$security]) : " ") . "',
                                                    '" . (($comments != -1) ? limpia($datos[$comments]) : " ") . "',
                                                    '" . (($rank != -1) ? limpia($datos[$rank]) : "0") . "',
                                                    '" . (($owner != -1) ? limpia($datos[$owner]) : " ") . "',
                                                    '" . (($vendor_lead_code != -1) ? limpia($datos[$vendor_lead_code]) : " ") . "',
                                                    NOW(),
                                                    '0000-00-00 00:00:00',
                                                    '0000-00-00 00:00:00',
                                                    -6,
                                                    '" . $list_id . "'),";
                                            }
                                        } else {
                                            $result = sv_mysqli_query($con, "SELECT idblacklist FROM blacklisted_numbers WHERE idblacklist='$idblacklist' AND number='{$datos[$phone_number]}'");
                                            if ($row = sv_mysqli_fetch_array($result)) {
                                                $status = "DNC";
                                            }
                                            $result = sv_mysqli_query($con, "SELECT idblacklist FROM blacklisted_lead_code WHERE idblacklist='$idblacklist' AND vendor_lead_code='" . (($vendor_lead_code != -1) ? $datos[$vendor_lead_code] : " ") . "'");
                                            if ($row = sv_mysqli_fetch_array($result)) {
                                                $status = "DNC";
                                            }
                                            $query = "INSERT INTO vicidial_list(status,title,source_id,first_name,middle_initial,last_name,address1,address2,address3,city,state,province,postal_code,country_code,alt_phone,phone_number,phone_code,email,security_phrase,comments,rank,owner,vendor_lead_code,entry_date,modify_date,date_of_birth,gmt_offset_now,list_id) VALUES (
                                            '$status','" .
                                                (($title != -1) ? limpia($datos[$title]) : " ") . "',
                                                '" . (($source_id != -1) ? limpia($datos[$source_id]) : " ") . "',
                                                '" . (($first_name != -1) ? limpia($datos[$first_name]) : " ") . "',
                                                '" . (($middle_initial != -1) ? limpia($datos[$middle_initial]) : " ") . "',
                                                '" . (($last_name != -1) ? limpia($datos[$last_name]) : " ") . "',
                                                '" . (($address1 != -1) ? limpia($datos[$address1]) : " ") . "',
                                                '" . (($address2 != -1) ? limpia($datos[$address2]) : " ") . "',
                                                '" . (($address3 != -1) ? limpia($datos[$address3]) : " ") . "',
                                                '" . (($city != -1) ? limpia($datos[$city]) : " ") . "',
                                                '" . (($state != -1) ? limpia($datos[$state]) : " ") . "',
                                                '" . (($province != -1) ? limpia($datos[$province]) : " ") . "',
                                                '" . (($postal_code != -1) ? limpia($datos[$postal_code]) : " ") . "',
                                                '" . (($country_code != -1) ? limpia($datos[$country_code]) : " ") . "',
                                                '" . (($alt_phone != -1) ? limpia($datos[$alt_phone]) : " ") . "',
                                                '" . (($phone_number != -1) ? limpia($datos[$phone_number]) : " ") . "',
                                                '52',
                                                '" . (($email != -1) ? limpia($datos[$email]) : " ") . "',
                                                '" . (($security != -1) ? limpia($datos[$security]) : " ") . "',
                                                '" . (($comments != -1) ? limpia($datos[$comments]) : " ") . "',
                                                '" . (($rank != -1) ? limpia($datos[$rank]) : "0") . "',
                                                '" . (($owner != -1) ? limpia($datos[$owner]) : " ") . "',
                                                '" . (($vendor_lead_code != -1) ? limpia($datos[$vendor_lead_code]) : " ") . "',
                                                NOW(),
                                                '0000-00-00 00:00:00',
                                                '0000-00-00 00:00:00',
                                                -6,
                                                '" . $list_id . "')";

                                            if ($modoEstricto || $listaMVC->getCRM() != null) {
                                                $querys[] = $query;
                                                if ($listaMVC->getCRM() != null) {
                                                    $estadosPendejos[] = $status;
                                                    $gestionDummy->setCalificacion($status);
                                                    $arregloPendejo = array();
                                                    for ($z = 0; $z < count($campos); $z++) {
                                                        $valorCRM = ($_POST[$campos[$z]->getId()] == -1 ? $campos[$z]->getValor() : $datos[$_POST[$campos[$z]->getId()]]);
                                                        $arregloPendejo[] = new Respuesta(null, $gestionDummy, $campos[$z], $valorCRM);
                                                    }
                                                    $respuestas[] = $arregloPendejo;
                                                }
                                            } else {
                                                $inserts .= "('$status','" .
                                                    (($title != -1) ? limpia($datos[$title]) : " ") . "',
                                                    '" . (($source_id != -1) ? limpia($datos[$source_id]) : " ") . "',
                                                    '" . (($first_name != -1) ? limpia($datos[$first_name]) : " ") . "',
                                                    '" . (($middle_initial != -1) ? limpia($datos[$middle_initial]) : " ") . "',
                                                    '" . (($last_name != -1) ? limpia($datos[$last_name]) : " ") . "',
                                                    '" . (($address1 != -1) ? limpia($datos[$address1]) : " ") . "',
                                                    '" . (($address2 != -1) ? limpia($datos[$address2]) : " ") . "',
                                                    '" . (($address3 != -1) ? limpia($datos[$address3]) : " ") . "',
                                                    '" . (($city != -1) ? limpia($datos[$city]) : " ") . "',
                                                    '" . (($state != -1) ? limpia($datos[$state]) : " ") . "',
                                                    '" . (($province != -1) ? limpia($datos[$province]) : " ") . "',
                                                    '" . (($postal_code != -1) ? limpia($datos[$postal_code]) : " ") . "',
                                                    '" . (($country_code != -1) ? limpia($datos[$country_code]) : " ") . "',
                                                    '" . (($alt_phone != -1) ? limpia($datos[$alt_phone]) : " ") . "',
                                                    '" . (($phone_number != -1) ? limpia($datos[$phone_number]) : " ") . "',
                                                    '52',
                                                    '" . (($email != -1) ? limpia($datos[$email]) : " ") . "',
                                                    '" . (($security != -1) ? limpia($datos[$security]) : " ") . "',
                                                    '" . (($comments != -1) ? limpia($datos[$comments]) : " ") . "',
                                                    '" . (($rank != -1) ? limpia($datos[$rank]) : "0") . "',
                                                    '" . (($owner != -1) ? limpia($datos[$owner]) : " ") . "',
                                                    '" . (($vendor_lead_code != -1) ? limpia($datos[$vendor_lead_code]) : " ") . "',
                                                    NOW(),
                                                    '0000-00-00 00:00:00',
                                                    '0000-00-00 00:00:00',
                                                    -6,
                                                    '" . $list_id . "'),";
                                            }
                                        }
                                    } else {
                                        $objeto = array();
                                        $objeto["Linea"] = ($linea + 1);
                                        if ($phone_number != -1) {
                                            $objeto["Telefono"] = $datos[$phone_number];
                                        } else {
                                            $objeto["Telefono"] = "";
                                        }

                                        $sal["erroneos"][] = $objeto;
                                    }
                                } else {
                                    $fallo = true;
                                    $objeto = array();
                                    $objeto["Linea"] = ($linea + 1);
                                    if ($phone_number != -1) {
                                        $objeto["Telefono"] = $datos[$phone_number];
                                    } else {
                                        $objeto["Telefono"] = "";
                                    }

                                    $sal["erroneos"][] = $objeto;
                                }
                            } else {
                                $fallo = true;
                                $objeto = array();
                                $objeto["Linea"] = ($linea + 1);
                                if ($phone_number != -1) {
                                    $objeto["Telefono"] = $datos[$phone_number];
                                } else {
                                    $objeto["Telefono"] = "";
                                }

                                $sal["erroneos"][] = $objeto;
                            }
                        }
                        $linea++;
                        if ($fallo && $modoEstricto) {
                            $sal["Estado"] = "error";
                            $sal["Descripcion"] = $this->lang->line("desc_registrosErroneos");
                            break;
                        }
                    }
                    fclose($gestor);
                    if ($sal["Estado"] != "error") {
                        if (strlen($inserts) != 0) {
                            $inserts = substr($inserts, 0, -1);
                            $query = "INSERT INTO vicidial_list(status,title,source_id,first_name,middle_initial,last_name,address1,address2,address3,city,state,province,postal_code,country_code,alt_phone,phone_number,phone_code,email,security_phrase,comments,rank,owner,vendor_lead_code,entry_date,modify_date,date_of_birth,gmt_offset_now,list_id) VALUES $inserts";
                            sv_mysqli_query($con, $query);
                        }
                        $sal["Estado"] = "ok";
                        $sal["total"] = $linea - 1;
                        $sal["lista"] = $list_id;
                        for ($i = 0; $i < count($querys); $i++) {
                            sv_mysqli_query($con, $querys[$i]);
                            if ($listaMVC->getCRM() != null) {
                                $nuevaGestion = new Gestion(null, $listaMVC->getCRM(), mysqli_insert_id($con), $fechaMysql, "9999999999", UsuarioDatos::getUsuarioByUsuario($_SESSION["Usuario"]), $estadosPendejos[$i]);
                                $id = GestionDatos::addGestion($nuevaGestion);
                                $nuevaGestion->setId($id);
                                for ($j = 0; $j < count($respuestas[$i]); $j++) {
                                    $respuestas[$i][$j]->setGestion($nuevaGestion);
                                    $respuestas[$i][$j]->setId(RespuestaDatos::insertRespuesta($respuestas[$i][$j]));
                                }
                            }
                        }
                    }
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_archivoInvalido");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosAgregarRegistros");
            }
            $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 addLead()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $list_id = limpia($_POST["lista"]);
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT list_id FROM vicidial_lists WHERE list_id = '$list_id' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $donde) LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $phone_number = limpia($_POST["phone_number"]);
                $phone_number = preg_replace('/[^0-9]/', '', $phone_number);
                if (strlen($phone_number) >= 6) {
                    $list_id = limpia($_POST["lista"]);
                    $comments = preg_replace("/\n/", '!N', $_POST["comments"]);
                    $comments = preg_replace("/\r/", '', $comments);
                    $comments = limpia($comments);
                    $status = limpia($_POST["status"]);
                    $title = limpia($_POST["title"]);
                    $first_name = limpia($_POST["first_name"]);
                    $last_name = limpia($_POST["last_name"]);
                    $address1 = limpia($_POST["address1"]);
                    $vendor_id = limpia($_POST["vendor_id"]);
                    $owner = limpia($_POST["owner"]);
                    $address2 = limpia($_POST["address2"]);
                    $address3 = limpia($_POST["address3"]);
                    $state = limpia($_POST["state"]);
                    $province = limpia($_POST["province"]);
                    $middle_initial = limpia($_POST["middle_initial"]);
                    $phone_code = limpia($_POST["phone_code"]);
                    $country_code = limpia($_POST["country_code"]);
                    $alt_phone = limpia($_POST["alt_phone"]);
                    $email = limpia($_POST["email"]);
                    $security = limpia($_POST["security"]);
                    $rank = limpia($_POST["rank"]);
                    $owner = limpia($_POST["owner"]);
                    $vendor_id = limpia($_POST["vendor_id"]);
                    $list_id = limpia($_POST["list_id"]);
                    $query = "INSERT INTO vicidial_list set status='" . $status . "',title='" . $title . "',
                        first_name='" . $first_name . "',
                        middle_initial='" . $middle_initial . "',
                        last_name='" . $last_name . "',
                        address1='" . $address1 . "',
                        address2='" . $address2 . "',
                        address3='" . $address3 . "',
                        city='" . $city . "',
                        modify_date = '0000-00-00 00:00:00',
                        state='" . $state . "',
                        province='" . $province . "',
                        postal_code='" . $postal_code . "',
                        country_code='" . $country_code . "',
                        alt_phone='" . $alt_phone . "',
                        phone_number='$phone_number',
                        phone_code='$phone_code',
                        email='" . $email . "',
                        security_phrase='" . $security . "',
                        comments='" . $comments . "',
                        rank='" . $rank . "',
                        owner='" . $owner . "',
                        vendor_lead_code='" . $vendor_id . "',
                        list_id='" . $list_id . "'";
                    sv_mysqli_query($con, $query);
                    $affected_rows = mysqli_affected_rows($con);
                    if ($affected_rows > 0) {
                        $sal["Estado"] = "ok";
                    } else {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_registroNoAgregado");
                    }
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_telefonoInvalido");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosAgregarLista");
            }
            $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 updateList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "WHERE user_group = '$cliente'";
            }
            $list_id = $_POST["id"];
            $campaign_id = $_POST["campana"];
            $query = "SELECT list_id FROM vicidial_lists WHERE list_id = '$list_id' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns $donde) LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $list_name = $_POST["nombre"];
                $list_description = $_POST["descripcion"];
                $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_listaInexistente");
                } else {
                    if ((strlen($campaign_id) < 2) or (strlen($list_name) < 2) or ($list_id < 100) or (strlen($list_id) > 19)) {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_idInvalido");
                    } else {
                        $stmt = "UPDATE vicidial_lists SET list_name = '$list_name', campaign_id = '$campaign_id', list_description = '$list_description', list_changedate = NOW() WHERE list_id = '$list_id' LIMIT 1";
                        $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='MODIFY', record_id='$list_id', event_code='ADMIN MODIFY LIST', event_sql=\"$SQL_log\", event_notes=''";
                        $rslt = sv_mysqli_query($con, $stmt);
                        $sal["Estado"] = "ok";
                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosAgregarLista");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosEditarLista");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function duplicateList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            //header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $lista = limpia($_POST["lista"]);
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT list_id FROM vicidial_lists WHERE list_id = '$lista' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_id $donde) LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                //$list_id = $_POST["id"];
                $query = "SELECT list_id FROM vicidial_lists ORDER BY list_id DESC LIMIT 1";
                $result1 = sv_mysqli_query($con, $query);
                if ($row1 = sv_mysqli_fetch_array($result1)) {
                    $list_id = $row1["list_id"] + 1;
                } else {
                    $list_id = 101;
                }
                $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_listaExistente");
                } else {
                    $stmt = "INSERT INTO vicidial_lists (list_id,list_name,campaign_id,active,list_description,list_changedate,list_lastcalldate,reset_time,agent_script_override,campaign_cid_override,am_message_exten_override,drop_inbound_group_override,xferconf_a_number,xferconf_b_number,xferconf_c_number,xferconf_d_number,xferconf_e_number,web_form_address,web_form_address_two,time_zone_setting,inventory_report,expiration_date,na_call_url,local_call_time,web_form_address_three,status_group_id,user_new_lead_limit,inbound_list_script_override,default_xfer_group) SELECT '$list_id',CONCAT(list_name,\"_\",\"duplicada\"),campaign_id,active,list_description,list_changedate,list_lastcalldate,reset_time,agent_script_override,campaign_cid_override,am_message_exten_override,drop_inbound_group_override,xferconf_a_number,xferconf_b_number,xferconf_c_number,xferconf_d_number,xferconf_e_number,web_form_address,web_form_address_two,time_zone_setting,inventory_report,expiration_date,na_call_url,local_call_time,web_form_address_three,status_group_id,user_new_lead_limit,inbound_list_script_override,default_xfer_group FROM vicidial_lists WHERE list_id = '$lista' LIMIT 1";
                    $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);

                    $queryLeadsLista = "SELECT * FROM vicidial_list WHERE list_id='$lista'";
                    $result = sv_mysqli_query($con, $queryLeadsLista);

                    $crm = ListaDatos::getListaById($lista)->getCRM();
                    $user = UsuarioDatos::getUsuarioByUsuario($usuario);

                    if ($crm != null) {
                        $queryUnirCRM = "INSERT INTO dialvox_crm_lista (Lista,CRM) VALUES ('" . limpia($list_id) . "','" . limpia($crm->getId()) . "')";
                        sv_mysqli_query($con, $queryUnirCRM);
                    }

                    while ($row = sv_mysqli_fetch_array($result)) {

                        $queryLead = "INSERT INTO vicidial_list (list_id,status,entry_date,modify_date,user,vendor_lead_code,source_id,gmt_offset_now,called_since_last_reset,phone_code,phone_number,title,first_name,middle_initial,last_name,address1,address2,address3,city,state,province,postal_code,country_code,gender,date_of_birth,alt_phone,email,security_phrase,comments,called_count,last_local_call_time,rank,owner,entry_list_id) VALUES ('$list_id','NEW',NOW(),'0000-00-00 00:00:00',NULL,'" . $row["vendor_lead_code"] . "','" . $row["source_id"] . "','" . $row["gmt_offset_now"] . "','N','" . $row["phone_code"] . "','" . $row["phone_number"] . "','" . $row["title"] . "','" . $row["first_name"] . "','" . $row["middle_initial"] . "','" . $row["last_name"] . "','" . $row["address1"] . "','" . $row["address2"] . "','" . $row["address3"] . "','" . $row["city"] . "','" . $row["state"] . "','" . $row["province"] . "','" . $row["postal_code"] . "','" . $row["country_code"] . "','" . $row["gender"] . "','" . $row["date_of_birth"] . "','" . $row["alt_phone"] . "','" . $row["email"] . "','" . $row["security_phrase"] . "','" . $row["comments"] . "','" . $row["called_count"] . "','" . $row["last_local_call_time"] . "','" . $row["rank"] . "','" . $row["owner"] . "','" . $row["entry_list_id"] . "')";

                        if (sv_mysqli_query($con, $queryLead)) {

                            if ($crm != null) {

                                $nuevaGestion = new Gestion(null, $crm, mysqli_insert_id($con), GestionDatos::getFecha(), "9999999999", UsuarioDatos::getUsuarioByUsuario($_SESSION["Usuario"]), 'NEW');
                                $id = GestionDatos::addGestion($nuevaGestion);
                                $nuevaGestion->setId($id);

                                $queryOgGestion = "SELECT id FROM dialvox_crm_gestion WHERE CRM = '" . limpia($crm->getId()) . "' AND Lead = '" . limpia($row["lead_id"]) . "' ORDER BY Fecha DESC LIMIT 1";
                                if ($result = sv_mysqli_query($con, $queryOgGestion)) {
                                    $ogGestion = sv_mysqli_fetch_array($result);
                                    $queryOgRespuestas = "SELECT id,Gestion,Campo,Respuesta FROM dialvox_crm_gestion_respuesta WHERE Gestion = '" . limpia($ogGestion["id"]) . "'";
                                    if ($result = sv_mysqli_query($con, $queryOgRespuestas)) {
                                        while ($ogRespuesta = sv_mysqli_fetch_array($result)) {
                                            $queryNuevaRespuesta = "INSERT INTO dialvox_crm_gestion_respuesta (Gestion, Campo, Respuesta) VALUES ('" . limpia($nuevaGestion->getId()) . "','" . limpia($ogRespuesta["Campo"]) . "','" . limpia($ogRespuesta["Respuesta"]) . "')";
                                            sv_mysqli_query($con, $queryNuevaRespuesta);
                                        }
                                    }
                                }
                            }
                        } else {
                            $sal["Err_Lead"][] = mysqli_error($con);
                        }

                    }

                    $sal["Estado"] = "ok";
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosAgregarLista");
            }
            $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 addList()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            //header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $campaign_id = $_POST["campana"];
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campaign_id' $donde LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                //$list_id = $_POST["id"];
                /*$query = "SELECT list_id FROM vicidial_lists ORDER BY list_id DESC LIMIT 1";
                $result1 = sv_mysqli_query($con,$query);
                if($row1 = sv_mysqli_fetch_array($result1)){
                $list_id = $row1["list_id"]+1;
                }else{
                $list_id = 101;
                }*/
                $hoy = getdate();
                if ($hoy["mday"] < 10) {
                    $hoy["mday"] = "0" . $hoy["mday"];
                }

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

                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 = $_POST["nombre"];
                $active = $_POST["activa"];
                $list_description = $_POST["descripcion"];
                $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_listaExistente");
                } else {
                    if ((strlen($list_name) < 2) or ($list_id < 100) or (strlen($list_id) > 19)) {
                        $sal["Estado"] = "error";
                        $sal["Descripcion"] = $this->lang->line("desc_idInvalido");
                    } else {
                        $stmt = "INSERT INTO vicidial_lists (list_id,list_name,campaign_id,active,list_description,list_changedate) values('$list_id','$list_name','$campaign_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);
                        $crm = null;
                        if (isset($_POST["crm"]) && $_POST["crm"] != null && $_POST["crm"] != "" && intval($_POST["crm"]) > 0) {
                            $crm = CRMDatos::getCRMById($_POST["crm"]);
                        }
                        if ($crm != null) {
                            $queryUnirCRM = "INSERT INTO dialvox_crm_lista (Lista,CRM) VALUES ('" . limpia($list_id) . "','" . limpia($crm->getId()) . "')";
                            sv_mysqli_query($con, $queryUnirCRM);
                        }
                        $sal["Estado"] = "ok";
                    }
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosAgregarLista");
            }
            $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 changeListStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $id = limpia($_POST["idLista"]);
            $and = "AND user_group = '" . $_SESSION["Cliente"] . "'";
            if ($_SESSION["Cliente"] == -1) {
                $and = "";
            }
            $query = "SELECT list_id FROM vicidial_lists WHERE list_id = '$id' AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = vicidial_lists.campaign_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_lists WHERE list_id = '$id' LIMIT 1");
                $row = sv_mysqli_fetch_array($result);
                $nuevo = 'Y';
                if ($row[0] == 'Y') {
                    $nuevo = 'N';
                }
                sv_mysqli_query($con, "UPDATE vicidial_lists SET active = '$nuevo' WHERE list_id = '$id' LIMIT 1");
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditarLista");
            }
            $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 searchLead()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];

            $and = "WHERE user_group = '" . $_SESSION["Cliente"] . "'";
            if ($_SESSION["Cliente"] == -1) {
                $and = "";
            }

            $sal = array();
            $con = getConnection();
            $case = -1;
            if (isset($_POST["vendor_lead_code"])) {
                $case = 0;
            } elseif (isset($_POST["phone_number"]) && isset($_POST["alt_phone_search"])) {
                $case = 1;
            } elseif (isset($_POST["lead_id"])) {
                $case = 2;
            } elseif (isset($_POST["status"]) || isset($_POST["list_id"]) || isset($_POST["user"]) || isset($_POST["owner"])) {
                $case = 3;
            } elseif (isset($_POST["log_lead_id"])) {
                $case = 4;
            } elseif (isset($_POST["log_phone"])) {
                $case = 5;
            } elseif (isset($_POST["log_lead_id_archive"])) {
                $case = 6;
            } elseif (isset($_POST["log_phone_archive"])) {
                $case = 7;
            }

            $result = null;
            if ($case != -1 && $case < 4) {
                $query = "SELECT lead_id,status,`user`,vendor_lead_code,list_id,phone_number,first_name,last_name,security_phrase,last_local_call_time,city  from vicidial_list";
                $where = "WHERE list_id IN (SELECT list_id FROM vicidial_lists WHERE campaign_id IN (SELECT campaign_id FROM vicidial_campaigns $and) ) ";
                switch ($case) {
                    case 0:
                        $where .= "  AND vendor_lead_code='" . limpia($_POST["vendor_lead_code"]) . "'";
                        break;
                    case 1:
                        if ($_POST["alt_phone_search"] == 1) {
                            $where .= " AND phone_number='" . limpia($_POST["phone_number"]) . "' AND  alt_phone='" . limpia($_POST["phone_number"]) . "' AND address3='" . limpia($_POST["phone_number"]) . "'";
                        } else {
                            $where .= " AND phone_number='" . limpia($_POST["phone_number"]) . "'";
                        }

                        break;
                    case 2:
                        $where .= " AND lead_id='" . limpia($_POST["lead_id"]) . "'";
                        break;
                    case 3:
                        if (isset($_POST["status"])) {
                            $where .= " AND status='" . limpia($_POST["status"]) . "' ";
                        }

                        if (isset($_POST["list_id"])) {
                            $where .= " AND status='" . limpia($_POST["list_id"]) . "' ";
                        }

                        if (isset($_POST["user"])) {
                            $where .= " AND user='" . limpia($_POST["user"]) . "' ";
                        }

                        if (isset($_POST["owner"])) {
                            $where .= " AND user='" . limpia($_POST["owner"]) . "' ";
                        }
                        break;
                }
                $result = sv_mysqli_query($con, "$query $where");
                $sal["leads"] = array();
                $i = 0;
                while ($row = sv_mysqli_fetch_array($result)) {
                    $sal["leads"][] = array(
                        "#" => $i,
                        "lead_id" => $row["lead_id"],
                        "status" => $row["status"],
                        "vendor_id" => $row["vendor_lead_code"],
                        "last_agent" => $row["user"],
                        "list_id" => $row["list_id"],
                        "phone" => $row["phone_number"],
                        "name" => $row["first_name"] . " " . $row["last_name"],
                        "city" => $row["city"],
                        "security" => $row["security_phrase"],
                        "last_call" => $row["last_local_call_time"]
                    );
                    $i++;
                }
                $sal["Estado"] = "ok";

            } elseif ($case != -1 && $case >= 4 && $case <= 7) {
                if ($case == 4 || $case == 6) {
                    $result1 = null;
                    $result2 = null;
                    if ($case == 4) {
                        $result1 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec,alt_dial from vicidial_log where lead_id='" . limpia($_POST["log_lead_id"]) . "'");
                        $result2 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec from vicidial_closer_log where lead_id='" . limpia($_POST["log_lead_id"]) . "'");
                    } else {
                        $result1 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec,alt_dial from vicidial_log_archive where lead_id='" . limpia($_POST["log_lead_id_archive"]) . "'");
                        $result2 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec from vicidial_closer_log_archive where lead_id='" . limpia($_POST["log_lead_id_archive"]) . "'");
                    }
                    $sal["logs"] = array();
                    $sal["logs"]["inbound"] = array();
                    $sal["logs"]["outbound"] = array();
                    $i = 0;
                    while ($row = sv_mysqli_fetch_array($result1)) {
                        $sal["logs"]["outbound"][] = array(
                            "#" => $i++,
                            "phone" => $row["phone_number"],
                            "campaign" => $row["campaign_id"],
                            "call_date" => $row["call_date"],
                            "status" => $row["status"],
                            "user" => $row["user"],
                            "list_id" => $row["list_id"],
                            "length" => $row["length_in_sec"],
                            "dial" => $row["alt_dial"]
                        );
                    }
                    $i = 0;
                    while ($row = sv_mysqli_fetch_array($result2)) {
                        $sal["logs"]["inbound"][] = array(
                            "#" => $i++,
                            "phone" => $row["phone_number"],
                            "campaign" => $row["campaign_id"],
                            "call_date" => $row["call_date"],
                            "status" => $row["status"],
                            "user" => $row["user"],
                            "list_id" => $row["list_id"],
                            "length" => $row["length_in_sec"]
                        );
                    }
                    $sal["Estado"] = "ok";
                } else {
                    $result1 = null;
                    $result2 = null;
                    $result3 = null;
                    if ($case == 5) {
                        $result1 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec,alt_dial from vicidial_log where phone_number='" . limpia($_POST["log_phone"]) . "'");
                        $result2 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec from vicidial_closer_log where phone_number='" . limpia($_POST["log_phone"]) . "'");
                        $result3 = sv_mysqli_query($con, "SELECT extension,caller_id_number,did_id,call_date from vicidial_did_log where caller_id_number='" . $_POST["log_phone"] . "'");
                    } else {
                        $result1 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec,alt_dial from vicidial_log_archive where phone_number='" . limpia($_POST["log_phone_archive"]) . "'");
                        $result2 = sv_mysqli_query($con, "SELECT lead_id,phone_number,campaign_id,call_date,status,user,list_id,length_in_sec from vicidial_closer_log_archive where phone_number='" . limpia($_POST["log_phone_archive"]) . "'");
                        $result3 = sv_mysqli_query($con, "SELECT extension,caller_id_number,did_id,call_date from vicidial_did_log where caller_id_number='" . limpia($_POST["log_phone_archive"]) . "'");
                    }

                    $sal["logs"] = array();
                    $sal["logs"]["inbound"] = array();
                    $sal["logs"]["outbound"] = array();
                    $sal["logs"]["did"] = array();

                    $i = 0;
                    while ($row = sv_mysqli_fetch_array($result1)) {
                        $sal["logs"]["outbound"][] = array(
                            "#" => $i++,
                            "phone" => $row["phone_number"],
                            "campaign" => $row["campaign_id"],
                            "call_date" => $row["call_date"],
                            "status" => $row["status"],
                            "user" => $row["user"],
                            "list_id" => $row["list_id"],
                            "length" => $row["length_in_sec"],
                            "dial" => $row["alt_dial"]
                        );
                    }
                    $i = 0;
                    while ($row = sv_mysqli_fetch_array($result2)) {
                        $sal["logs"]["inbound"][] = array(
                            "#" => $i++,
                            "phone" => $row["phone_number"],
                            "campaign" => $row["campaign_id"],
                            "call_date" => $row["call_date"],
                            "status" => $row["status"],
                            "user" => $row["user"],
                            "list_id" => $row["list_id"],
                            "length" => $row["length_in_sec"]
                        );
                    }
                    $i = 0;
                    while ($row = sv_mysqli_fetch_array($result3)) {
                        $sal["logs"]["did"][] = array("#" => $i++, "did" => $row["did_id"], "phone" => $row["caller_id_number"], "call_date" => $row["call_date"]);
                    }
                    $sal["Estado"] = "ok";
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_filtroInvalido");
            }
            $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 showLead()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('listas', "spanish");
                break;
            case "en":
                $this->lang->load('listas', "english");
                break;
            default:
                $this->lang->load('listas', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];

            $lead_id = limpia($_POST["lead_id"]);
            $sal = array();
            $con = getConnection();
            $result = sv_mysqli_query($con, "SELECT * FROM vicidial_list WHERE lead_id='$lead_id'");
            if ($row = sv_mysqli_fetch_array($result)) {
                $sal["lead_info"] = $row;
            }
            $sal["calls"] = array();
            $result = sv_mysqli_query($con, "SELECT uniqueid,lead_id,list_id,campaign_id,call_date,start_epoch,end_epoch,SEC_TO_TIME(length_in_sec) as length_in_sec,status,phone_code,phone_number,user,comments,processed,user_group,term_reason,alt_dial from vicidial_log where lead_id='$lead_id' order by uniqueid desc ");
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["calls"][] = $row;
            }
            $sal["agent"] = array();
            $result = sv_mysqli_query($con, "SELECT agent_log_id,user,server_ip,event_time,lead_id,campaign_id,pause_epoch,SEC_TO_TIME(pause_sec) as pause_sec,wait_epoch,SEC_TO_TIME(wait_sec) as wait_sec,talk_epoch,SEC_TO_TIME(talk_sec) as talk_sec,dispo_epoch,SEC_TO_TIME(dispo_sec) as dispo_sec,status,user_group,comments,sub_status from vicidial_agent_log where lead_id='$lead_id' order by agent_log_id desc ");
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["agent"][] = $row;
            }
            $sal["closer"] = array();
            $result = sv_mysqli_query($con, "SELECT closecallid,lead_id,list_id,campaign_id,call_date,start_epoch,end_epoch,SEC_TO_TIME(length_in_sec) as length_in_sec,status,phone_code,phone_number,user,comments,processed,SEC_TO_TIME(queue_seconds) as queue_seconds,user_group,xfercallid,term_reason,uniqueid,agent_only from vicidial_closer_log where lead_id='$lead_id' order by closecallid desc");
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["closer"][] = $row;
            }
            $sal["park"] = array();
            $result = sv_mysqli_query($con, "SELECT * from park_log where lead_id='$lead_id' order by parked_time, grab_time, hangup_time desc");
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["park"][] = $row;
            }
            $sal["ivr"] = array();
            $result = sv_mysqli_query($con, "SELECT campaign_id,SEC_TO_TIME(event_date) as event_date,menu_id,menu_action from vicidial_outbound_ivr_log where lead_id='$lead_id' order by uniqueid,event_date,menu_action desc ");
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["ivr"][] = $row;
            }
            $sal["record"] = array();
            $result = sv_mysqli_query($con, "SELECT recording_id,channel,server_ip,extension,start_time,start_epoch,end_time,end_epoch,SEC_TO_TIME(length_in_sec) as length_in_sec,length_in_min,filename,location,lead_id,user,vicidial_id from recording_log where lead_id='$lead_id' UNION SELECT recording_id,channel,server_ip,extension,start_time,start_epoch,end_time,end_epoch,length_in_sec,length_in_min,filename,location,lead_id,user,vicidial_id from recording_log_archive where lead_id='$lead_id' ORDER BY recording_id ");
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["record"][] = $row;
            }

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

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

    public function buscador()
    {
        $this->load->view('buscadorLeads/head');
        $this->load->view('buscadorLeads/vw_busqueda');
        $this->load->view('buscadorLeads/foot');
    }

}