<?php

require_once "BASEPATH.php";

class ReporteEntrantes 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 MathZDC($a, $b)
    {
        if ($b == 0) {
            return 0;
        }

        return $a / $b;
    }
    public function getDialReport()
    {
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && (strpos($_SESSION["Grupo"], GRUPO_ADMINS) !== false)) {
            //header('Content-type: application/json');
            header('Content-Type: application/csv');
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $sal = array();
            $cliente = $_SESSION["Cliente"];
            $donde = "";
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }

            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }

            // Leyendo los grupos
            $gruposStr = "";
            $nombreCampana = "";
            if (isset($_GET["grupos"]) && is_array($_GET["grupos"]) && !empty($_GET["grupos"])) {
                $grupos = $_GET["grupos"];
                $gruposStr = "";
                foreach ($grupos as $grupo) {
                    $gruposStr .= "'$grupo',";
                    $nombreCampana .= "$grupo,";
                }
                $gruposStr = substr($gruposStr, 0, -1);

            } else {

                if ($cliente != -1) {
                    $gruposStr = "SELECT group_id FROM vicidial_inbound_groups WHERE user_group  = '$cliente'";
                } else {
                    $gruposStr = "SELECT group_id FROM vicidial_inbound_groups ";
                }

                $nombreCampana = "Todos los grupos de entrada";

            }

            $filtroFecha = "";
            if (isset($_GET["fechaInicial"]) && isset($_GET["fechaFinal"])) {
                $fechaInicial = limpia($_GET["fechaInicial"]);
                $fechaFinal = limpia($_GET["fechaFinal"]);
                $filtroFecha = "AND DATE(call_date) >= DATE('$fechaInicial') AND DATE(call_date) <= DATE('$fechaFinal')";
            }
            // Leyendo los grupos

            $query = "SELECT group_id,group_name FROM vicidial_inbound_groups WHERE group_id IN ($gruposStr) $donde";

            //echo($query);
            $result = sv_mysqli_query($con, $query);
            $sal["Registros"] = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT lead_id,(SELECT list_name FROM vicidial_lists WHERE list_id = vicidial_closer_log.list_id) AS list_id,call_date,status,phone_number,user,'INBOUND' AS alt_dial FROM vicidial_closer_log WHERE campaign_id IN ('" . $row["group_id"] . "') $filtroFecha ORDER BY call_date";
                if ($archived) {
                    $query = "SELECT lead_id,(SELECT list_name FROM vicidial_lists WHERE list_id = vicidial_closer_log_archive.list_id) AS list_id,call_date,status,phone_number,user,'INBOUND' AS alt_dial FROM vicidial_closer_log_archive WHERE campaign_id IN ('" . $row["group_id"] . "') $filtroFecha ORDER BY call_date";
                }
                $result1 = sv_mysqli_query($con, $query);
                $out = "";
                $stmtNombres = "SELECT 'Orden de numero' AS label_alt_dial,'id de registro' AS label_lead_id, 'Fecha registro' AS label_entry_date, 'Fecha de modificacion' AS label_modify_date, 'Estado del registro' AS label_status, 'Usuario' AS label_user, 'Nombre de Lista' AS label_list_id, 'Llamado desde el ultimo reinicio' AS label_called_since_last_reset, 'Zona horaria' AS label_gmt_offset_now, 'Codigo telefonico' AS label_phone_code, 'Fecha de nacimiento' AS label_date_of_birth,'Veces llamado' AS label_called_count, 'Fecha del ultimo llamado' AS label_last_local_call_time,'Pais' AS label_country_code,'Rango' AS label_rank, 'Autor' AS label_owner,'Titulo' AS label_title,'Nombre' AS label_first_name,'Segundo Nombre' AS label_middle_initial,'Apellidos' AS label_last_name,'Direccion' AS label_address1,'Direccion 2' AS label_address2,'Telefono alterno 2' AS label_address3,'Ciudad' AS label_city,'Estado' AS label_state,'Provincia' AS label_province,'Codigo Postal' AS label_postal_code,label_vendor_lead_code,'Genero' AS label_gender,'Telefono' AS label_phone_number,'Telefono alterno' AS label_alt_phone,label_security_phrase,'Email' AS label_email,'Comentarios' AS label_comments from system_settings";
                $resultNombres = sv_mysqli_query($con, $stmtNombres, MYSQLI_ASSOC);
                $rowNombres = sv_mysqli_fetch_array($resultNombres);
                while ($row1 = sv_mysqli_fetch_array($result1)) {
                    //$sal["Registros"][] = $row1;
                    $llaves = array_keys($row1);
                    $objeto = array();
                    for ($i = 0; $i < count($llaves); $i++) {
                        $titulo = "label_" . $llaves[$i];
                        if (array_key_exists($titulo, $rowNombres) && $rowNombres[$titulo] != "") {
                            $objeto[$rowNombres[$titulo]] = $row1[$llaves[$i]];
                        } else {
                            $objeto[$llaves[$i]] = $row1[$llaves[$i]];
                        }
                    }
                    $sal["Registros"][] = $objeto;
                }
                foreach ($sal["Registros"] as &$nombre) {
                    if ($nombre["Usuario"] == "VDAD") {
                        $nombre["Usuario"] = "SISTEMA";
                    }
                }

            }

            header("Content-Disposition: attachment; filename=\"Registro de llamadas entrada $nombreCampana .csv\"");
            ob_start();
            $out = fopen('php://output', 'w');
            $test = array();
            $this->trata($out, $sal["Registros"], $test);
            fclose($out);
            $str = ob_get_contents();
            ob_end_clean();
            $this->output->set_output($str);

        }
    }
    public function inboundReport()
    {
        include_once RUTA_APP . 'Conexion.php';
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reporteentrantes', "spanish");
                break;
            case "en":
                $this->lang->load('reporteentrantes', "english");
                break;
            default:
                $this->lang->load('reporteentrantes', "spanish");
                break;
        }
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $cliente = $_SESSION["Cliente"];
            $sal = array();
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }

            $gruposStr = "";
            if (isset($_GET["grupos"]) && is_array($_GET["grupos"]) && !empty($_GET["grupos"])) {
                $grupos = $_GET["grupos"];
                $gruposStr = "";
                foreach ($grupos as $grupo) {
                    $gruposStr .= "'$grupo',";
                }
                $gruposStr = substr($gruposStr, 0, -1);

            } else {
                if ($cliente != -1) {
                    $gruposStr = "SELECT group_id FROM vicidial_inbound_groups WHERE user_group  = '$cliente'";
                } else {
                    $gruposStr = "SELECT group_id FROM vicidial_inbound_groups ";
                }

            }
            $fechaInicial = limpia($_GET["fechaInicial"]);
            $fechaFinal = limpia($_GET["fechaFinal"]);
            header('Content-type: application/json');
            $and = "";
            if ($cliente != -1) {
                $and = "AND campaign_id IN (SELECT group_id FROM vicidial_inbound_groups WHERE user_group  = '$cliente')";
            }
            $and1 = "";
            if ($cliente != -1) {
                $and1 = "AND comment_a IN (SELECT group_id FROM vicidial_inbound_groups WHERE user_group  = '$cliente')";
            }
            $salida = array();
            $query = "SELECT COUNT(closecallid),SUM(length_in_sec) FROM vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) $and and status IN('DROP','XDROP') ";
            if ($archived) {
                $query = "SELECT COUNT(closecallid),SUM(length_in_sec) from vicidial_closer_log_archive WHERE DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) $and and status IN('DROP','XDROP')";
            }

            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $DROPcalls = sprintf("%10s", $row[0]);

            $query = "SELECT COUNT(closecallid),SUM(length_in_sec) from vicidial_closer_log WHERE DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) $and";
            if ($archived) {
                $query = "SELECT COUNT(closecallid),SUM(length_in_sec) from vicidial_closer_log_archive WHERE DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) $and";
            }

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

            $query = "SELECT count(closecallid),sum(queue_seconds) from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) and status NOT IN('DROP','XDROP') $and";
            if ($archived) {
                $query = "SELECT count(closecallid),sum(queue_seconds) from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) and status NOT IN('DROP','XDROP') $and";
            }

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

            $query = "SELECT count(closecallid),sum(queue_seconds) from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) and status IN('DROP','XDROP') $and";
            if ($archived) {
                $query = "SELECT count(closecallid),sum(queue_seconds) from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and campaign_id IN ($gruposStr) and status IN('DROP','XDROP') $and";
            }

            $result2 = sv_mysqli_query($con, $query);
            $rowy = sv_mysqli_fetch_array($result2);

            $query = "SELECT count(*) AS C from live_inbound_log where DATE(start_time) >= DATE('$fechaInicial') and DATE(start_time) <= DATE('$fechaFinal') and comment_a IN ($gruposStr) and comment_b='START' $and1";
            $result3 = sv_mysqli_query($con, $query);
            $rowx = sv_mysqli_fetch_array($result3);

            $TOTALcalls = sprintf("%10s", $row[0]);
            $IVRcalls = sprintf("%10s", $rowx[0]);
            $TOTALsec = $row[1];
            $ANSWEREDcalls = sprintf("%10s", $rowW[0]);

            if (($DROPcalls < 1) or ($TOTALcalls < 1)) {
                $DROPpercent = '0';
            } else {
                $DROPpercent = (($DROPcalls / $TOTALcalls) * 100);
                $DROPpercent = round($DROPpercent, 0);
            }
            if (($rowy[0] < 1) or ($rowy[1] < 1)) {
                $average_hold_seconds = '0';
            } else {
                $average_hold_seconds = ($rowy[1] / $rowy[0]);
                $average_hold_seconds = round($average_hold_seconds, 0);
                $average_hold_seconds = sprintf("%10s", $average_hold_seconds);
            }
            if (($ANSWEREDcalls < 1) or ($DROPcalls < 1)) {
                $DROP_ANSWEREDpercent = '0';
            } else {
                $DROP_ANSWEREDpercent = (($DROPcalls / $ANSWEREDcalls) * 100);
                $DROP_ANSWEREDpercent = round($DROP_ANSWEREDpercent, 0);
            }
            if (($row[0] < 1) or ($TOTALsec < 1)) {
                $average_call_seconds = '0';
            } else {
                $average_call_seconds = ($TOTALsec / $row[0]);
                $average_call_seconds = round($average_call_seconds, 0);
                $average_call_seconds = sprintf("%10s", $average_call_seconds);
            }
            $ANSWEREDcalls = sprintf("%10s", $rowW[0]);
            if (($ANSWEREDcalls < 1) or ($TOTALcalls < 1)) {
                $ANSWEREDpercent = '0';
            } else {
                $ANSWEREDpercent = (($ANSWEREDcalls / $TOTALcalls) * 100);
                $ANSWEREDpercent = round($ANSWEREDpercent, 0);
            }
            if (($rowy[0] < 1) or ($ANSWEREDcalls < 1)) {
                $average_answer_seconds = '0';
            } else {
                $average_answer_seconds = ($rowW[1] / $rowW[0]);
                $average_answer_seconds = round($average_answer_seconds, 2);
                $average_answer_seconds = sprintf("%10s", $average_answer_seconds);
            }
            $salida["llamadasTotalesEnElGrupo"] = $TOTALcalls;
            $salida["duracionPromedioTodasLlamadas"] = $average_call_seconds;
            $salida["llamadasRespondidas"] = $ANSWEREDcalls;
            $salida["llamadasRespondidasPorcentaje"] = $ANSWEREDpercent;
            $salida["tiempoPromedioEsperaLlamadasFila"] = $average_answer_seconds;
            $salida["llamadasIVR"] = $IVRcalls;
            $salida["llamadasDejadasTotal"] = $DROPcalls;
            $salida["llamadasDejadasTotalPorcentaje"] = $DROPpercent;
            $salida["dejadosRespondidos"] = $DROP_ANSWEREDpercent;
            $salida["tiempoPromedioEsperaLlamadasDejadas"] = $average_hold_seconds;

            $query = "SELECT count(closecallid) AS C,queue_seconds from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by queue_seconds";
            if ($archived) {
                $query = "SELECT count(closecallid) AS C,queue_seconds from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by queue_seconds";
            }

            $result = sv_mysqli_query($con, $query);
            $hd_0 = 0;
            $hd_5 = 0;
            $hd10 = 0;
            $hd15 = 0;
            $hd20 = 0;
            $hd25 = 0;
            $hd30 = 0;
            $hd35 = 0;
            $hd40 = 0;
            $hd45 = 0;
            $hd50 = 0;
            $hd55 = 0;
            $hd60 = 0;
            $hd90 = 0;
            $hd99 = 0;
            $TOTALcalls = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $TOTALcalls = ($TOTALcalls + $row[0]);
                if ($row[1] == 0) {
                    $hd_0 = ($hd_0 + $row[0]);
                }
                if (($row[1] > 0) and ($row[1] <= 5)) {
                    $hd_5 = ($hd_5 + $row[0]);
                }
                if (($row[1] > 5) and ($row[1] <= 10)) {
                    $hd10 = ($hd10 + $row[0]);
                }
                if (($row[1] > 10) and ($row[1] <= 15)) {
                    $hd15 = ($hd15 + $row[0]);
                }
                if (($row[1] > 15) and ($row[1] <= 20)) {
                    $hd20 = ($hd20 + $row[0]);
                }
                if (($row[1] > 20) and ($row[1] <= 25)) {
                    $hd25 = ($hd25 + $row[0]);
                }
                if (($row[1] > 25) and ($row[1] <= 30)) {
                    $hd30 = ($hd30 + $row[0]);
                }
                if (($row[1] > 30) and ($row[1] <= 35)) {
                    $hd35 = ($hd35 + $row[0]);
                }
                if (($row[1] > 35) and ($row[1] <= 40)) {
                    $hd40 = ($hd40 + $row[0]);
                }
                if (($row[1] > 40) and ($row[1] <= 45)) {
                    $hd45 = ($hd45 + $row[0]);
                }
                if (($row[1] > 45) and ($row[1] <= 50)) {
                    $hd50 = ($hd50 + $row[0]);
                }
                if (($row[1] > 50) and ($row[1] <= 55)) {
                    $hd55 = ($hd55 + $row[0]);
                }
                if (($row[1] > 55) and ($row[1] <= 60)) {
                    $hd60 = ($hd60 + $row[0]);
                }
                if (($row[1] > 60) and ($row[1] <= 90)) {
                    $hd90 = ($hd90 + $row[0]);
                }
                if ($row[1] > 90) {
                    $hd99 = ($hd99 + $row[0]);
                }
            }
            $hd_0 = sprintf("%5s", $hd_0);
            $hd_5 = sprintf("%5s", $hd_5);
            $hd10 = sprintf("%5s", $hd10);
            $hd15 = sprintf("%5s", $hd15);
            $hd20 = sprintf("%5s", $hd20);
            $hd25 = sprintf("%5s", $hd25);
            $hd30 = sprintf("%5s", $hd30);
            $hd35 = sprintf("%5s", $hd35);
            $hd40 = sprintf("%5s", $hd40);
            $hd45 = sprintf("%5s", $hd45);
            $hd50 = sprintf("%5s", $hd50);
            $hd55 = sprintf("%5s", $hd55);
            $hd60 = sprintf("%5s", $hd60);
            $hd90 = sprintf("%5s", $hd90);
            $hd99 = sprintf("%5s", $hd99);
            $sal["tabla1"]["0"] = $hd_0;
            $sal["tabla1"]["5"] = $hd_5;
            $sal["tabla1"]["10"] = $hd10;
            $sal["tabla1"]["15"] = $hd15;
            $sal["tabla1"]["20"] = $hd20;
            $sal["tabla1"]["25"] = $hd25;
            $sal["tabla1"]["30"] = $hd30;
            $sal["tabla1"]["35"] = $hd35;
            $sal["tabla1"]["40"] = $hd40;
            $sal["tabla1"]["45"] = $hd45;
            $sal["tabla1"]["50"] = $hd50;
            $sal["tabla1"]["55"] = $hd55;
            $sal["tabla1"]["60"] = $hd60;
            $sal["tabla1"]["90"] = $hd90;
            $sal["tabla1"]["+90"] = $hd99;
            $sal["tabla1"]["total"] = $TOTALcalls;
            $query = "SELECT count(closecallid) AS C,queue_seconds from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and and status IN('DROP','XDROP') group by queue_seconds";
            if ($archived) {
                $query = "SELECT count(closecallid) AS C,queue_seconds from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and and status IN('DROP','XDROP') group by queue_seconds";
            }

            $result = sv_mysqli_query($con, $query);
            $hd_0 = 0;
            $hd_5 = 0;
            $hd10 = 0;
            $hd15 = 0;
            $hd20 = 0;
            $hd25 = 0;
            $hd30 = 0;
            $hd35 = 0;
            $hd40 = 0;
            $hd45 = 0;
            $hd50 = 0;
            $hd55 = 0;
            $hd60 = 0;
            $hd90 = 0;
            $hd99 = 0;
            $BDdropCALLS = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $BDdropCALLS = ($BDdropCALLS + $row[0]);
                if ($row[1] == 0) {
                    $hd_0 = ($hd_0 + $row[0]);
                }
                if (($row[1] > 0) and ($row[1] <= 5)) {
                    $hd_5 = ($hd_5 + $row[0]);
                }
                if (($row[1] > 5) and ($row[1] <= 10)) {
                    $hd10 = ($hd10 + $row[0]);
                }
                if (($row[1] > 10) and ($row[1] <= 15)) {
                    $hd15 = ($hd15 + $row[0]);
                }
                if (($row[1] > 15) and ($row[1] <= 20)) {
                    $hd20 = ($hd20 + $row[0]);
                }
                if (($row[1] > 20) and ($row[1] <= 25)) {
                    $hd25 = ($hd25 + $row[0]);
                }
                if (($row[1] > 25) and ($row[1] <= 30)) {
                    $hd30 = ($hd30 + $row[0]);
                }
                if (($row[1] > 30) and ($row[1] <= 35)) {
                    $hd35 = ($hd35 + $row[0]);
                }
                if (($row[1] > 35) and ($row[1] <= 40)) {
                    $hd40 = ($hd40 + $row[0]);
                }
                if (($row[1] > 40) and ($row[1] <= 45)) {
                    $hd45 = ($hd45 + $row[0]);
                }
                if (($row[1] > 45) and ($row[1] <= 50)) {
                    $hd50 = ($hd50 + $row[0]);
                }
                if (($row[1] > 50) and ($row[1] <= 55)) {
                    $hd55 = ($hd55 + $row[0]);
                }
                if (($row[1] > 55) and ($row[1] <= 60)) {
                    $hd60 = ($hd60 + $row[0]);
                }
                if (($row[1] > 60) and ($row[1] <= 90)) {
                    $hd90 = ($hd90 + $row[0]);
                }
                if ($row[1] > 90) {
                    $hd99 = ($hd99 + $row[0]);
                }
            }
            $hd_0 = sprintf("%5s", $hd_0);
            $hd_5 = sprintf("%5s", $hd_5);
            $hd10 = sprintf("%5s", $hd10);
            $hd15 = sprintf("%5s", $hd15);
            $hd20 = sprintf("%5s", $hd20);
            $hd25 = sprintf("%5s", $hd25);
            $hd30 = sprintf("%5s", $hd30);
            $hd35 = sprintf("%5s", $hd35);
            $hd40 = sprintf("%5s", $hd40);
            $hd45 = sprintf("%5s", $hd45);
            $hd50 = sprintf("%5s", $hd50);
            $hd55 = sprintf("%5s", $hd55);
            $hd60 = sprintf("%5s", $hd60);
            $hd90 = sprintf("%5s", $hd90);
            $hd99 = sprintf("%5s", $hd99);
            $sal["tabla2"]["0"] = $hd_0;
            $sal["tabla2"]["5"] = $hd_5;
            $sal["tabla2"]["10"] = $hd10;
            $sal["tabla2"]["15"] = $hd15;
            $sal["tabla2"]["20"] = $hd20;
            $sal["tabla2"]["25"] = $hd25;
            $sal["tabla2"]["30"] = $hd30;
            $sal["tabla2"]["35"] = $hd35;
            $sal["tabla2"]["40"] = $hd40;
            $sal["tabla2"]["45"] = $hd45;
            $sal["tabla2"]["50"] = $hd50;
            $sal["tabla2"]["55"] = $hd55;
            $sal["tabla2"]["60"] = $hd60;
            $sal["tabla2"]["90"] = $hd90;
            $sal["tabla2"]["+90"] = $hd99;
            $sal["tabla2"]["total"] = $BDdropCALLS;

            $stmt = "SELECT count(closecallid),queue_seconds from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and and status NOT IN('DROP','XDROP') group by queue_seconds";
            if ($archived) {
                $stmt = "SELECT count(closecallid),queue_seconds from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and and status NOT IN('DROP','XDROP') group by queue_seconds";
            }
            $rslt = sv_mysqli_query($con, $stmt);
            $reasons_to_print = sv_mysqli_num_rows($rslt);
            $i = 0;
            $ad_0 = $ad_5 = $ad10 = $ad15 = $ad20 = $ad25 = $ad30 = $ad35 = $ad40 = $ad45 = $ad50 = $ad55 = $ad60 = $ad90 = $ad99 = 0;
            $BDansweredCALLS = 0;
            while ($i < $reasons_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $BDansweredCALLS = ($BDansweredCALLS + $row[0]);
                ### Get interval totals
                if ($row[1] == 0) {
                    $ad_0 = ($ad_0 + $row[0]);
                }
                if (($row[1] > 0) and ($row[1] <= 5)) {
                    $ad_5 = ($ad_5 + $row[0]);
                }
                if (($row[1] > 5) and ($row[1] <= 10)) {
                    $ad10 = ($ad10 + $row[0]);
                }
                if (($row[1] > 10) and ($row[1] <= 15)) {
                    $ad15 = ($ad15 + $row[0]);
                }
                if (($row[1] > 15) and ($row[1] <= 20)) {
                    $ad20 = ($ad20 + $row[0]);
                }
                if (($row[1] > 20) and ($row[1] <= 25)) {
                    $ad25 = ($ad25 + $row[0]);
                }
                if (($row[1] > 25) and ($row[1] <= 30)) {
                    $ad30 = ($ad30 + $row[0]);
                }
                if (($row[1] > 30) and ($row[1] <= 35)) {
                    $ad35 = ($ad35 + $row[0]);
                }
                if (($row[1] > 35) and ($row[1] <= 40)) {
                    $ad40 = ($ad40 + $row[0]);
                }
                if (($row[1] > 40) and ($row[1] <= 45)) {
                    $ad45 = ($ad45 + $row[0]);
                }
                if (($row[1] > 45) and ($row[1] <= 50)) {
                    $ad50 = ($ad50 + $row[0]);
                }
                if (($row[1] > 50) and ($row[1] <= 55)) {
                    $ad55 = ($ad55 + $row[0]);
                }
                if (($row[1] > 55) and ($row[1] <= 60)) {
                    $ad60 = ($ad60 + $row[0]);
                }
                if (($row[1] > 60) and ($row[1] <= 90)) {
                    $ad90 = ($ad90 + $row[0]);
                }
                if ($row[1] > 90) {
                    $ad99 = ($ad99 + $row[0]);
                }
                $i++;
            }
            ### Calculate cumulative totals
            $Cad_0 = $ad_0;
            $Cad_5 = ($Cad_0 + $ad_5);
            $Cad10 = ($Cad_5 + $ad10);
            $Cad15 = ($Cad10 + $ad15);
            $Cad20 = ($Cad15 + $ad20);
            $Cad25 = ($Cad20 + $ad25);
            $Cad30 = ($Cad25 + $ad30);
            $Cad35 = ($Cad30 + $ad35);
            $Cad40 = ($Cad35 + $ad40);
            $Cad45 = ($Cad40 + $ad45);
            $Cad50 = ($Cad45 + $ad50);
            $Cad55 = ($Cad50 + $ad55);
            $Cad60 = ($Cad55 + $ad60);
            $Cad90 = ($Cad60 + $ad90);
            $Cad99 = ($Cad90 + $ad99);
            ### Calculate interval percentages
            $pad_0 = 0;
            $pad_5 = 0;
            $pad10 = 0;
            $pad15 = 0;
            $pad20 = 0;
            $pad25 = 0;
            $pad30 = 0;
            $pad35 = 0;
            $pad40 = 0;
            $pad45 = 0;
            $pad50 = 0;
            $pad55 = 0;
            $pad60 = 0;
            $pad90 = 0;
            $pad99 = 0;
            $pCad_0 = 0;
            $pCad_5 = 0;
            $pCad10 = 0;
            $pCad15 = 0;
            $pCad20 = 0;
            $pCad25 = 0;
            $pCad30 = 0;
            $pCad35 = 0;
            $pCad40 = 0;
            $pCad45 = 0;
            $pCad50 = 0;
            $pCad55 = 0;
            $pCad60 = 0;
            $pCad90 = 0;
            $pCad99 = 0;
            $ApCad_0 = 0;
            $ApCad_5 = 0;
            $ApCad10 = 0;
            $ApCad15 = 0;
            $ApCad20 = 0;
            $ApCad25 = 0;
            $ApCad30 = 0;
            $ApCad35 = 0;
            $ApCad40 = 0;
            $ApCad45 = 0;
            $ApCad50 = 0;
            $ApCad55 = 0;
            $ApCad60 = 0;
            $ApCad90 = 0;
            $ApCad99 = 0;
            if (($BDansweredCALLS > 0) and ($TOTALcalls > 0)) {
                $pad_0 = ($this->MathZDC($ad_0, $TOTALcalls) * 100);
                $pad_0 = round($pad_0, 0);
                $pad_5 = ($this->MathZDC($ad_5, $TOTALcalls) * 100);
                $pad_5 = round($pad_5, 0);
                $pad10 = ($this->MathZDC($ad10, $TOTALcalls) * 100);
                $pad10 = round($pad10, 0);
                $pad15 = ($this->MathZDC($ad15, $TOTALcalls) * 100);
                $pad15 = round($pad15, 0);
                $pad20 = ($this->MathZDC($ad20, $TOTALcalls) * 100);
                $pad20 = round($pad20, 0);
                $pad25 = ($this->MathZDC($ad25, $TOTALcalls) * 100);
                $pad25 = round($pad25, 0);
                $pad30 = ($this->MathZDC($ad30, $TOTALcalls) * 100);
                $pad30 = round($pad30, 0);
                $pad35 = ($this->MathZDC($ad35, $TOTALcalls) * 100);
                $pad35 = round($pad35, 0);
                $pad40 = ($this->MathZDC($ad40, $TOTALcalls) * 100);
                $pad40 = round($pad40, 0);
                $pad45 = ($this->MathZDC($ad45, $TOTALcalls) * 100);
                $pad45 = round($pad45, 0);
                $pad50 = ($this->MathZDC($ad50, $TOTALcalls) * 100);
                $pad50 = round($pad50, 0);
                $pad55 = ($this->MathZDC($ad55, $TOTALcalls) * 100);
                $pad55 = round($pad55, 0);
                $pad60 = ($this->MathZDC($ad60, $TOTALcalls) * 100);
                $pad60 = round($pad60, 0);
                $pad90 = ($this->MathZDC($ad90, $TOTALcalls) * 100);
                $pad90 = round($pad90, 0);
                $pad99 = ($this->MathZDC($ad99, $TOTALcalls) * 100);
                $pad99 = round($pad99, 0);

                $pCad_0 = ($this->MathZDC($Cad_0, $TOTALcalls) * 100);
                $pCad_0 = round($pCad_0, 0);
                $pCad_5 = ($this->MathZDC($Cad_5, $TOTALcalls) * 100);
                $pCad_5 = round($pCad_5, 0);
                $pCad10 = ($this->MathZDC($Cad10, $TOTALcalls) * 100);
                $pCad10 = round($pCad10, 0);
                $pCad15 = ($this->MathZDC($Cad15, $TOTALcalls) * 100);
                $pCad15 = round($pCad15, 0);
                $pCad20 = ($this->MathZDC($Cad20, $TOTALcalls) * 100);
                $pCad20 = round($pCad20, 0);
                $pCad25 = ($this->MathZDC($Cad25, $TOTALcalls) * 100);
                $pCad25 = round($pCad25, 0);
                $pCad30 = ($this->MathZDC($Cad30, $TOTALcalls) * 100);
                $pCad30 = round($pCad30, 0);
                $pCad35 = ($this->MathZDC($Cad35, $TOTALcalls) * 100);
                $pCad35 = round($pCad35, 0);
                $pCad40 = ($this->MathZDC($Cad40, $TOTALcalls) * 100);
                $pCad40 = round($pCad40, 0);
                $pCad45 = ($this->MathZDC($Cad45, $TOTALcalls) * 100);
                $pCad45 = round($pCad45, 0);
                $pCad50 = ($this->MathZDC($Cad50, $TOTALcalls) * 100);
                $pCad50 = round($pCad50, 0);
                $pCad55 = ($this->MathZDC($Cad55, $TOTALcalls) * 100);
                $pCad55 = round($pCad55, 0);
                $pCad60 = ($this->MathZDC($Cad60, $TOTALcalls) * 100);
                $pCad60 = round($pCad60, 0);
                $pCad90 = ($this->MathZDC($Cad90, $TOTALcalls) * 100);
                $pCad90 = round($pCad90, 0);
                $pCad99 = ($this->MathZDC($Cad99, $TOTALcalls) * 100);
                $pCad99 = round($pCad99, 0);

                $ApCad_0 = ($this->MathZDC($Cad_0, $BDansweredCALLS) * 100);
                $ApCad_0 = round($ApCad_0, 0);
                $ApCad_5 = ($this->MathZDC($Cad_5, $BDansweredCALLS) * 100);
                $ApCad_5 = round($ApCad_5, 0);
                $ApCad10 = ($this->MathZDC($Cad10, $BDansweredCALLS) * 100);
                $ApCad10 = round($ApCad10, 0);
                $ApCad15 = ($this->MathZDC($Cad15, $BDansweredCALLS) * 100);
                $ApCad15 = round($ApCad15, 0);
                $ApCad20 = ($this->MathZDC($Cad20, $BDansweredCALLS) * 100);
                $ApCad20 = round($ApCad20, 0);
                $ApCad25 = ($this->MathZDC($Cad25, $BDansweredCALLS) * 100);
                $ApCad25 = round($ApCad25, 0);
                $ApCad30 = ($this->MathZDC($Cad30, $BDansweredCALLS) * 100);
                $ApCad30 = round($ApCad30, 0);
                $ApCad35 = ($this->MathZDC($Cad35, $BDansweredCALLS) * 100);
                $ApCad35 = round($ApCad35, 0);
                $ApCad40 = ($this->MathZDC($Cad40, $BDansweredCALLS) * 100);
                $ApCad40 = round($ApCad40, 0);
                $ApCad45 = ($this->MathZDC($Cad45, $BDansweredCALLS) * 100);
                $ApCad45 = round($ApCad45, 0);
                $ApCad50 = ($this->MathZDC($Cad50, $BDansweredCALLS) * 100);
                $ApCad50 = round($ApCad50, 0);
                $ApCad55 = ($this->MathZDC($Cad55, $BDansweredCALLS) * 100);
                $ApCad55 = round($ApCad55, 0);
                $ApCad60 = ($this->MathZDC($Cad60, $BDansweredCALLS) * 100);
                $ApCad60 = round($ApCad60, 0);
                $ApCad90 = ($this->MathZDC($Cad90, $BDansweredCALLS) * 100);
                $ApCad90 = round($ApCad90, 0);
                $ApCad99 = ($this->MathZDC($Cad99, $BDansweredCALLS) * 100);
                $ApCad99 = round($ApCad99, 0);
            }

            ### Format variables
            $ad_0 = sprintf("%5s", $ad_0);
            $ad_5 = sprintf("%5s", $ad_5);
            $ad10 = sprintf("%5s", $ad10);
            $ad15 = sprintf("%5s", $ad15);
            $ad20 = sprintf("%5s", $ad20);
            $ad25 = sprintf("%5s", $ad25);
            $ad30 = sprintf("%5s", $ad30);
            $ad35 = sprintf("%5s", $ad35);
            $ad40 = sprintf("%5s", $ad40);
            $ad45 = sprintf("%5s", $ad45);
            $ad50 = sprintf("%5s", $ad50);
            $ad55 = sprintf("%5s", $ad55);
            $ad60 = sprintf("%5s", $ad60);
            $ad90 = sprintf("%5s", $ad90);
            $ad99 = sprintf("%5s", $ad99);
            $Cad_0 = sprintf("%5s", $Cad_0);
            $Cad_5 = sprintf("%5s", $Cad_5);
            $Cad10 = sprintf("%5s", $Cad10);
            $Cad15 = sprintf("%5s", $Cad15);
            $Cad20 = sprintf("%5s", $Cad20);
            $Cad25 = sprintf("%5s", $Cad25);
            $Cad30 = sprintf("%5s", $Cad30);
            $Cad35 = sprintf("%5s", $Cad35);
            $Cad40 = sprintf("%5s", $Cad40);
            $Cad45 = sprintf("%5s", $Cad45);
            $Cad50 = sprintf("%5s", $Cad50);
            $Cad55 = sprintf("%5s", $Cad55);
            $Cad60 = sprintf("%5s", $Cad60);
            $Cad90 = sprintf("%5s", $Cad90);
            $Cad99 = sprintf("%5s", $Cad99);
            $pad_0 = sprintf("%4s", $pad_0) . '%';
            $pad_5 = sprintf("%4s", $pad_5) . '%';
            $pad10 = sprintf("%4s", $pad10) . '%';
            $pad15 = sprintf("%4s", $pad15) . '%';
            $pad20 = sprintf("%4s", $pad20) . '%';
            $pad25 = sprintf("%4s", $pad25) . '%';
            $pad30 = sprintf("%4s", $pad30) . '%';
            $pad35 = sprintf("%4s", $pad35) . '%';
            $pad40 = sprintf("%4s", $pad40) . '%';
            $pad45 = sprintf("%4s", $pad45) . '%';
            $pad50 = sprintf("%4s", $pad50) . '%';
            $pad55 = sprintf("%4s", $pad55) . '%';
            $pad60 = sprintf("%4s", $pad60) . '%';
            $pad90 = sprintf("%4s", $pad90) . '%';
            $pad99 = sprintf("%4s", $pad99) . '%';
            $pCad_0 = sprintf("%4s", $pCad_0) . '%';
            $pCad_5 = sprintf("%4s", $pCad_5) . '%';
            $pCad10 = sprintf("%4s", $pCad10) . '%';
            $pCad15 = sprintf("%4s", $pCad15) . '%';
            $pCad20 = sprintf("%4s", $pCad20) . '%';
            $pCad25 = sprintf("%4s", $pCad25) . '%';
            $pCad30 = sprintf("%4s", $pCad30) . '%';
            $pCad35 = sprintf("%4s", $pCad35) . '%';
            $pCad40 = sprintf("%4s", $pCad40) . '%';
            $pCad45 = sprintf("%4s", $pCad45) . '%';
            $pCad50 = sprintf("%4s", $pCad50) . '%';
            $pCad55 = sprintf("%4s", $pCad55) . '%';
            $pCad60 = sprintf("%4s", $pCad60) . '%';
            $pCad90 = sprintf("%4s", $pCad90) . '%';
            $pCad99 = sprintf("%4s", $pCad99) . '%';
            $ApCad_0 = sprintf("%4s", $ApCad_0) . '%';
            $ApCad_5 = sprintf("%4s", $ApCad_5) . '%';
            $ApCad10 = sprintf("%4s", $ApCad10) . '%';
            $ApCad15 = sprintf("%4s", $ApCad15) . '%';
            $ApCad20 = sprintf("%4s", $ApCad20) . '%';
            $ApCad25 = sprintf("%4s", $ApCad25) . '%';
            $ApCad30 = sprintf("%4s", $ApCad30) . '%';
            $ApCad35 = sprintf("%4s", $ApCad35) . '%';
            $ApCad40 = sprintf("%4s", $ApCad40) . '%';
            $ApCad45 = sprintf("%4s", $ApCad45) . '%';
            $ApCad50 = sprintf("%4s", $ApCad50) . '%';
            $ApCad55 = sprintf("%4s", $ApCad55) . '%';
            $ApCad60 = sprintf("%4s", $ApCad60) . '%';
            $ApCad90 = sprintf("%4s", $ApCad90) . '%';
            $ApCad99 = sprintf("%4s", $ApCad99) . '%';
            $BDansweredCALLS = sprintf("%10s", $BDansweredCALLS);

            $sal["tabla3"]["INTERVAL"]["0"] = $ad_0;
            $sal["tabla3"]["INTERVAL"]["5"] = $ad_5;
            $sal["tabla3"]["INTERVAL"]["10"] = $ad10;
            $sal["tabla3"]["INTERVAL"]["15"] = $ad15;
            $sal["tabla3"]["INTERVAL"]["20"] = $ad20;
            $sal["tabla3"]["INTERVAL"]["25"] = $ad25;
            $sal["tabla3"]["INTERVAL"]["30"] = $ad30;
            $sal["tabla3"]["INTERVAL"]["35"] = $ad35;
            $sal["tabla3"]["INTERVAL"]["40"] = $ad40;
            $sal["tabla3"]["INTERVAL"]["45"] = $ad45;
            $sal["tabla3"]["INTERVAL"]["50"] = $ad50;
            $sal["tabla3"]["INTERVAL"]["55"] = $ad55;
            $sal["tabla3"]["INTERVAL"]["60"] = $ad60;
            $sal["tabla3"]["INTERVAL"]["90"] = $ad90;
            $sal["tabla3"]["INTERVAL"]["+90"] = $ad99;
            $sal["tabla3"]["INTERVAL"]["Total"] = $BDansweredCALLS;

            $sal["tabla3"]["INT"]["0"] = $pad_0;
            $sal["tabla3"]["INT"]["5"] = $pad_5;
            $sal["tabla3"]["INT"]["10"] = $pad10;
            $sal["tabla3"]["INT"]["15"] = $pad15;
            $sal["tabla3"]["INT"]["20"] = $pad20;
            $sal["tabla3"]["INT"]["25"] = $pad25;
            $sal["tabla3"]["INT"]["30"] = $pad30;
            $sal["tabla3"]["INT"]["35"] = $pad35;
            $sal["tabla3"]["INT"]["40"] = $pad40;
            $sal["tabla3"]["INT"]["45"] = $pad45;
            $sal["tabla3"]["INT"]["50"] = $pad50;
            $sal["tabla3"]["INT"]["55"] = $pad55;
            $sal["tabla3"]["INT"]["60"] = $pad60;
            $sal["tabla3"]["INT"]["90"] = $pad90;
            $sal["tabla3"]["INT"]["+90"] = $pad99;
            $sal["tabla3"]["INT"]["Total"] = "";

            $sal["tabla3"]["CUMULATIVE"]["0"] = $Cad_0;
            $sal["tabla3"]["CUMULATIVE"]["5"] = $Cad_5;
            $sal["tabla3"]["CUMULATIVE"]["10"] = $Cad10;
            $sal["tabla3"]["CUMULATIVE"]["15"] = $Cad15;
            $sal["tabla3"]["CUMULATIVE"]["20"] = $Cad20;
            $sal["tabla3"]["CUMULATIVE"]["25"] = $Cad25;
            $sal["tabla3"]["CUMULATIVE"]["30"] = $Cad30;
            $sal["tabla3"]["CUMULATIVE"]["35"] = $Cad35;
            $sal["tabla3"]["CUMULATIVE"]["40"] = $Cad40;
            $sal["tabla3"]["CUMULATIVE"]["45"] = $Cad45;
            $sal["tabla3"]["CUMULATIVE"]["50"] = $Cad50;
            $sal["tabla3"]["CUMULATIVE"]["55"] = $Cad55;
            $sal["tabla3"]["CUMULATIVE"]["60"] = $Cad60;
            $sal["tabla3"]["CUMULATIVE"]["90"] = $Cad90;
            $sal["tabla3"]["CUMULATIVE"]["+90"] = $Cad99;
            $sal["tabla3"]["CUMULATIVE"]["Total"] = $BDansweredCALLS;

            $sal["tabla3"]["CUM"]["0"] = $pCad_0;
            $sal["tabla3"]["CUM"]["5"] = $pCad_5;
            $sal["tabla3"]["CUM"]["10"] = $pCad10;
            $sal["tabla3"]["CUM"]["15"] = $pCad15;
            $sal["tabla3"]["CUM"]["20"] = $pCad20;
            $sal["tabla3"]["CUM"]["25"] = $pCad25;
            $sal["tabla3"]["CUM"]["30"] = $pCad30;
            $sal["tabla3"]["CUM"]["35"] = $pCad35;
            $sal["tabla3"]["CUM"]["40"] = $pCad40;
            $sal["tabla3"]["CUM"]["45"] = $pCad45;
            $sal["tabla3"]["CUM"]["50"] = $pCad50;
            $sal["tabla3"]["CUM"]["55"] = $pCad55;
            $sal["tabla3"]["CUM"]["60"] = $pCad60;
            $sal["tabla3"]["CUM"]["90"] = $pCad90;
            $sal["tabla3"]["CUM"]["+90"] = $pCad99;
            $sal["tabla3"]["CUM"]["Total"] = "";

            $sal["tabla3"]["CUMANS"]["0"] = $ApCad_0;
            $sal["tabla3"]["CUMANS"]["5"] = $ApCad_5;
            $sal["tabla3"]["CUMANS"]["10"] = $ApCad10;
            $sal["tabla3"]["CUMANS"]["15"] = $ApCad15;
            $sal["tabla3"]["CUMANS"]["20"] = $ApCad20;
            $sal["tabla3"]["CUMANS"]["25"] = $ApCad25;
            $sal["tabla3"]["CUMANS"]["30"] = $ApCad30;
            $sal["tabla3"]["CUMANS"]["35"] = $ApCad35;
            $sal["tabla3"]["CUMANS"]["40"] = $ApCad40;
            $sal["tabla3"]["CUMANS"]["45"] = $ApCad45;
            $sal["tabla3"]["CUMANS"]["50"] = $ApCad50;
            $sal["tabla3"]["CUMANS"]["55"] = $ApCad55;
            $sal["tabla3"]["CUMANS"]["60"] = $ApCad60;
            $sal["tabla3"]["CUMANS"]["90"] = $ApCad90;
            $sal["tabla3"]["CUMANS"]["+90"] = $ApCad99;
            $sal["tabla3"]["CUMANS"]["Total"] = "";

            $stmt = "SELECT COUNT(closecallid),term_reason from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by term_reason";
            if ($archived) {
                $stmt = " SELECT COUNT(closecallid),term_reason from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by term_reason";
            }
            $rslt = sv_mysqli_query($con, $stmt);
            $reasons_to_print = sv_mysqli_num_rows($rslt);
            $i = 0;
            $TOTALcalls = 0;
            $sal["tabla4"] = array();
            $sal["tabla4"]["Registros"] = array();
            while ($i < $reasons_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $TOTALcalls = ($TOTALcalls + $row[0]);
                $REASONcount = ($row[0]);
                $reason = $row[1];
                $xd = array();
                $xd["razon"] = $reason;
                $xd["conteo"] = $REASONcount;
                $sal["tabla4"]["Registros"][] = $xd;
                $i++;
            }
            $TOTALcalls = sprintf("%10s", $TOTALcalls);
            $sal["tabla4"]["Total"] = $TOTALcalls;

            $sal["tabla5"] = array();
            $sal["tabla5"]["Registros"] = array();

            $stmt = "select vsc_id,vsc_name from vicidial_status_categories;";
            $rslt = sv_mysqli_query($con, $stmt);
            $statcats_to_print = sv_mysqli_num_rows($rslt);
            $i = 0;
            $TOTALsec = 0;
            $vsc_count = $vsc_name = $vsc_id = array();
            while ($i < $statcats_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $vsc_id[$i] = $row[0];
                $vsc_name[$i] = $row[1];
                $vsc_count[$i] = 0;
                $i++;
            }

            $status = $status_name = $human_answered = $category = $statname_list = $statcat_list = array();
            $q = 0;
            $stmt = "SELECT status,status_name,human_answered,category from vicidial_statuses";
            $rslt = sv_mysqli_query($con, $stmt);
            $statuses_to_print = sv_mysqli_num_rows($rslt);
            $p = 0;
            while ($p < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $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]";
                $q++;
                $p++;
            }



            $stmt = "SELECT campaign_id FROM vicidial_campaigns WHERE user_group='$cliente'";
            $rslt = sv_mysqli_query($con, $stmt);
            $campaigns_ids = "";

            while ($row = sv_mysqli_fetch_array($rslt)) {
                $campaigns_ids .= "'" . $row["campaign_id"] . "',";
            }
            $campaigns_ids = substr($campaigns_ids, 0, -1);



            $stmt = "SELECT status,status_name,human_answered,category from vicidial_campaign_statuses WHERE campaign_id IN ($campaigns_ids)";
            $rslt = sv_mysqli_query($con, $stmt);
            $statuses_to_print = sv_mysqli_num_rows($rslt);
            $p = 0;
            while ($p < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $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]";
                $q++;
                $p++;
            }

            $stmt = "SELECT COUNT(closecallid),status,sum(length_in_sec) from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by status";
            if ($archived) {
                $stmt = "SELECT COUNT(closecallid),status,sum(length_in_sec) from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by status";
            }

            $rslt = sv_mysqli_query($con, $stmt);
            $statuses_to_print = sv_mysqli_num_rows($rslt);
            $i = 0;
            $max_calls = $max_total_time = $max_avg_time = $max_callshr = 1000000;
            $TOTALcalls = 0;
            while ($i < $statuses_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $STATUScount = $row[0];
                $RAWstatus = $row[1];
                $r = 0;
                $foundstat = 0;
                while ($r < $statcats_to_print) {
                    if (isset($statcat_list[$RAWstatus]) && (($statcat_list[$RAWstatus] == "$vsc_id[$r]") and ($foundstat < 1))) {
                        $vsc_count[$r] = ($vsc_count[$r] + $STATUScount);
                    }
                    $r++;
                }
                $TOTALcalls = ($TOTALcalls + $row[0]);
                $STATUSrate = ($this->MathZDC($STATUScount, $this->MathZDC($TOTALsec, 3600)));
                $STATUSrate = sprintf("%.2f", $STATUSrate);

                $STATUShours = $row[2];
                $TOTALsec += $row[2];
                $STATUSavg_sec = $this->MathZDC($row[2], $STATUScount);
                $STATUSavg = $STATUSavg_sec;

                if ($row[0] > $max_calls) {
                    $max_calls = $row[0];
                }
                if ($row[2] > $max_total_time) {
                    $max_total_time = $row[2];
                }
                if ($STATUSavg_sec > $max_avg_time) {
                    $max_avg_time = $STATUSavg_sec;
                }
                if ($STATUSrate > $max_callshr) {
                    $max_callshr = $STATUSrate;
                }

                $status_name = "";
                $statcat = "";

                if (isset($statcat_list[$RAWstatus])) {

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

                }

                $xd = array();
                $xd["STATUS"] = $row[1];
                $xd["DESCRIPTION"] = $status_name;
                $xd["CATEGORY"] = $statcat;
                $xd["TOTALTIME"] = $STATUShours;
                $xd["CALLS"] = $STATUScount;
                $xd["AVERAGETIME"] = $STATUSavg;
                $xd["CALLSHOURS"] = $STATUSrate;

                $sal["tabla5"]["Registros"][] = $xd;
                $i++;
            }

            $TOTALrate = $this->MathZDC($TOTALcalls, $this->MathZDC($TOTALsec, 3600));
            $TOTALrate = sprintf("%.2f", $TOTALrate);
            $TOTALhours = $TOTALsec;
            $TOTALavg_sec = $this->MathZDC($TOTALsec, $TOTALcalls);
            $TOTALavg = $TOTALavg_sec;

            $sal["tabla5"]["Total"]["CALLS"] = $TOTALcalls;
            $sal["tabla5"]["Total"]["TOTALTIME"] = $TOTALhours;
            $sal["tabla5"]["Total"]["AVGTIME"] = $TOTALavg;
            $sal["tabla5"]["Total"]["CALLSHOURS"] = $TOTALrate;

            $sal["tabla6"] = array();
            $sal["tabla6"]["Registros"] = array();
            $sal["tabla6"]["Total"] = 0;

            $TOTCATcalls = 0;
            $r = 0;
            while ($r < $statcats_to_print) {
                if ($vsc_id[$r] != 'UNDEFINED') {
                    $TOTCATcalls = ($TOTCATcalls + $vsc_count[$r]);
                    $category = sprintf("%-20s", $vsc_id[$r]);
                    $CATcount = sprintf("%10s", $vsc_count[$r]);
                    $CATname = sprintf("%-30s", $vsc_name[$r]);
                    $xd = array();
                    $xd["CATEGORY"] = $category;
                    $xd["CALLS"] = $CATcount;
                    $xd["DESCRIPTION"] = $CATname;
                    $sal["tabla6"]["Registros"][] = $xd;
                }
                $r++;
            }
            $sal["tabla6"]["Total"] = $TOTCATcalls;
            $sal["tabla7"] = array();
            $TOTALcalls = 0;

            $stmt = "SELECT count(closecallid) AS C,queue_position from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by queue_position";
            if ($archived) {
                $stmt = "SELECT count(closecallid) AS C,queue_position from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and group by queue_position";
            }

            $rslt = sv_mysqli_query($con, $stmt);
            $positions_to_print = sv_mysqli_num_rows($rslt);
            $i = 0;
            $qp_1 = $qp_2 = $qp_3 = $qp_4 = $qp_5 = $qp_6 = $qp_7 = $qp_8 = $qp_9 = $qp10 = $qp15 = $qp20 = $qp25 = $qp99 = 0;
            while ($i < $positions_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $TOTALcalls = ($TOTALcalls + $row[0]);
                if (($row[1] > 0) and ($row[1] <= 1)) {
                    $qp_1 = ($qp_1 + $row[0]);
                }
                if (($row[1] > 1) and ($row[1] <= 2)) {
                    $qp_2 = ($qp_2 + $row[0]);
                }
                if (($row[1] > 2) and ($row[1] <= 3)) {
                    $qp_3 = ($qp_3 + $row[0]);
                }
                if (($row[1] > 3) and ($row[1] <= 4)) {
                    $qp_4 = ($qp_4 + $row[0]);
                }
                if (($row[1] > 4) and ($row[1] <= 5)) {
                    $qp_5 = ($qp_5 + $row[0]);
                }
                if (($row[1] > 5) and ($row[1] <= 6)) {
                    $qp_6 = ($qp_6 + $row[0]);
                }
                if (($row[1] > 6) and ($row[1] <= 7)) {
                    $qp_7 = ($qp_7 + $row[0]);
                }
                if (($row[1] > 7) and ($row[1] <= 8)) {
                    $qp_8 = ($qp_8 + $row[0]);
                }
                if (($row[1] > 8) and ($row[1] <= 9)) {
                    $qp_9 = ($qp_9 + $row[0]);
                }
                if (($row[1] > 9) and ($row[1] <= 10)) {
                    $qp10 = ($qp10 + $row[0]);
                }
                if (($row[1] > 10) and ($row[1] <= 15)) {
                    $qp15 = ($qp15 + $row[0]);
                }
                if (($row[1] > 15) and ($row[1] <= 20)) {
                    $qp20 = ($qp20 + $row[0]);
                }
                if (($row[1] > 20) and ($row[1] <= 25)) {
                    $qp25 = ($qp25 + $row[0]);
                }
                if ($row[1] > 25) {
                    $qp99 = ($qp99 + $row[0]);
                }
                $i++;
            }
            $sal["tabla7"]["1"] = $qp_1;
            $sal["tabla7"]["2"] = $qp_2;
            $sal["tabla7"]["3"] = $qp_3;
            $sal["tabla7"]["4"] = $qp_4;
            $sal["tabla7"]["5"] = $qp_5;
            $sal["tabla7"]["6"] = $qp_6;
            $sal["tabla7"]["7"] = $qp_7;
            $sal["tabla7"]["8"] = $qp_8;
            $sal["tabla7"]["9"] = $qp_9;
            $sal["tabla7"]["10"] = $qp10;
            $sal["tabla7"]["15"] = $qp15;
            $sal["tabla7"]["20"] = $qp20;
            $sal["tabla7"]["25"] = $qp25;
            $sal["tabla7"]["+25"] = $qp99;
            $sal["tabla7"]["total"] = $TOTALcalls;

            $sal["tabla8"] = array();
            $sal["tabla8"]["Registros"] = array();

            // Posiblemente sea necesario arreglar
            // la query
            $stmt = "select vicidial_closer_log.user,full_name,count(*) AS C,sum(length_in_sec-queue_seconds) AS S,avg(length_in_sec-queue_seconds) AS A  from vicidial_closer_log,vicidial_users where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and and vicidial_closer_log.user is not null and length_in_sec is not null and vicidial_closer_log.user=vicidial_users.user group by vicidial_closer_log.user";
            if ($archived) {
                $stmt = "select vicidial_closer_log_archive.user,full_name,count(*) AS C,sum(length_in_sec-queue_seconds) AS S,avg(length_in_sec-queue_seconds) AS A from vicidial_closer_log_archive,vicidial_users where DATE(call_date) >= DATE('$fechaInicial') and DATE(call_date) <= DATE('$fechaFinal') and  campaign_id IN ($gruposStr) $and and vicidial_closer_log_archive.user is not null and length_in_sec is not null and vicidial_closer_log_archive.user=vicidial_users.user group by vicidial_closer_log_archive.user";
            }

            $rslt = sv_mysqli_query($con, $stmt);
            $users_to_print = sv_mysqli_num_rows($rslt);
            $i = 0;
            $TOTcalls = 0;
            $TOTtime = 0;
            $max_timehms = $max_average = 100000;

            while ($i < $users_to_print) {
                $row = sv_mysqli_fetch_array($rslt);
                $TOTcalls = ($TOTcalls + $row[2]);
                $TOTtime = ($TOTtime + $row[3]);
                $user = $row[0];
                $full_name = $row[1];
                $USERcalls = $row[2];
                $USERtotTALK = $row[3];
                $USERavgTALK = $row[4];
                if ($row[2] > $max_calls) {
                    $max_calls = $row[2];
                }
                if ($row[3] > $max_timehms) {
                    $max_timehms = $row[3];
                }
                if ($row[4] > $max_average) {
                    $max_average = $row[4];
                }
                $USERtotTALK_MS = $USERtotTALK;
                $USERavgTALK_MS = $USERavgTALK;

                $xd = array();
                $xd["usuario"] = $user;
                $xd["nombre"] = $full_name;
                if ($xd["usuario"] == "VDCL") {
                    $xd["usuario"] = "SISTEMA";
                    $xd["nombre"] = "Ningun agente disponible";
                }
                $xd["calls"] = $USERcalls;
                $xd["tiempo"] = $USERtotTALK_MS;
                $xd["promedio"] = $USERavgTALK_MS;
                $sal["tabla8"]["Registros"][] = $xd;
                $i++;
            }
            $TOTagents = $i;
            $TOTavg = $this->MathZDC($TOTtime, $TOTcalls);

            $sal["tabla8"]["Total"]["Agentes"] = $TOTagents;
            $sal["tabla8"]["Total"]["Llamadas"] = $TOTcalls;
            $sal["tabla8"]["Total"]["Tiempo"] = $TOTtime;
            $sal["tabla8"]["Total"]["Promedio"] = $TOTavg;

            $finalRes = array("datos" => $salida, "tabla" => $sal);
            //echo(json_encode($salida));
            sv_mysqli_close($con);
            if (!isset($_GET["csv"])) {
                $finalRes["Estado"] = "ok";
                $this->output->set_output(json_encode($finalRes));
            } else {
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=ReporteEntrante(" . $fechaInicial . "-" . $fechaFinal . ").csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                ob_clean();
                $tiempos = array("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "90", "+90", "Total");
                $out = fopen('php://output', 'w');
                fwrite($out, "{$this->lang->line('header_1')}\n\n");

                fwrite($out, "{$this->lang->line('header_2')}\n");
                fwrite($out, implode(",", $tiempos) . "\n");
                foreach ($tiempos as $value) {

                    fwrite($out, $sal["tabla1"][strtolower($value)]);
                    if (strtolower($value) != "total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }

                }

                fwrite($out, "\n");
                fwrite($out, "{$this->lang->line('header_3')}\n");
                fwrite($out, implode(",", $tiempos) . "\n");
                foreach ($tiempos as $value) {
                    fwrite($out, $sal["tabla2"][strtolower($value)]);
                    if (strtolower($value) != "total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }

                }

                fwrite($out, "\n");
                fwrite($out, "\n");
                fwrite($out, "{$this->lang->line('header_4')}\n");
                fwrite($out, " ," . implode(",", $tiempos) . "\n");

                fwrite($out, "INTERVAL,");
                foreach ($tiempos as $value) {
                    fwrite($out, $sal["tabla3"]["INTERVAL"][$value]);
                    if ($value != "Total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }

                }
                fwrite($out, "INTERVAL %,");
                foreach ($tiempos as $value) {
                    fwrite($out, $sal["tabla3"]["INT"][$value]);
                    if ($value != "Total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }

                }
                fwrite($out, "CUMULATIVE,");
                foreach ($tiempos as $value) {
                    fwrite($out, $sal["tabla3"]["CUMULATIVE"][$value]);
                    if ($value != "Total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }
                }
                fwrite($out, "CUMULATIVE %,");
                foreach ($tiempos as $value) {
                    fwrite($out, $sal["tabla3"]["CUM"][$value]);
                    if ($value != "Total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }
                }
                fwrite($out, "CUM ANS %,");
                foreach ($tiempos as $value) {
                    fwrite($out, $sal["tabla3"]["CUMANS"][$value]);
                    if ($value != "Total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }
                }

                fwrite($out, "\n");
                fwrite($out, "\n");
                fwrite($out, "{$this->lang->line('header_5')}\n");
                fwrite($out, "{$this->lang->line('header_5')},{$this->lang->line('header_6')}\n");
                foreach ($sal["tabla4"]["Registros"] as $valor) {
                    foreach ($valor as $key => $value) {
                        fwrite($out, "$key,$value\n");
                    }
                    fwrite($out, "\n");
                }

                fwrite($out, "Total:," . $sal["tabla4"]["Total"] . "\n");
                fwrite($out, "\n");
                fwrite($out, "\n");

                fwrite($out, "{$this->lang->line('header_7')}\n");
                fwrite($out, "{$this->lang->line('header_8')},{$this->lang->line('header_9')},{$this->lang->line('header_10')},{$this->lang->line('header_6')},{$this->lang->line('header_11')},{$this->lang->line('header_12')}, {$this->lang->line('header_13')}\n");
                foreach ($sal["tabla5"]["Registros"] as $value) {
                    fwrite($out, "{$value['STATUS']},{$value['DESCRIPTION']},{$value['CATEGORY']},{$value['CALLS']},{$value['TOTALTIME']},{$value['AVERAGETIME']},{$value['CALLSHOURS']}\n");
                }
                fwrite($out, "Total:,,,{$sal['tabla5']['Total']['CALLS']},{$sal['tabla5']['Total']['TOTALTIME']},{$sal['tabla5']['Total']['AVGTIME']},{$sal['tabla5']['Total']['CALLSHOURS']},\n");
                fwrite($out, "\n");
                fwrite($out, "\n");
                fwrite($out, "{$this->lang->line('header_14')}\n");
                fwrite($out, "{$this->lang->line('header_10')},{$this->lang->line('header_6')},{$this->lang->line('header_9')}\n");
                foreach ($sal["tabla6"]["Registros"] as $value) {
                    fwrite($out, "{$value['CATEGORY']},{$value['DESCRIPTION']},{$value['CALLS']}\n");
                }
                fwrite($out, "Total:,{$sal['tabla6']['Total']}\n");
                fwrite($out, "\n");
                fwrite($out, "\n");

                $posiciones = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "15", "20", "25", "+25", "total");
                fwrite($out, "{$this->lang->line('header_15')}\n");
                fwrite($out, implode(",", $posiciones) . "\n");
                foreach ($posiciones as $value) {
                    fwrite($out, "{$sal["tabla7"][$value]}");
                    if ($value != "total") {
                        fwrite($out, ",");
                    } else {
                        fwrite($out, "\n");
                    }

                }

                fwrite($out, "\n");
                fwrite($out, "\n");
                fwrite($out, "{$this->lang->line('header_16')}\n");
                fwrite($out, "{$this->lang->line('header_17')},{$this->lang->line('header_18')},{$this->lang->line('header_6')},{$this->lang->line('header_11')},{$this->lang->line('header_12')}\n");
                foreach ($sal["tabla8"]["Registros"] as $value) {
                    fwrite($out, "{$value['usuario']},{$value['nombre']},{$value['calls']},{$value['tiempo']},{$value['promedio']},\n");
                }
                fwrite($out, "Total:, {$sal['tabla8']['Total']['Agentes']},{$sal['tabla8']['Total']['Llamadas']},{$sal['tabla8']['Total']['Tiempo']},{$sal['tabla8']['Total']['Promedio']}\n");
                fclose($out);
            }
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_SinPermisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function index()
    {
        $this->load->view('reporteEntrantes/head');
        $this->load->view('reporteEntrantes/vw_reporte_entrantes');
        $this->load->view('reporteEntrantes/foot');
    }
}
