<?php

require_once "BASEPATH.php";

class ReporteSalientes 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 outboundReport()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportesalientes', "spanish");
                break;
            case "en":
                $this->lang->load('reportesalientes', "english");
                break;
            default:
                $this->lang->load('reportesalientes', "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';
            $tiempoInicial = time();
            $con = getConnection();
            $fechaInicial = limpia($_GET["fechaInicial"]);
            $fechaFinal = limpia($_GET["fechaFinal"]);
            $sal = array();
            $campana = limpia($_GET["campana"]);
            $lista = limpia($_GET["lista"]);
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }

            $campana1 = $campana;
            if ($campana == -1) {
                $campana = "campaign_id";
            } else {
                $campana = "'" . $campana . "'";
                $campana1 = "'" . $campana1 . "'";
            }
            $andLista = "";
            if ($lista == -1) {
                $lista = "list_id";
            } else {
                $lista = "'$lista'";
            }
            $whC = "";
            if ($_SESSION["Cliente"] != -1) {
                $whC = "WHERE vsc_id REGEXP '^" . $_SESSION["Cliente"] . "+[0-9]+$'";
            }
            $query = "select vsc_id,vsc_name from vicidial_status_categories $whC";
            $result = sv_mysqli_query($con, $query);
            $statcats_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            while ($i < $statcats_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $vsc_id[$i] = $row[0];
                $vsc_name[$i] = $row[1];
                $vsc_count[$i] = 0;
                $i++;
            }
            $customer_interactive_statuses = '';
            $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";
                }
            }
            if ($lista != "list_id") {
                $query = "SELECT lead_id FROM vicidial_list WHERE list_id = $lista";
                $result = sv_mysqli_query($con, $query);
                $leadsXD = "";
                while ($row = sv_mysqli_fetch_array($result)) {
                    $leadsXD .= "'" . $row["lead_id"] . "',";
                }
                if ($leadsXD != "") {
                    $leadsXD = substr($leadsXD, 0, -1);
                    $andLista = "AND lead_id IN ($leadsXD)";
                } else {
                    $andLista = "AND 1 = 2";
                }
            }
            $query = "select status from vicidial_statuses where human_answered='Y' UNION SELECT status from vicidial_campaign_statuses where human_answered='Y' and campaign_id = $campana $and";

            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $customer_interactive_statuses .= "'$row[0]',";
            }
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $TOTALcallsRAW = $row[0];
            $TOTALsec = $row[1];
            $inTOTALcallsRAW = 0;
            $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log_archive,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            #$row = sv_mysqli_fetch_array($result);
            $INallcalls_to_printZ = sv_mysqli_num_rows($result);
            $y = 0;
            $inTOTALsec = 0;
            while ($y < $INallcalls_to_printZ) {
                $row = sv_mysqli_fetch_array($result);
                $length_in_secZ = $row[0];
                $queue_secondsZ = $row[1];
                $agent_alert_delayZ = $row[2];
                $TOTALdelay = round($agent_alert_delayZ / 1000);
                $thiscallsec = (($length_in_secZ - $queue_secondsZ) - $TOTALdelay);
                if ($thiscallsec < 0) {
                    $thiscallsec = 0;
                }
                $inTOTALsec = ($inTOTALsec + $thiscallsec);
                $y++;
            }
            $inTOTALcallsRAW = $y;
            $TOTALsec = ($TOTALsec + $inTOTALsec);
            $inTOTALcalls = sprintf("%10s", $inTOTALcallsRAW);
            $TOTALcalls = sprintf("%10s", $TOTALcallsRAW);
            if (($row[0] < 1) or ($TOTALsec < 1)) {
                $average_call_seconds = '         0';
            } else {
                $average_call_seconds = ($TOTALsec / $TOTALcallsRAW);
                $average_call_seconds = round($average_call_seconds, 2);
                $average_call_seconds = sprintf("%10s", $average_call_seconds);
            }
            $sal["totales"]["llamadasTotales"] = $TOTALcalls;
            $sal["totales"]["duracionPromedio"] = $average_call_seconds;
            $sal["totales"]["rollover"] = $inTOTALcalls;
            #RespuestasHumanas
            $customer_interactive_statuses = substr($customer_interactive_statuses, 0, -1);
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $CIcallsRAW = $row[0];
            $CIsec = $row[1];
            $length_in_secZ = 0;
            $queue_secondsZ = 0;
            $agent_alert_delayZ = 0;
            $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and vicidial_closer_log.status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log_archive,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and vicidial_closer_log_archive.status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            $sal["ERROR"] = mysqli_error($con);
            $INallcalls_to_printZ = sv_mysqli_num_rows($result);
            $y = 0;
            $inCIsec = 0;
            while ($y < $INallcalls_to_printZ) {
                $row = sv_mysqli_fetch_array($result);
                $length_in_secZ = $row[0];
                $queue_secondsZ = $row[1];
                $agent_alert_delayZ = $row[2];
                $CIdelay = round($agent_alert_delayZ / 1000);
                $thiscallsec = (($length_in_secZ - $queue_secondsZ) - $CIdelay);
                if ($thiscallsec < 0) {
                    $thiscallsec = 0;
                }
                $inCIsec = ($inCIsec + $thiscallsec);
                $y++;
            }
            $inCIcallsRAW = $y;
            $CIsec = ($CIsec + $inCIsec);
            $CIcallsRAW = ($CIcallsRAW + $inCIcallsRAW);
            $CIcalls = sprintf("%10s", $CIcallsRAW);
            if (($CIcallsRAW < 1) or ($CIsec < 1)) {
                $average_ci_seconds = '         0';
            } else {
                $average_ci_seconds = ($CIsec / $CIcallsRAW);
                $average_ci_seconds = round($average_ci_seconds, 2);
                $average_ci_seconds = sprintf("%10s", $average_ci_seconds);
            }
            $CIsec = intval($CIsec);
            $sal["respuestasHumanas"]["total"] = $CIcalls;
            $sal["respuestasHumanas"]["duracionPromedio"] = $average_ci_seconds;
            $sal["respuestasHumanas"]["tiempoTotal"] = $CIsec;
            #Abandonos
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status='DROP' and (length_in_sec <= 6000 or length_in_sec is null) $and";
            if ($archived) {
                $query = " select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status='DROP' and (length_in_sec <= 6000 or length_in_sec is null) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $DROPcalls = sprintf("%10s", $row[0]);
            $DROPcallsRAW = $row[0];
            $DROPseconds = $row[1];
            $q = 0;
            $query = "SELECT status,status_name,human_answered,category from vicidial_statuses";
            $result = sv_mysqli_query($con, $query);
            $statuses_to_print = sv_mysqli_num_rows($result);
            $p = 0;
            $statname_list = array();
            $statcat_list = array();
            $camp_ANS_STAT_SQL = "";
            while ($p < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $status[$q] = $row[0];
                $status_name[$q] = $row[1];
                $human_answered[$q] = $row[2];
                $category[$q] = $row[3];
                $statname_list["$status[$q]"] = "$status_name[$q]";
                $statcat_list["$status[$q]"] = "$category[$q]";
                if ($human_answered[$q] == 'Y') {
                    $camp_ANS_STAT_SQL .= "'$row[0]',";
                }
                $q++;
                $p++;
            }
            $query = "SELECT distinct status,status_name,human_answered,category from vicidial_campaign_statuses where campaign_id = $campana $and";
            $result = sv_mysqli_query($con, $query);
            $statuses_to_print = sv_mysqli_num_rows($result);
            $p = 0;
            while ($p < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $status[$q] = $row[0];
                $status_name[$q] = $row[1];
                $human_answered[$q] = $row[2];
                $category[$q] = $row[3];
                $statname_list["$status[$q]"] = "$status_name[$q]";
                $statcat_list["$status[$q]"] = "$category[$q]";
                if ($human_answered[$q] == 'Y') {
                    $camp_ANS_STAT_SQL .= "'$row[0]',";
                }
                $q++;
                $p++;
            }
            $tiempoFinal = time(); ////////////////////////////////////////////////////////////////////////////////////////////////////
            //$sal["TiempoShidori"]=$tiempoFinal-$tiempoInicial;
            $tiempoInicial = time();
            $camp_ANS_STAT_SQL = preg_replace('/,$/i', '', $camp_ANS_STAT_SQL);
            $query = "select count(*) AS C from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN($camp_ANS_STAT_SQL) $and";
            if ($archived) {
                $query = " select count(*) AS C from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN($camp_ANS_STAT_SQL) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $ANSWERcalls = $row[0];
            if (($DROPcalls < 1) or ($TOTALcalls < 1)) {
                $DROPpercent = '0';
            } else {
                $DROPpercent = (($DROPcallsRAW / $TOTALcalls) * 100);
                $DROPpercent = round($DROPpercent, 2);
            }
            if (($DROPcalls < 1) or ($ANSWERcalls < 1)) {
                $DROPANSWERpercent = '0';
            } else {
                $DROPANSWERpercent = (($DROPcallsRAW / $ANSWERcalls) * 100);
                $DROPANSWERpercent = round($DROPANSWERpercent, 2);
            }
            if (($DROPseconds < 1) or ($DROPcallsRAW < 1)) {
                $average_hold_seconds = '         0';
            } else {
                $average_hold_seconds = ($DROPseconds / $DROPcallsRAW);
                $average_hold_seconds = round($average_hold_seconds, 2);
                $average_hold_seconds = sprintf("%10s", $average_hold_seconds);
            }
            $sal["abandono"]["total"] = $DROPcalls;
            $sal["abandono"]["pocentaje"] = $DROPpercent;
            $sal["abandono"]["totalAbandonadasRespuestas"] = $ANSWERcalls;
            $sal["abandono"]["porcentajeAbandonadasRespuestas"] = $DROPANSWERpercent;
            if (($DROPcalls < 1) or ($CIcallsRAW < 1)) {
                $inDROPANSWERpercent = '0';
            } else {
                $inDROPANSWERpercent = (($DROPcallsRAW / $CIcallsRAW) * 100);
                $inDROPANSWERpercent = round($inDROPANSWERpercent, 2);
            }
            $sal["abandono"]["totalRollover"] = $CIcallsRAW;
            $sal["abandono"]["porcentajeRollover"] = $inDROPANSWERpercent;
            $sal["abandono"]["segundos"] = $average_hold_seconds;
            $result = sv_mysqli_query($con, "select closer_campaigns from vicidial_campaigns where campaign_id = $campana $and");
            $ccamps_to_print = sv_mysqli_num_rows($result);
            $c = 0;
            $closer_campaignsSQL = "";
            while ($ccamps_to_print > $c) {
                $row = sv_mysqli_fetch_array($result);
                $closer_campaigns = $row[0];
                $closer_campaigns = preg_replace("/^ | -$/", "", $closer_campaigns);
                $closer_campaigns = preg_replace("/ /", "','", $closer_campaigns);
                $closer_campaignsSQL .= "'$closer_campaigns',";
                $c++;
            }
            $closer_campaignsSQL = preg_replace('/,$/i', '', $closer_campaignsSQL);
            $query = "select count(*) AS C from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id = $campana and list_id = $lista and status NOT IN('DROP','XDROP','HXFER','QVMAIL','HOLDTO','LIVE','QUEUE') $and";
            if ($archived) {
                $query = "select count(*) AS C from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id = $campana and list_id = $lista and status NOT IN('DROP','XDROP','HXFER','QVMAIL','HOLDTO','LIVE','QUEUE') $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $TOTALanswers = ($row[0] + $ANSWERcalls);
            $query = "SELECT sum(wait_sec + talk_sec + dispo_sec) from vicidial_agent_log where DATE(event_time) >= DATE('$fechaInicial') and DATE(event_time) <= DATE('$fechaFinal') and pause_sec<65000 and wait_sec<65000 and talk_sec<65000 and dispo_sec<65000 and campaign_id = $campana $andLista $and";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $agent_non_pause_sec = $row[0];
            if ($agent_non_pause_sec > 0) {
                $AVG_ANSWERagent_non_pause_sec = (($TOTALanswers / $agent_non_pause_sec) * 60);
                $AVG_ANSWERagent_non_pause_sec = round($AVG_ANSWERagent_non_pause_sec, 2);
            } else {
                $AVG_ANSWERagent_non_pause_sec = 0;
            }
            $AVG_ANSWERagent_non_pause_sec = sprintf("%10s", $AVG_ANSWERagent_non_pause_sec);
            $sal["abandono"]["rating"] = $AVG_ANSWERagent_non_pause_sec;
            #SIN RESPUESTAS
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('NA','ADC','AB','CPDB','CPDUK','CPDATB','CPDNA','CPDREJ','CPDINV','CPDSUA','CPDSI','CPDSNC','CPDSR','CPDSUK','CPDSV','CPDERR') and (length_in_sec <= 60 or length_in_sec is null) $and";
            if ($archived) {
                $query = " select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('NA','ADC','AB','CPDB','CPDUK','CPDATB','CPDNA','CPDREJ','CPDINV','CPDSUA','CPDSI','CPDSNC','CPDSR','CPDSUK','CPDSV','CPDERR') and (length_in_sec <= 60 or length_in_sec is null) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $autoNAcalls = sprintf("%10s", $row[0]);
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('B','DC','N') and (length_in_sec <= 60 or length_in_sec is null) $and";
            if ($archived) {
                $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('B','DC','N') and (length_in_sec <= 60 or length_in_sec is null) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $manualNAcalls = sprintf("%10s", $row[0]);
            $totalNAcalls = ($autoNAcalls + $manualNAcalls);
            $totalNAcalls = sprintf("%10s", $totalNAcalls);
            if (($totalNAcalls < 1) or ($TOTALcalls < 1)) {
                $NApercent = '0';
            } else {
                $NApercent = (($totalNAcalls / $TOTALcalls) * 100);
                $NApercent = round($NApercent, 2);
            }
            if (($row[0] < 1) or ($row[1] < 1)) {
                $average_na_seconds = '         0';
            } else {
                $average_na_seconds = ($row[1] / $row[0]);
                $average_na_seconds = round($average_na_seconds, 2);
                $average_na_seconds = sprintf("%10s", $average_na_seconds);
            }
            $sal["sinRespuesta"]["total"] = $totalNAcalls;
            $sal["sinRespuesta"]["porcentaje"] = $NApercent;
            $sal["sinRespuesta"]["totalLlamadasAutomaticas"] = $autoNAcalls;
            $sal["sinRespuesta"]["totalLlamadasManuales"] = $manualNAcalls;
            $sal["sinRespuesta"]["duracionAproximada"] = $average_na_seconds;
            #RAZON DE COLGADO
            $TOTALcalls = 0;
            $query = "select count(*) AS C,term_reason from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and group by term_reason";
            if ($archived) {
                $query = "select count(*) AS C,term_reason from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and group by term_reason";
            }

            $result = sv_mysqli_query($con, $query);
            $reasons_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $max_calls = 1;
            $sal["razonesColgado"]["Registros"] = array();
            while ($i < $reasons_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $TOTALcalls = ($TOTALcalls + $row[0]);
                $REASONcount = $row[0];
                $reason = $row[1];
                //$REASONcount =    sprintf("%10s", $row[0]);while(strlen($REASONcount)>10) {$REASONcount = substr("$REASONcount", 0, -1);}
                //$reason =    sprintf("%-20s", $row[1]);while(strlen($reason)>20) {$reason = substr("$reason", 0, -1);}
                if (preg_match('/NONE/', $reason)) {$reason = 'NO ANSWER';}
                if (preg_match('/CALLER/', $reason)) {$reason = 'CUSTOMER';}
                $reason = str_replace("CUSTOMER", $this->lang->line("razon_customer"), $reason);
                $reason = str_replace("AGENT", $this->lang->line("razon_agente"), $reason);
                $reason = str_replace("QUEUETIMEOUT", $this->lang->line("razon_queue"), $reason);
                $reason = str_replace("ABANDON", $this->lang->line("razon_abandon"), $reason);
                $reason = str_replace("NO ANSWER", $this->lang->line("razon_noanswer"), $reason);
                $sal["razonesColgado"]["Registros"][$i]["razon"] = $reason;
                $sal["razonesColgado"]["Registros"][$i]["llamadas"] = $REASONcount;
                if ($row[0] > $max_calls) {
                    $max_calls = $row[0];
                }
                $graph_stats[$i][0] = $row[0];
                $graph_stats[$i][1] = $row[1];
                $i++;
            }
            $TOTALcalls = sprintf("%10s", $TOTALcalls);
            $sal["razonesColgado"]["total"] = $TOTALcalls;
            $TOTALcalls = 0;

            $query = "SELECT sum(pause_sec + wait_sec + talk_sec + dispo_sec) from vicidial_agent_log where DATE(event_time) >= DATE('$fechaInicial') and DATE(event_time) <= DATE('$fechaFinal') and campaign_id = $campana $andLista and pause_sec<65000 and wait_sec<65000 and talk_sec<65000 and dispo_sec<65000 $and";
            $result = sv_mysqli_query($con, $query);
            $rowx = sv_mysqli_fetch_array($result);
            $AGENTsec = "$rowx[0]";
            $Ctally_to_print = sv_mysqli_num_rows($result);
            $query = "select count(*) AS C,status,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and group by status";
            if ($archived) {
                $query = "select count(*) AS C,status,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and  group by status";
            }
            $result = sv_mysqli_query($con, $query);
            $statuses_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $statusSQL = "";
            while ($i < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $STATUScountARY[$i] = $row[0];
                $RAWstatusARY[$i] = $row[1];
                $RAWhoursARY[$i] = $row[2];
                $statusSQL .= "'$row[1]',";
                $i++;
            }
            $i = 0;
            $TOTALtimeS = 0;
            $max_total_time = 1;
            $STATUSavg_sec = 1;
            $max_callshr = 1;
            $max_avg_time = 1;
            $max_agentcallshr = 1;
            $statcat_list["DISPO"] = "";
            $statname_list["DISPO"] = "";
            $sal["estadoLlamada"] = array();
            $sal["estadoLlamada"]["Registros"] = array();
            while ($i < $statuses_to_print) {
                $STATUScount = $STATUScountARY[$i];
                $RAWstatus = $RAWstatusARY[$i];
                $RAWhours = $RAWhoursARY[$i];
                $r = 0;
                while ($r < $statcats_to_print) {
                    if (array_key_exists($RAWstatus, $statcat_list) && $statcat_list[$RAWstatus] == "$vsc_id[$r]") {
                        $vsc_count[$r] = ($vsc_count[$r] + $STATUScount);
                    }
                    $r++;
                }
                if ($AGENTsec < 1) {
                    $AGENTsec = 1;
                }
                $TOTALcalls = ($TOTALcalls + $STATUScount);
                $TOTALtimeS = ($TOTALtimeS + $RAWhours);
                $STATUSrate = ($STATUScount / ($TOTALsec / 3600));
                $STATUSrate = sprintf("%.2f", $STATUSrate);
                $AGENTrate = ($STATUScount / ($AGENTsec / 3600));
                $AGENTrate = sprintf("%.2f", $AGENTrate);
                if ($STATUScount > $max_calls) {$max_calls = $STATUScount;}
                if ($RAWhours > $max_total_time) {$max_total_time = $RAWhours;}
                if ($STATUSavg_sec > $max_avg_time) {$max_avg_time = $STATUSavg_sec;}
                if ($STATUSrate > $max_callshr) {$max_callshr = $STATUSrate;}
                if ($AGENTrate > $max_agentcallshr) {$max_agentcallshr = $AGENTrate;}
                $STATUShours = $RAWhours;
                $STATUSavg_sec = ($RAWhours / $STATUScount);
                $STATUSavg = $STATUSavg_sec;
                $STATUScount = sprintf("%10s", $STATUScount);while (strlen($STATUScount) > 10) {$STATUScount = substr("$STATUScount", 0, -1);}
                $status = sprintf("%-6s", $RAWstatus);while (strlen($status) > 6) {$status = substr("$status", 0, -1);}
                $STATUShours = sprintf("%10s", $STATUShours);while (strlen($STATUShours) > 10) {$STATUShours = substr("$STATUShours", 0, -1);}
                $STATUSavg = sprintf("%8s", $STATUSavg);while (strlen($STATUSavg) > 8) {$STATUSavg = substr("$STATUSavg", 0, -1);}
                $STATUSrate = sprintf("%8s", $STATUSrate);while (strlen($STATUSrate) > 8) {$STATUSrate = substr("$STATUSrate", 0, -1);}
                $AGENTrate = sprintf("%8s", $AGENTrate);while (strlen($AGENTrate) > 8) {$AGENTrate = substr("$AGENTrate", 0, -1);}
                if (!array_key_exists($RAWstatus, $statname_list)) {
                    $statname_list[$RAWstatus] = "";
                }

                $status_name = sprintf("%-20s", $statname_list[$RAWstatus]);
                while (strlen($status_name) > 20) {$status_name = substr("$status_name", 0, -1);}
                if (!array_key_exists($RAWstatus, $statcat_list)) {
                    $statcat_list[$RAWstatus] = "";
                }

                $statcat = sprintf("%-20s", $statcat_list[$RAWstatus]);
                while (strlen($statcat) > 20) {$statcat = substr("$statcat", 0, -1);}
                $sal["estadoLlamada"]["Registros"][$i]["status"] = $status;
                $sal["estadoLlamada"]["Registros"][$i]["status_name"] = $status_name;
                $sal["estadoLlamada"]["Registros"][$i]["statcat"] = $statcat;
                $sal["estadoLlamada"]["Registros"][$i]["STATUScount"] = $STATUScount;
                $sal["estadoLlamada"]["Registros"][$i]["STATUShours"] = $STATUShours;
                $sal["estadoLlamada"]["Registros"][$i]["STATUSavg"] = $STATUSavg;
                $sal["estadoLlamada"]["Registros"][$i]["STATUSrate"] = $STATUSrate;
                $sal["estadoLlamada"]["Registros"][$i]["AGENTrate"] = $AGENTrate;
                $i++;
            }
            $aTOTALrate = 0;
            $aTOTALhours = 0;
            if ($TOTALcalls < 1) {
                $TOTALhours = '0:00:00';
                $TOTALavg = '0:00:00';
                $TOTALrate = '0.00';
            } else {
                $TOTALrate = ($TOTALcalls / ($TOTALsec / 3600));
                $TOTALrate = sprintf("%.2f", $TOTALrate);
                $aTOTALrate = ($TOTALcalls / ($AGENTsec / 3600));
                $aTOTALrate = sprintf("%.2f", $aTOTALrate);
                $aTOTALhours = intval($AGENTsec);
                $TOTALhours = intval($TOTALtimeS);
                $TOTALavg_sec = intval($TOTALtimeS / $TOTALcalls);
                $TOTALavg = intval($TOTALavg_sec);
            }
            $tiempoFinal = time(); ////////////////////////////////////////////////////////////////////////////////////////////////////
            //$sal["TiempoShidori3"]=$tiempoFinal-$tiempoInicial;
            $tiempoInicial = time();
            $TOTALcalls = sprintf("%10s", $TOTALcalls);
            $TOTALhours = sprintf("%10s", $TOTALhours);while (strlen($TOTALhours) > 10) {$TOTALhours = substr("$TOTALhours", 0, -1);}
            $aTOTALhours = sprintf("%10s", $aTOTALhours);while (strlen($aTOTALhours) > 10) {$aTOTALhours = substr("$aTOTALhours", 0, -1);}
            $TOTALavg = sprintf("%8s", $TOTALavg);while (strlen($TOTALavg) > 8) {$TOTALavg = substr("$TOTALavg", 0, -1);}
            $TOTALrate = sprintf("%8s", $TOTALrate);while (strlen($TOTALrate) > 8) {$TOTALrate = substr("$TOTALrate", 0, -1);}
            $aTOTALrate = sprintf("%8s", $aTOTALrate);while (strlen($aTOTALrate) > 8) {$aTOTALrate = substr("$aTOTALrate", 0, -1);}
            $sal["estadoLlamada"]["total"]["TOTALcalls"] = $TOTALcalls;
            $sal["estadoLlamada"]["total"]["TOTALhours"] = $TOTALhours;
            $sal["estadoLlamada"]["total"]["TOTALavg"] = $TOTALavg;
            $sal["estadoLlamada"]["total"]["TOTALrate"] = $TOTALrate;
            $query = "select count(*) AS C,list_id from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and  group by list_id";
            if ($archived) {
                $query = " select count(*) AS C,list_id from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and  group by list_id";
            }
            $result = sv_mysqli_query($con, $query);
            //$listids_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $listids_to_print = 0;
            $max_calls = 1;
            $LISTIDlists = array();
            $LISTIDcalls = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $listids_to_print++;
                $LISTIDcalls[$i] = $row[0];
                $LISTIDlists[$i] = $row[1];
                if ($row[0] > $max_calls) {
                    $max_calls = $row[0];
                }
                $i++;
            }
            $i = 0;
            $LISTIDlist_names = array();
            $sal["estadisticasIdListas"]["Registros"] = array();
            $TOTALcalls = 0;
            while ($i < $listids_to_print) {
                $query = "select list_name from vicidial_lists where list_id='$LISTIDlists[$i]';";
                $result = sv_mysqli_query($con, $query);
                $list_name_to_print = sv_mysqli_num_rows($result);
                if ($list_name_to_print > 0) {
                    $row = sv_mysqli_fetch_array($result);
                    $LISTIDlist_names[$i] = $row[0];
                } else {
                    $LISTIDlist_names[$i] = "";
                }
                $TOTALcalls = ($TOTALcalls + $LISTIDcalls[$i]);
                $LISTIDcount = $LISTIDcalls[$i];
                $LISTIDname = "$LISTIDlists[$i] - $LISTIDlist_names[$i]";
                /*while(strlen($LISTIDcount)>10) {
                $LISTIDcount = substr("$LISTIDcount", 0, -1);
                }
                $LISTIDname =    sprintf("%-40s", "$LISTIDlists[$i] - $LISTIDlist_names[$i]");
                while(strlen($LISTIDname)>40) {
                $LISTIDname = substr("$LISTIDname", 0, -1);
                }*/
                #$ASCII_text .= "| $LISTIDname | $LISTIDcount |\n";
                $sal["estadisticasIdListas"]["Registros"][$i]["lista"] = $LISTIDname;
                $sal["estadisticasIdListas"]["Registros"][$i]["llamadas"] = $LISTIDcount;
                $i++;
            }
            $sal["estadisticasIdListas"]["total"] = $TOTALcalls;
            #Carrier stats
            $query = "select dialstatus,count(*) AS C,campaign_id from vicidial_carrier_log vcl,vicidial_log vl where vcl.uniqueid=vl.uniqueid and DATE(vcl.call_date) > DATE('$fechaInicial') and DATE(vcl.call_date) < DATE('$fechaFinal') and DATE(vl.call_date) > DATE('$fechaInicial') and DATE(vl.call_date) < DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista group by dialstatus $and ";
            if ($archived) {
                $query = " select dialstatus,count(*) AS C,campaign_id from vicidial_carrier_log vcl,vicidial_log_archive vl where vcl.uniqueid=vl.uniqueid and DATE(vcl.call_date) > DATE('$fechaInicial') and DATE(vcl.call_date) < DATE('$fechaFinal') and DATE(vl.call_date) > DATE('$fechaInicial') and DATE(vl.call_date) < DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista group by dialstatus $and ";
            }

            $result = sv_mysqli_query($con, $query);
            $carrierstatuses_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $TOTCARcalls = 0;
            $sal["carrier"]["Registros"] = array();
            while ($i < $carrierstatuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $TOTCARcalls = ($TOTCARcalls + $row[1]);
                $CARstatus = sprintf("%-20s", $row[0]);while (strlen($CARstatus) > 20) {$CARstatus = substr("$CARstatus", 0, -1);}
                $CARcount = sprintf("%10s", $row[1]);while (strlen($CARcount) > 10) {$CARcount = substr("$CARcount", 0, -1);}
                $sal["carrier"]["Registros"][$i]["estado"] = $CARstatus;
                $sal["carrier"]["Registros"][$i]["llamadas"] = $CARcount;
                $i++;
            }
            $TOTCARcalls = sprintf("%10s", $TOTCARcalls);while (strlen($TOTCARcalls) > 10) {$TOTCARcalls = substr("$TOTCARcalls", 0, -1);}
            $sal["carrier"]["total"] = $TOTCARcalls;
            $max_calls = 1;
            $TOTCATcalls = 0;
            $r = 0;
            $i = 0;
            $sal["estadisticasCategoriasEstPersonalizados"]["Registros"] = array();
            while ($r < $statcats_to_print) {
                if ($vsc_id[$r] != 'UNDEFINED') {
                    $TOTCATcalls = ($TOTCATcalls + $vsc_count[$r]);
                    $category = sprintf("%-20s", $vsc_id[$r]);while (strlen($category) > 20) {$category = substr("$category", 0, -1);}
                    $CATcount = sprintf("%10s", $vsc_count[$r]);while (strlen($CATcount) > 10) {$CATcount = substr("$CATcount", 0, -1);}
                    $CATname = sprintf("%-30s", $vsc_name[$r]);while (strlen($CATname) > 30) {$CATname = substr("$CATname", 0, -1);}
                    if ($vsc_count[$r] > $max_calls) {$max_calls = $vsc_count[$r];}
                    $i++;
                    #$ASCII_text .= "| $category | $CATcount | $CATname |\n";
                    $sal["estadisticasCategoriasEstPersonalizados"]["Registros"][$i]["categoria"] = $category;
                    $sal["estadisticasCategoriasEstPersonalizados"]["Registros"][$i]["llamadas"] = $CATcount;
                    $sal["estadisticasCategoriasEstPersonalizados"]["Registros"][$i]["descripcion"] = $CATname;
                }
                $r++;
            }
            $TOTCATcalls = sprintf("%10s", $TOTCATcalls);while (strlen($TOTCATcalls) > 10) {$TOTCATcalls = substr("$TOTCATcalls", 0, -1);}
            $sal["estadisticasCategoriasEstPersonalizados"]["total"] = $TOTCATcalls;
            $TOTagents = 0;
            $TOTcalls = 0;
            $TOTtime = 0;
            $TOTavg = 0;
            $max_calls = 1;
            $max_total_time = 1;
            $max_avg_time = 1;
            $RAWuser_calls = $RAWuser = $RAWfull_name = $RAWuser_talk = $RAWuser_average = array();
            $query = "select vicidial_log.user,full_name,count(*) AS C,sum(length_in_sec) AS S,avg(length_in_sec) AS A from vicidial_log,vicidial_users where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and and vicidial_log.user is not null and length_in_sec is not null and length_in_sec >= 0 and vicidial_log.user=vicidial_users.user group by vicidial_log.user ";
            if ($archived) {
                $query = " select vicidial_log_archive.user,full_name,count(*) AS C,sum(length_in_sec) AS S,avg(length_in_sec) AS A from vicidial_log_archive,vicidial_users where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and and vicidial_log_archive.user is not null and length_in_sec is not null and length_in_sec >= 0 and vicidial_log_archive.user=vicidial_users.user group by vicidial_log_archive.user ";
            }
            $result = sv_mysqli_query($con, $query);
            $users_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            while ($i < $users_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $RAWuser[$i] = $row[0];
                $RAWfull_name[$i] = $row[1];
                $RAWuser_calls[$i] = $row[2];
                $RAWuser_talk[$i] = $row[3];
                $RAWuser_average[$i] = $row[4];
                $TOTcalls = ($TOTcalls + $row[2]);
                $TOTtime = ($TOTtime + $row[3]);
                $i++;
            }
            $i = 0;
            $sal["estadisticasAgente"]["Registros"] = array();
            while ($i < $users_to_print) {
                $user = sprintf("%-6s", $RAWuser[$i]);while (strlen($user) > 20) {$user = substr("$user", 0, -1);}
                //$user = $RAWuser[$i];
                $full_name = sprintf("%-15s", $RAWfull_name[$i]);while (strlen($full_name) > 15) {$full_name = substr("$full_name", 0, -1);}
                //$full_name = $RAWfull_name[$i];
                $include_rollover = "YES";
                if (preg_match("/YES/i", $include_rollover)) {
                    $length_in_secZ = 0;
                    $queue_secondsZ = 0;
                    $agent_alert_delayZ = 0;
                    $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  and group_id=campaign_id and user='$RAWuser[$i]' and list_id = $lista";
                    //$sal["querys"][] = $query;
                    $y = 0;
                    $result = sv_mysqli_query($con, $query);
                    $INallcalls_to_printZ = sv_mysqli_num_rows($result);
                    while ($y < $INallcalls_to_printZ) {
                        $row = sv_mysqli_fetch_array($result);
                        $length_in_secZ = $row[0];
                        $queue_secondsZ = $row[1];
                        $agent_alert_delayZ = $row[2];
                        $CIdelay = round($agent_alert_delayZ / 1000);
                        $thiscallsec = (($length_in_secZ - $queue_secondsZ) - $CIdelay);
                        if ($thiscallsec < 0) {
                            $thiscallsec = 0;
                        }
                        $inCIsec = ($inCIsec + $thiscallsec);
                        $y++;
                    }
                    $inCIcallsRAW = $y;
                    $RAWuser_talk[$i] = ($RAWuser_talk[$i] + $inCIsec);
                    $RAWuser_calls[$i] = ($RAWuser_calls[$i] + $inCIcallsRAW);
                    $TOTcalls = ($TOTcalls + $inCIcallsRAW);
                    $TOTtime = ($TOTtime + $inCIsec);
                }
                $USERcalls = sprintf("%10s", $RAWuser_calls[$i]);
                $USERtotTALK = $RAWuser_talk[$i];
                $USERavgTALK = round($RAWuser_talk[$i] / $RAWuser_calls[$i]);
                if ($RAWuser_calls[$i] > $max_calls) {$max_calls = $RAWuser_calls[$i];}
                if ($RAWuser_talk[$i] > $max_total_time) {$max_total_time = $RAWuser_talk[$i];}
                if ($USERavgTALK > $max_avg_time) {$max_avg_time = $USERavgTALK;}
                $USERtotTALK_MS = intval($USERtotTALK);
                $USERavgTALK_MS = intval($USERavgTALK);
                $USERtotTALK_MS = sprintf("%9s", $USERtotTALK_MS);
                $USERavgTALK_MS = sprintf("%6s", $USERavgTALK_MS);
                $sal["estadisticasAgente"]["Registros"][$i]["agente"] = $user;
                $sal["estadisticasAgente"]["Registros"][$i]["nombre"] = $full_name;
                $sal["estadisticasAgente"]["Registros"][$i]["llamadas"] = $USERcalls;
                $sal["estadisticasAgente"]["Registros"][$i]["hora"] = $USERtotTALK_MS;
                $sal["estadisticasAgente"]["Registros"][$i]["promedio"] = $USERavgTALK_MS;
                $i++;
                $tiempoFinal = time(); ////////////////////////////////////////////////////////////////////////////////////////////////////
                //$sal["TiempoShidori4"]=$tiempoFinal-$tiempoInicial;
                $tiempoInicial = time();

            }
            sv_mysqli_close($con);
            if (!isset($_GET["csv"])) {
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=\"ReporteSalientes(" . $fechaInicial . "-" . $fechaFinal . ").csv\"");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');
                $test = array();
                switch ($_GET["donde"]) {
                    case 2:
                        $this->trata($out, $sal["estadoLlamada"], $test);
                        break;
                    case 1:
                        $this->trata($out, $sal["razonesColgado"], $test);
                        break;
                    case 3:
                        $this->trata($out, $sal["estadisticasCategoriasEstPersonalizados"], $test);
                        break;
                    case 4:
                        $this->trata($out, $sal["estadisticasAgente"], $test);
                        break;
                    case 5:
                        $this->trata($out, $sal["estadisticasIdListas"], $test);
                        break;

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

    public function outboundReportCSV()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportesalientes', "spanish");
                break;
            case "en":
                $this->lang->load('reportesalientes', "english");
                break;
            default:
                $this->lang->load('reportesalientes', "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';
            $tiempoInicial = time();
            $con = getConnection();
            $fechaInicial = limpia($_GET["fechaInicial"]);
            $fechaFinal = limpia($_GET["fechaFinal"]);
            $sal = array();
            $campana = limpia($_GET["campana"]);
            $lista = limpia($_GET["lista"]);
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }

            $campana1 = $campana;
            if ($campana == -1) {
                $campana = "campaign_id";
            } else {
                $campana = "'" . $campana . "'";
                $campana1 = "'" . $campana1 . "'";
            }
            $andLista = "";
            if ($lista == -1) {
                $lista = "list_id";
            } else {
                $lista = "'$lista'";
            }
            $whC = "";
            if ($_SESSION["Cliente"] != -1) {
                $whC = "WHERE vsc_id REGEXP '^" . $_SESSION["Cliente"] . "+[0-9]+$'";
            }
            $query = "select vsc_id,vsc_name from vicidial_status_categories $whC";
            $result = sv_mysqli_query($con, $query);
            $statcats_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            while ($i < $statcats_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $vsc_id[$i] = $row[0];
                $vsc_name[$i] = $row[1];
                $vsc_count[$i] = 0;
                $i++;
            }
            $customer_interactive_statuses = '';
            $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";
                }
            }
            if ($lista != "list_id") {
                $query = "SELECT lead_id FROM vicidial_list WHERE list_id = $lista";
                $result = sv_mysqli_query($con, $query);
                $leadsXD = "";
                while ($row = sv_mysqli_fetch_array($result)) {
                    $leadsXD .= "'" . $row["lead_id"] . "',";
                }
                if ($leadsXD != "") {
                    $leadsXD = substr($leadsXD, 0, -1);
                    $andLista = "AND lead_id IN ($leadsXD)";
                } else {
                    $andLista = "AND 1 = 2";
                }
            }
            $query = "select status from vicidial_statuses where human_answered='Y' UNION SELECT status from vicidial_campaign_statuses where human_answered='Y' and campaign_id = $campana $and";

            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $customer_interactive_statuses .= "'$row[0]',";
            }
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $TOTALcallsRAW = $row[0];
            $TOTALsec = $row[1];
            $inTOTALcallsRAW = 0;
            $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log_archive,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            #$row = sv_mysqli_fetch_array($result);
            $INallcalls_to_printZ = sv_mysqli_num_rows($result);
            $y = 0;
            $inTOTALsec = 0;
            while ($y < $INallcalls_to_printZ) {
                $row = sv_mysqli_fetch_array($result);
                $length_in_secZ = $row[0];
                $queue_secondsZ = $row[1];
                $agent_alert_delayZ = $row[2];
                $TOTALdelay = round($agent_alert_delayZ / 1000);
                $thiscallsec = (($length_in_secZ - $queue_secondsZ) - $TOTALdelay);
                if ($thiscallsec < 0) {
                    $thiscallsec = 0;
                }
                $inTOTALsec = ($inTOTALsec + $thiscallsec);
                $y++;
            }
            $inTOTALcallsRAW = $y;
            $TOTALsec = ($TOTALsec + $inTOTALsec);
            $inTOTALcalls = sprintf("%10s", $inTOTALcallsRAW);
            $TOTALcalls = sprintf("%10s", $TOTALcallsRAW);
            if (($row[0] < 1) or ($TOTALsec < 1)) {
                $average_call_seconds = '         0';
            } else {
                $average_call_seconds = ($TOTALsec / $TOTALcallsRAW);
                $average_call_seconds = round($average_call_seconds, 2);
                $average_call_seconds = sprintf("%10s", $average_call_seconds);
            }
            $this->lang->line("desc_estadoRemarcable");
            $sal["totales"]["llamadasTotales"] = $TOTALcalls;
            $sal["totales"]["duracionPromedio"] = $average_call_seconds;
            $sal["totales"]["rollover"] = $inTOTALcalls;
            #RespuestasHumanas
            $customer_interactive_statuses = substr($customer_interactive_statuses, 0, -1);
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $CIcallsRAW = $row[0];
            $CIsec = $row[1];
            $length_in_secZ = 0;
            $queue_secondsZ = 0;
            $agent_alert_delayZ = 0;
            $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and vicidial_closer_log.status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            if ($archived) {
                $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log_archive,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and group_id=campaign_id and vicidial_closer_log_archive.status IN($customer_interactive_statuses) and campaign_id = $campana and list_id = $lista $and";
            }
            $result = sv_mysqli_query($con, $query);
            $sal["ERROR"] = mysqli_error($con);
            $INallcalls_to_printZ = sv_mysqli_num_rows($result);
            $y = 0;
            $inCIsec = 0;
            while ($y < $INallcalls_to_printZ) {
                $row = sv_mysqli_fetch_array($result);
                $length_in_secZ = $row[0];
                $queue_secondsZ = $row[1];
                $agent_alert_delayZ = $row[2];
                $CIdelay = round($agent_alert_delayZ / 1000);
                $thiscallsec = (($length_in_secZ - $queue_secondsZ) - $CIdelay);
                if ($thiscallsec < 0) {
                    $thiscallsec = 0;
                }
                $inCIsec = ($inCIsec + $thiscallsec);
                $y++;
            }
            $inCIcallsRAW = $y;
            $CIsec = ($CIsec + $inCIsec);
            $CIcallsRAW = ($CIcallsRAW + $inCIcallsRAW);
            $CIcalls = sprintf("%10s", $CIcallsRAW);
            if (($CIcallsRAW < 1) or ($CIsec < 1)) {
                $average_ci_seconds = '         0';
            } else {
                $average_ci_seconds = ($CIsec / $CIcallsRAW);
                $average_ci_seconds = round($average_ci_seconds, 2);
                $average_ci_seconds = sprintf("%10s", $average_ci_seconds);
            }
            $CIsec = intval($CIsec);
            $sal["respuestasHumanas"]["total"] = $CIcalls;
            $sal["respuestasHumanas"]["duracionPromedio"] = $average_ci_seconds;
            $sal["respuestasHumanas"]["tiempoTotal"] = $CIsec;
            #Abandonos
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status='DROP' and (length_in_sec <= 6000 or length_in_sec is null) $and";
            if ($archived) {
                $query = " select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status='DROP' and (length_in_sec <= 6000 or length_in_sec is null) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $DROPcalls = sprintf("%10s", $row[0]);
            $DROPcallsRAW = $row[0];
            $DROPseconds = $row[1];
            $q = 0;
            $query = "SELECT status,status_name,human_answered,category from vicidial_statuses";
            $result = sv_mysqli_query($con, $query);
            $statuses_to_print = sv_mysqli_num_rows($result);
            $p = 0;
            $statname_list = array();
            $statcat_list = array();
            $camp_ANS_STAT_SQL = "";
            while ($p < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $status[$q] = $row[0];
                $status_name[$q] = $row[1];
                $human_answered[$q] = $row[2];
                $category[$q] = $row[3];
                $statname_list["$status[$q]"] = "$status_name[$q]";
                $statcat_list["$status[$q]"] = "$category[$q]";
                if ($human_answered[$q] == 'Y') {
                    $camp_ANS_STAT_SQL .= "'$row[0]',";
                }
                $q++;
                $p++;
            }
            $query = "SELECT distinct status,status_name,human_answered,category from vicidial_campaign_statuses where campaign_id = $campana $and";
            $result = sv_mysqli_query($con, $query);
            $statuses_to_print = sv_mysqli_num_rows($result);
            $p = 0;
            while ($p < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $status[$q] = $row[0];
                $status_name[$q] = $row[1];
                $human_answered[$q] = $row[2];
                $category[$q] = $row[3];
                $statname_list["$status[$q]"] = "$status_name[$q]";
                $statcat_list["$status[$q]"] = "$category[$q]";
                if ($human_answered[$q] == 'Y') {
                    $camp_ANS_STAT_SQL .= "'$row[0]',";
                }
                $q++;
                $p++;
            }
            $tiempoFinal = time(); ////////////////////////////////////////////////////////////////////////////////////////////////////
            //$sal["TiempoShidori"]=$tiempoFinal-$tiempoInicial;
            $tiempoInicial = time();
            $camp_ANS_STAT_SQL = preg_replace('/,$/i', '', $camp_ANS_STAT_SQL);
            $query = "select count(*) AS C from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN($camp_ANS_STAT_SQL) $and";
            if ($archived) {
                $query = " select count(*) AS C from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN($camp_ANS_STAT_SQL) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $ANSWERcalls = $row[0];
            if (($DROPcalls < 1) or ($TOTALcalls < 1)) {
                $DROPpercent = '0';
            } else {
                $DROPpercent = (($DROPcallsRAW / $TOTALcalls) * 100);
                $DROPpercent = round($DROPpercent, 2);
            }
            if (($DROPcalls < 1) or ($ANSWERcalls < 1)) {
                $DROPANSWERpercent = '0';
            } else {
                $DROPANSWERpercent = (($DROPcallsRAW / $ANSWERcalls) * 100);
                $DROPANSWERpercent = round($DROPANSWERpercent, 2);
            }
            if (($DROPseconds < 1) or ($DROPcallsRAW < 1)) {
                $average_hold_seconds = '         0';
            } else {
                $average_hold_seconds = ($DROPseconds / $DROPcallsRAW);
                $average_hold_seconds = round($average_hold_seconds, 2);
                $average_hold_seconds = sprintf("%10s", $average_hold_seconds);
            }
            $sal["abandono"]["total"] = $DROPcalls;
            $sal["abandono"]["pocentaje"] = $DROPpercent;
            $sal["abandono"]["totalAbandonadasRespuestas"] = $ANSWERcalls;
            $sal["abandono"]["porcentajeAbandonadasRespuestas"] = $DROPANSWERpercent;
            if (($DROPcalls < 1) or ($CIcallsRAW < 1)) {
                $inDROPANSWERpercent = '0';
            } else {
                $inDROPANSWERpercent = (($DROPcallsRAW / $CIcallsRAW) * 100);
                $inDROPANSWERpercent = round($inDROPANSWERpercent, 2);
            }
            $sal["abandono"]["totalRollover"] = $CIcallsRAW;
            $sal["abandono"]["porcentajeRollover"] = $inDROPANSWERpercent;
            $sal["abandono"]["segundos"] = $average_hold_seconds;
            $result = sv_mysqli_query($con, "select closer_campaigns from vicidial_campaigns where campaign_id = $campana $and");
            $ccamps_to_print = sv_mysqli_num_rows($result);
            $c = 0;
            $closer_campaignsSQL = "";
            while ($ccamps_to_print > $c) {
                $row = sv_mysqli_fetch_array($result);
                $closer_campaigns = $row[0];
                $closer_campaigns = preg_replace("/^ | -$/", "", $closer_campaigns);
                $closer_campaigns = preg_replace("/ /", "','", $closer_campaigns);
                $closer_campaignsSQL .= "'$closer_campaigns',";
                $c++;
            }
            $closer_campaignsSQL = preg_replace('/,$/i', '', $closer_campaignsSQL);
            $query = "select count(*) AS C from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id = $campana and list_id = $lista and status NOT IN('DROP','XDROP','HXFER','QVMAIL','HOLDTO','LIVE','QUEUE') $and";
            if ($archived) {
                $query = "select count(*) AS C from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id = $campana and list_id = $lista and status NOT IN('DROP','XDROP','HXFER','QVMAIL','HOLDTO','LIVE','QUEUE') $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $TOTALanswers = ($row[0] + $ANSWERcalls);
            $query = "SELECT sum(wait_sec + talk_sec + dispo_sec) from vicidial_agent_log where DATE(event_time) >= DATE('$fechaInicial') and DATE(event_time) <= DATE('$fechaFinal') and pause_sec<65000 and wait_sec<65000 and talk_sec<65000 and dispo_sec<65000 and campaign_id = $campana $andLista $and";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $agent_non_pause_sec = $row[0];
            if ($agent_non_pause_sec > 0) {
                $AVG_ANSWERagent_non_pause_sec = (($TOTALanswers / $agent_non_pause_sec) * 60);
                $AVG_ANSWERagent_non_pause_sec = round($AVG_ANSWERagent_non_pause_sec, 2);
            } else {
                $AVG_ANSWERagent_non_pause_sec = 0;
            }
            $AVG_ANSWERagent_non_pause_sec = sprintf("%10s", $AVG_ANSWERagent_non_pause_sec);
            $sal["abandono"]["rating"] = $AVG_ANSWERagent_non_pause_sec;
            #SIN RESPUESTAS
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('NA','ADC','AB','CPDB','CPDUK','CPDATB','CPDNA','CPDREJ','CPDINV','CPDSUA','CPDSI','CPDSNC','CPDSR','CPDSUK','CPDSV','CPDERR') and (length_in_sec <= 60 or length_in_sec is null) $and";
            if ($archived) {
                $query = " select count(*) AS C,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('NA','ADC','AB','CPDB','CPDUK','CPDATB','CPDNA','CPDREJ','CPDINV','CPDSUA','CPDSI','CPDSNC','CPDSR','CPDSUK','CPDSV','CPDERR') and (length_in_sec <= 60 or length_in_sec is null) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $autoNAcalls = sprintf("%10s", $row[0]);
            $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('B','DC','N') and (length_in_sec <= 60 or length_in_sec is null) $and";
            if ($archived) {
                $query = "select count(*) AS C,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista and status IN('B','DC','N') and (length_in_sec <= 60 or length_in_sec is null) $and";
            }
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $manualNAcalls = sprintf("%10s", $row[0]);
            $totalNAcalls = ($autoNAcalls + $manualNAcalls);
            $totalNAcalls = sprintf("%10s", $totalNAcalls);
            if (($totalNAcalls < 1) or ($TOTALcalls < 1)) {
                $NApercent = '0';
            } else {
                $NApercent = (($totalNAcalls / $TOTALcalls) * 100);
                $NApercent = round($NApercent, 2);
            }
            if (($row[0] < 1) or ($row[1] < 1)) {
                $average_na_seconds = '         0';
            } else {
                $average_na_seconds = ($row[1] / $row[0]);
                $average_na_seconds = round($average_na_seconds, 2);
                $average_na_seconds = sprintf("%10s", $average_na_seconds);
            }
            $sal["sinRespuesta"]["total"] = $totalNAcalls;
            $sal["sinRespuesta"]["porcentaje"] = $NApercent;
            $sal["sinRespuesta"]["totalLlamadasAutomaticas"] = $autoNAcalls;
            $sal["sinRespuesta"]["totalLlamadasManuales"] = $manualNAcalls;
            $sal["sinRespuesta"]["duracionAproximada"] = $average_na_seconds;
            #RAZON DE COLGADO
            $TOTALcalls = 0;
            $query = "select count(*) AS C,term_reason from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and group by term_reason";
            if ($archived) {
                $query = "select count(*) AS C,term_reason from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and group by term_reason";
            }

            $result = sv_mysqli_query($con, $query);
            $reasons_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $max_calls = 1;
            $sal[$this->lang->line("csv_razonesColgado")][$this->lang->line("csv_razonesColgado_registros")] = array();
            while ($i < $reasons_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $TOTALcalls = ($TOTALcalls + $row[0]);
                $REASONcount = $row[0];
                $reason = $row[1];
                //$REASONcount =    sprintf("%10s", $row[0]);while(strlen($REASONcount)>10) {$REASONcount = substr("$REASONcount", 0, -1);}
                //$reason =    sprintf("%-20s", $row[1]);while(strlen($reason)>20) {$reason = substr("$reason", 0, -1);}
                if (preg_match('/NONE/', $reason)) {$reason = 'NO ANSWER';}
                if (preg_match('/CALLER/', $reason)) {$reason = 'CUSTOMER';}
                $reason = str_replace("CUSTOMER", $this->lang->line("razon_customer"), $reason);
                $reason = str_replace("AGENT", $this->lang->line("razon_agente"), $reason);
                $reason = str_replace("QUEUETIMEOUT", $this->lang->line("razon_queue"), $reason);
                $reason = str_replace("ABANDON", $this->lang->line("razon_abandon"), $reason);
                $reason = str_replace("NO ANSWER", $this->lang->line("razon_noanswer"), $reason);
                $sal[$this->lang->line("csv_razonesColgado")][$this->lang->line("csv_razonesColgado_registros")][$i][$this->lang->line("csv_razonesColgado_registros_n_razon")] = $reason;
                $sal[$this->lang->line("csv_razonesColgado")][$this->lang->line("csv_razonesColgado_registros")][$i][$this->lang->line("csv_razonesColgado_registros_n_llamadas")] = $REASONcount;
                if ($row[0] > $max_calls) {
                    $max_calls = $row[0];
                }
                $graph_stats[$i][0] = $row[0];
                $graph_stats[$i][1] = $row[1];
                $i++;
            }
            $TOTALcalls = sprintf("%10s", $TOTALcalls);
            $sal[$this->lang->line("csv_razonesColgado")][$this->lang->line("csv_razonesColgado_registros_total")] = $TOTALcalls;
            $TOTALcalls = 0;

            $query = "SELECT sum(pause_sec + wait_sec + talk_sec + dispo_sec) from vicidial_agent_log where DATE(event_time) >= DATE('$fechaInicial') and DATE(event_time) <= DATE('$fechaFinal') and campaign_id = $campana $andLista and pause_sec<65000 and wait_sec<65000 and talk_sec<65000 and dispo_sec<65000 $and";
            $result = sv_mysqli_query($con, $query);
            $rowx = sv_mysqli_fetch_array($result);
            $AGENTsec = "$rowx[0]";
            $Ctally_to_print = sv_mysqli_num_rows($result);
            $query = "select count(*) AS C,status,sum(length_in_sec) AS S from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and group by status";
            if ($archived) {
                $query = "select count(*) AS C,status,sum(length_in_sec) AS S from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and  group by status";
            }
            $result = sv_mysqli_query($con, $query);
            $statuses_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $statusSQL = "";
            while ($i < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $STATUScountARY[$i] = $row[0];
                $RAWstatusARY[$i] = $row[1];
                $RAWhoursARY[$i] = $row[2];
                $statusSQL .= "'$row[1]',";
                $i++;
            }
            $i = 0;
            $TOTALtimeS = 0;
            $max_total_time = 1;
            $STATUSavg_sec = 1;
            $max_callshr = 1;
            $max_avg_time = 1;
            $max_agentcallshr = 1;
            $statcat_list["DISPO"] = "";
            $statname_list["DISPO"] = "";
            $sal[$this->lang->line("csv_estadoLlamada")] = array();
            $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")] = array();
            while ($i < $statuses_to_print) {
                $STATUScount = $STATUScountARY[$i];
                $RAWstatus = $RAWstatusARY[$i];
                $RAWhours = $RAWhoursARY[$i];
                $r = 0;
                while ($r < $statcats_to_print) {
                    if (array_key_exists($RAWstatus, $statcat_list) && $statcat_list[$RAWstatus] == "$vsc_id[$r]") {
                        $vsc_count[$r] = ($vsc_count[$r] + $STATUScount);
                    }
                    $r++;
                }
                if ($AGENTsec < 1) {
                    $AGENTsec = 1;
                }
                $TOTALcalls = ($TOTALcalls + $STATUScount);
                $TOTALtimeS = ($TOTALtimeS + $RAWhours);
                $STATUSrate = ($STATUScount / ($TOTALsec / 3600));
                $STATUSrate = sprintf("%.2f", $STATUSrate);
                $AGENTrate = ($STATUScount / ($AGENTsec / 3600));
                $AGENTrate = sprintf("%.2f", $AGENTrate);
                if ($STATUScount > $max_calls) {$max_calls = $STATUScount;}
                if ($RAWhours > $max_total_time) {$max_total_time = $RAWhours;}
                if ($STATUSavg_sec > $max_avg_time) {$max_avg_time = $STATUSavg_sec;}
                if ($STATUSrate > $max_callshr) {$max_callshr = $STATUSrate;}
                if ($AGENTrate > $max_agentcallshr) {$max_agentcallshr = $AGENTrate;}
                $STATUShours = $RAWhours;
                $STATUSavg_sec = ($RAWhours / $STATUScount);
                $STATUSavg = $STATUSavg_sec;
                $STATUScount = sprintf("%10s", $STATUScount);while (strlen($STATUScount) > 10) {$STATUScount = substr("$STATUScount", 0, -1);}
                $status = sprintf("%-6s", $RAWstatus);while (strlen($status) > 6) {$status = substr("$status", 0, -1);}
                $STATUShours = sprintf("%10s", $STATUShours);while (strlen($STATUShours) > 10) {$STATUShours = substr("$STATUShours", 0, -1);}
                $STATUSavg = sprintf("%8s", $STATUSavg);while (strlen($STATUSavg) > 8) {$STATUSavg = substr("$STATUSavg", 0, -1);}
                $STATUSrate = sprintf("%8s", $STATUSrate);while (strlen($STATUSrate) > 8) {$STATUSrate = substr("$STATUSrate", 0, -1);}
                $AGENTrate = sprintf("%8s", $AGENTrate);while (strlen($AGENTrate) > 8) {$AGENTrate = substr("$AGENTrate", 0, -1);}
                if (!array_key_exists($RAWstatus, $statname_list)) {
                    $statname_list[$RAWstatus] = "";
                }

                $status_name = sprintf("%-20s", $statname_list[$RAWstatus]);
                while (strlen($status_name) > 20) {$status_name = substr("$status_name", 0, -1);}
                if (!array_key_exists($RAWstatus, $statcat_list)) {
                    $statcat_list[$RAWstatus] = "";
                }

                $statcat = sprintf("%-20s", $statcat_list[$RAWstatus]);
                while (strlen($statcat) > 20) {$statcat = substr("$statcat", 0, -1);}
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_status")] = $status;
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_statusName")] = $status_name;
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_statCat")] = $statcat;
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_statusCount")] = $STATUScount;
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_statusHours")] = $STATUShours;
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_statusAvg")] = $STATUSavg;
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_statusRate")] = $STATUSrate;
                $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_registros")][$i][$this->lang->line("csv_estadoLlamada_registros_n_agentRate")] = $AGENTrate;
                $i++;
            }
            $aTOTALrate = 0;
            $aTOTALhours = 0;
            if ($TOTALcalls < 1) {
                $TOTALhours = '0:00:00';
                $TOTALavg = '0:00:00';
                $TOTALrate = '0.00';
            } else {
                $TOTALrate = ($TOTALcalls / ($TOTALsec / 3600));
                $TOTALrate = sprintf("%.2f", $TOTALrate);
                $aTOTALrate = ($TOTALcalls / ($AGENTsec / 3600));
                $aTOTALrate = sprintf("%.2f", $aTOTALrate);
                $aTOTALhours = intval($AGENTsec);
                $TOTALhours = intval($TOTALtimeS);
                $TOTALavg_sec = intval($TOTALtimeS / $TOTALcalls);
                $TOTALavg = intval($TOTALavg_sec);
            }
            $tiempoFinal = time(); ////////////////////////////////////////////////////////////////////////////////////////////////////
            //$sal["TiempoShidori3"]=$tiempoFinal-$tiempoInicial;
            $tiempoInicial = time();
            $TOTALcalls = sprintf("%10s", $TOTALcalls);
            $TOTALhours = sprintf("%10s", $TOTALhours);while (strlen($TOTALhours) > 10) {$TOTALhours = substr("$TOTALhours", 0, -1);}
            $aTOTALhours = sprintf("%10s", $aTOTALhours);while (strlen($aTOTALhours) > 10) {$aTOTALhours = substr("$aTOTALhours", 0, -1);}
            $TOTALavg = sprintf("%8s", $TOTALavg);while (strlen($TOTALavg) > 8) {$TOTALavg = substr("$TOTALavg", 0, -1);}
            $TOTALrate = sprintf("%8s", $TOTALrate);while (strlen($TOTALrate) > 8) {$TOTALrate = substr("$TOTALrate", 0, -1);}
            $aTOTALrate = sprintf("%8s", $aTOTALrate);while (strlen($aTOTALrate) > 8) {$aTOTALrate = substr("$aTOTALrate", 0, -1);}
            $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_total")][$this->lang->line("csv_estadoLlamada_total_totalCalls")] = $TOTALcalls;
            $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_total")][$this->lang->line("csv_estadoLlamada_total_totalHours")] = $TOTALhours;
            $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_total")][$this->lang->line("csv_estadoLlamada_total_totalAvg")] = $TOTALavg;
            $sal[$this->lang->line("csv_estadoLlamada")][$this->lang->line("csv_estadoLlamada_total")][$this->lang->line("csv_estadoLlamada_total_totalRate")] = $TOTALrate;
            $query = "select count(*) AS C,list_id from vicidial_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and  group by list_id";
            if ($archived) {
                $query = " select count(*) AS C,list_id from vicidial_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista $and  group by list_id";
            }
            $result = sv_mysqli_query($con, $query);
            //$listids_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $listids_to_print = 0;
            $max_calls = 1;
            $LISTIDlists = array();
            $LISTIDcalls = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $listids_to_print++;
                $LISTIDcalls[$i] = $row[0];
                $LISTIDlists[$i] = $row[1];
                if ($row[0] > $max_calls) {
                    $max_calls = $row[0];
                }
                $i++;
            }
            $i = 0;
            $LISTIDlist_names = array();
            $sal[$this->lang->line("csv_estadisticasIdListas")][$this->lang->line("csv_estadisticasIdListas_registros")] = array();
            $TOTALcalls = 0;
            while ($i < $listids_to_print) {
                $query = "select list_name from vicidial_lists where list_id='$LISTIDlists[$i]';";
                $result = sv_mysqli_query($con, $query);
                $list_name_to_print = sv_mysqli_num_rows($result);
                if ($list_name_to_print > 0) {
                    $row = sv_mysqli_fetch_array($result);
                    $LISTIDlist_names[$i] = $row[0];
                } else {
                    $LISTIDlist_names[$i] = "";
                }
                $TOTALcalls = ($TOTALcalls + $LISTIDcalls[$i]);
                $LISTIDcount = $LISTIDcalls[$i];
                $LISTIDname = "$LISTIDlists[$i] - $LISTIDlist_names[$i]";
                /*while(strlen($LISTIDcount)>10) {
                $LISTIDcount = substr("$LISTIDcount", 0, -1);
                }
                $LISTIDname =    sprintf("%-40s", "$LISTIDlists[$i] - $LISTIDlist_names[$i]");
                while(strlen($LISTIDname)>40) {
                $LISTIDname = substr("$LISTIDname", 0, -1);
                }*/
                #$ASCII_text .= "| $LISTIDname | $LISTIDcount |\n";
                $sal[$this->lang->line("csv_estadisticasIdListas")][$this->lang->line("csv_estadisticasIdListas_registros")][$i][$this->lang->line("csv_estadisticasIdListas_registros_n_llamadas")] = $LISTIDname;
                $sal[$this->lang->line("csv_estadisticasIdListas")][$this->lang->line("csv_estadisticasIdListas_registros")][$i][$this->lang->line("csv_estadisticasIdListas_registros_n_listas")] = $LISTIDcount;
                $i++;
            }
            $sal[$this->lang->line("csv_estadisticasIdListas")][$this->lang->line("csv_estadisticasIdListas_total")] = $TOTALcalls;
            #Carrier stats
            $query = "select dialstatus,count(*) AS C,campaign_id from vicidial_carrier_log vcl,vicidial_log vl where vcl.uniqueid=vl.uniqueid and DATE(vcl.call_date) > DATE('$fechaInicial') and DATE(vcl.call_date) < DATE('$fechaFinal') and DATE(vl.call_date) > DATE('$fechaInicial') and DATE(vl.call_date) < DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista group by dialstatus $and ";
            if ($archived) {
                $query = " select dialstatus,count(*) AS C,campaign_id from vicidial_carrier_log vcl,vicidial_log_archive vl where vcl.uniqueid=vl.uniqueid and DATE(vcl.call_date) > DATE('$fechaInicial') and DATE(vcl.call_date) < DATE('$fechaFinal') and DATE(vl.call_date) > DATE('$fechaInicial') and DATE(vl.call_date) < DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista group by dialstatus $and ";
            }

            $result = sv_mysqli_query($con, $query);
            $carrierstatuses_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            $TOTCARcalls = 0;
            $sal["carrier"]["Registros"] = array();
            while ($i < $carrierstatuses_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $TOTCARcalls = ($TOTCARcalls + $row[1]);
                $CARstatus = sprintf("%-20s", $row[0]);while (strlen($CARstatus) > 20) {$CARstatus = substr("$CARstatus", 0, -1);}
                $CARcount = sprintf("%10s", $row[1]);while (strlen($CARcount) > 10) {$CARcount = substr("$CARcount", 0, -1);}
                $sal["carrier"]["Registros"][$i]["estado"] = $CARstatus;
                $sal["carrier"]["Registros"][$i]["llamadas"] = $CARcount;
                $i++;
            }
            $TOTCARcalls = sprintf("%10s", $TOTCARcalls);while (strlen($TOTCARcalls) > 10) {$TOTCARcalls = substr("$TOTCARcalls", 0, -1);}
            $sal["carrier"]["total"] = $TOTCARcalls;
            $max_calls = 1;
            $TOTCATcalls = 0;
            $r = 0;
            $i = 0;
            $sal[$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados")][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_registros")] = array();
            while ($r < $statcats_to_print) {
                if ($vsc_id[$r] != 'UNDEFINED') {
                    $TOTCATcalls = ($TOTCATcalls + $vsc_count[$r]);
                    $category = sprintf("%-20s", $vsc_id[$r]);while (strlen($category) > 20) {$category = substr("$category", 0, -1);}
                    $CATcount = sprintf("%10s", $vsc_count[$r]);while (strlen($CATcount) > 10) {$CATcount = substr("$CATcount", 0, -1);}
                    $CATname = sprintf("%-30s", $vsc_name[$r]);while (strlen($CATname) > 30) {$CATname = substr("$CATname", 0, -1);}
                    if ($vsc_count[$r] > $max_calls) {$max_calls = $vsc_count[$r];}
                    $i++;
                    #$ASCII_text .= "| $category | $CATcount | $CATname |\n";
                    $sal[$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados")][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_registros")][$i][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_registros_n_categoria")] = $category;
                    $sal[$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados")][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_registros")][$i][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_registros_n_llamadas")] = $CATcount;
                    $sal[$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados")][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_registros")][$i][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_registros_n_descripcion")] = $CATname;
                }
                $r++;
            }
            $TOTCATcalls = sprintf("%10s", $TOTCATcalls);while (strlen($TOTCATcalls) > 10) {$TOTCATcalls = substr("$TOTCATcalls", 0, -1);}
            $sal[$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados")][$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados_total")] = $TOTCATcalls;
            $TOTagents = 0;
            $TOTcalls = 0;
            $TOTtime = 0;
            $TOTavg = 0;
            $max_calls = 1;
            $max_total_time = 1;
            $max_avg_time = 1;
            $RAWuser_calls = $RAWuser = $RAWfull_name = $RAWuser_talk = $RAWuser_average = array();
            $query = "select vicidial_log.user,full_name,count(*) AS C,sum(length_in_sec) AS S,avg(length_in_sec) AS A from vicidial_log,vicidial_users where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and and vicidial_log.user is not null and length_in_sec is not null and length_in_sec >= 0 and vicidial_log.user=vicidial_users.user group by vicidial_log.user ";
            if ($archived) {
                $query = " select vicidial_log_archive.user,full_name,count(*) AS C,sum(length_in_sec) AS S,avg(length_in_sec) AS A from vicidial_log_archive,vicidial_users where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  $and and vicidial_log_archive.user is not null and length_in_sec is not null and length_in_sec >= 0 and vicidial_log_archive.user=vicidial_users.user group by vicidial_log_archive.user ";
            }
            $result = sv_mysqli_query($con, $query);
            $users_to_print = sv_mysqli_num_rows($result);
            $i = 0;
            while ($i < $users_to_print) {
                $row = sv_mysqli_fetch_array($result);
                $RAWuser[$i] = $row[0];
                $RAWfull_name[$i] = $row[1];
                $RAWuser_calls[$i] = $row[2];
                $RAWuser_talk[$i] = $row[3];
                $RAWuser_average[$i] = $row[4];
                $TOTcalls = ($TOTcalls + $row[2]);
                $TOTtime = ($TOTtime + $row[3]);
                $i++;
            }
            $i = 0;
            $sal[$this->lang->line("csv_estadisticasAgente")] = array();
            $sal[$this->lang->line("csv_estadisticasAgente")][$this->lang->line("csv_estadisticasAgente_registros")] = array();
            while ($i < $users_to_print) {
                $user = sprintf("%-6s", $RAWuser[$i]);while (strlen($user) > 20) {$user = substr("$user", 0, -1);}
                //$user = $RAWuser[$i];
                $full_name = sprintf("%-15s", $RAWfull_name[$i]);while (strlen($full_name) > 15) {$full_name = substr("$full_name", 0, -1);}
                //$full_name = $RAWfull_name[$i];
                $include_rollover = "YES";
                if (preg_match("/YES/i", $include_rollover)) {
                    $length_in_secZ = 0;
                    $queue_secondsZ = 0;
                    $agent_alert_delayZ = 0;
                    $query = "select length_in_sec,queue_seconds,agent_alert_delay from vicidial_closer_log,vicidial_inbound_groups where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id = $campana and list_id = $lista  and group_id=campaign_id and user='$RAWuser[$i]' and list_id = $lista";
                    //$sal["querys"][] = $query;
                    $y = 0;
                    $result = sv_mysqli_query($con, $query);
                    $INallcalls_to_printZ = sv_mysqli_num_rows($result);
                    while ($y < $INallcalls_to_printZ) {
                        $row = sv_mysqli_fetch_array($result);
                        $length_in_secZ = $row[0];
                        $queue_secondsZ = $row[1];
                        $agent_alert_delayZ = $row[2];
                        $CIdelay = round($agent_alert_delayZ / 1000);
                        $thiscallsec = (($length_in_secZ - $queue_secondsZ) - $CIdelay);
                        if ($thiscallsec < 0) {
                            $thiscallsec = 0;
                        }
                        $inCIsec = ($inCIsec + $thiscallsec);
                        $y++;
                    }
                    $inCIcallsRAW = $y;
                    $RAWuser_talk[$i] = ($RAWuser_talk[$i] + $inCIsec);
                    $RAWuser_calls[$i] = ($RAWuser_calls[$i] + $inCIcallsRAW);
                    $TOTcalls = ($TOTcalls + $inCIcallsRAW);
                    $TOTtime = ($TOTtime + $inCIsec);
                }
                $USERcalls = sprintf("%10s", $RAWuser_calls[$i]);
                $USERtotTALK = $RAWuser_talk[$i];
                $USERavgTALK = round($RAWuser_talk[$i] / $RAWuser_calls[$i]);
                if ($RAWuser_calls[$i] > $max_calls) {$max_calls = $RAWuser_calls[$i];}
                if ($RAWuser_talk[$i] > $max_total_time) {$max_total_time = $RAWuser_talk[$i];}
                if ($USERavgTALK > $max_avg_time) {$max_avg_time = $USERavgTALK;}
                $USERtotTALK_MS = intval($USERtotTALK);
                $USERavgTALK_MS = intval($USERavgTALK);
                $USERtotTALK_MS = sprintf("%9s", $USERtotTALK_MS);
                $USERavgTALK_MS = sprintf("%6s", $USERavgTALK_MS);
                $sal[$this->lang->line("csv_estadisticasAgente")][$this->lang->line("csv_estadisticasAgente_registros")][$i][$this->lang->line("csv_estadisticasAgente_registros_n_agente")] = $user;
                $sal[$this->lang->line("csv_estadisticasAgente")][$this->lang->line("csv_estadisticasAgente_registros")][$i][$this->lang->line("csv_estadisticasAgente_registros_n_nombre")] = $full_name;
                $sal[$this->lang->line("csv_estadisticasAgente")][$this->lang->line("csv_estadisticasAgente_registros")][$i][$this->lang->line("csv_estadisticasAgente_registros_n_llamadas")] = $USERcalls;
                $sal[$this->lang->line("csv_estadisticasAgente")][$this->lang->line("csv_estadisticasAgente_registros")][$i][$this->lang->line("csv_estadisticasAgente_registros_n_hora")] = $USERtotTALK_MS;
                $sal[$this->lang->line("csv_estadisticasAgente")][$this->lang->line("csv_estadisticasAgente_registros")][$i][$this->lang->line("csv_estadisticasAgente_registros_n_promedio")] = $USERavgTALK_MS;
                $i++;
                $tiempoFinal = time(); ////////////////////////////////////////////////////////////////////////////////////////////////////
                //$sal["TiempoShidori4"]=$tiempoFinal-$tiempoInicial;
                $tiempoInicial = time();

            }
            sv_mysqli_close($con);
            if (!isset($_GET["csv"])) {
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=\"ReporteSalientes(" . $fechaInicial . "-" . $fechaFinal . ").csv\"");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');
                $test = array();
                switch ($_GET["donde"]) {
                    case 2:
                        $this->trata($out, $sal[$this->lang->line("csv_estadoLlamada")], $test);
                        break;
                    case 1:
                        $this->trata($out, $sal[$this->lang->line("csv_razonesColgado")], $test);
                        break;
                    case 3:
                        $this->trata($out, $sal[$this->lang->line("csv_estadisticasCategoriasEstadosPersonalizados")], $test);
                        break;
                    case 4:
                        $this->trata($out, $sal[$this->lang->line("csv_estadisticasAgente")], $test);
                        break;
                    case 5:
                        $this->trata($out, $sal[$this->lang->line("csv_estadisticasIdListas")], $test);
                        break;

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

    public function infoCampaHistSal()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportesalientes', "spanish");
                break;
            case "en":
                $this->lang->load('reportesalientes', "english");
                break;
            default:
                $this->lang->load('reportesalientes', "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';

            $campa = limpia($_POST["campana"]);

            $sal = [];
            $con = getConnection();

            if ($_SESSION["Cliente"] == -1) {
                $and = "";
            }
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }
            $query = "SELECT * FROM asterisk.vicidial_campaigns;";

            $query2 = "SELECT vicidial_statuses.status as statusu, vicidial_statuses.status_name as name FROM vicidial_statuses " .
                "UNION SELECT vicidial_campaign_statuses.status as statusu, vicidial_campaign_statuses.status_name as name from vicidial_campaign_statuses " .
                " WHERE vicidial_campaign_statuses.campaign_id = '" . $campa . "'";

            $contador = 0;
            $datosxD = [];
            $estatus = [];

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

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

                if (!empty($row2["statusu"])) {

                    $query3 = "SELECT count(*) as cuantos, DATE_FORMAT(vicidial_log.call_date, '%Y-%m-%d %H:00:00') as fechaW,call_date from vicidial_log " .
                        "where vicidial_log.campaign_id = '" . $campa . "' and vicidial_log.status = '" . $row2["statusu"] . "'" .
                        "GROUP BY YEAR(vicidial_log.call_date), MONTH(vicidial_log.call_date), DAY(vicidial_log.call_date), HOUR(vicidial_log.call_date) ";

                    if ($archived) {
                        $query3 .= " UNION SELECT count(*) as cuantos, DATE_FORMAT(vicidial_log_archive.call_date, '%Y-%m-%d %H:00:00') as fechaW,call_date from vicidial_log_archive " .
                            "where vicidial_log_archive.campaign_id = '" . $campa . "' and vicidial_log_archive.status = '" . $row2["statusu"] . "'" .
                            "GROUP BY YEAR(vicidial_log_archive.call_date), MONTH(vicidial_log_archive.call_date), DAY(vicidial_log_archive.call_date), HOUR(vicidial_log_archive.call_date) ";

                    }
                    $query3 = "SELECT SUM(T.cuantos) AS cuantos,fechaW FROM ($query3) AS T GROUP BY YEAR(T.call_date), MONTH(T.call_date), DAY(T.call_date), HOUR(T.call_date) order by (T.call_date) ASC";

                    $result4 = sv_mysqli_query($con, $query3);

                    $contador2 = 0;

                    $contadorLlamadas = 0;

                    while ($row4 = sv_mysqli_fetch_array($result4)) {

                        $estatus[$contador]["calls"][$contador2]["cuenta"] = $row4["cuantos"];
                        $estatus[$contador]["calls"][$contador2]["fecha"] = $row4["fechaW"];

                        $contador2++;
                        $contadorLlamadas++;

                    }

                    if ($contadorLlamadas != 0) {

                        $estatus[$contador]["estatus"] = $row2["name"];

                    }

                }

                $contador++;

            }

            $sal["estado"] = "ok";
            $sal["estatus"] = $estatus;
            $this->output->set_output(json_encode($sal));
            //$this->output->set_output(json_encode($campa));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosSalientes");
            $this->output->set_output(json_encode($sal));
        }
    }

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