<?php

require_once "BASEPATH.php";

class ReporteHora 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 summaryHourly()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportehora', "spanish");
                break;
            case "en":
                $this->lang->load('reportehora', "english");
                break;
            default:
                $this->lang->load('reportehora', "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';
            $fechaInicio = limpia($_GET["fechaInicio"]);
            $fechaFin = limpia($_GET["fechaFin"]);
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];
            $sal = $group_name = $agent_alert_delay = $length_in_sec = $queue_seconds = $talk_sec = $calls_count = $drop_count = $answer_count = $max_queue_seconds = array();
            $i = 0;
            $MT = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $and = "";
            $and1 = "";
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }

            if ($_SESSION["Cliente"] != -1) {
                if (isset($_GET["grupos"]) && is_array($_GET["grupos"]) && !empty($_GET["grupos"])) {
                    $gruposStr = "";
                    foreach ($_GET["grupos"] as $grupo) {
                        $gruposStr .= "'$grupo',";
                    }
                    $gruposStr = substr($gruposStr, 0, -1);
                    $and = "AND campaign_id IN ($gruposStr)";
                    $and1 = "WHERE group_id IN ($gruposStr)";
                } else {
                    $and = "AND campaign_id IN (SELECT group_id FROM vicidial_inbound_groups WHERE user_group LIKE '%" . $_SESSION["Cliente"] . "%')";
                    $and1 = "WHERE user_group LIKE '%" . $_SESSION["Cliente"] . "%'";
                }

            }
            $query = "select group_name,agent_alert_delay,group_id from vicidial_inbound_groups $and1";
            $result = sv_mysqli_query($con, $query);
            $TOTcalls_count = 0;
            $print_calls = 0;
            $TOTcalls_count = 0;
            $TOTanswer_count = 0;
            $TOTtalk_sec = 0;
            $TOTqueue_seconds = 0;
            $TOTdrop_count = 0;
            $TOTmax_queue_seconds = 0;
            $max_calls = 0;
            $max_answer = 0;
            $max_avgqueue = 0;
            $max_avgtalk = 0;
            $max_talk = 0;
            $max_queue = 0;
            $max_totalabandons = 0;
            $max_maxqueue = 0;
            $otroProm = 0;
            $otroProm2 = 0;
            $sal["Totales"] = array();
            $sal["Totales"]["tiempoCharla"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $sal["Totales"]["totalContestadas"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $sal["Totales"]["totalLlamadas"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $sal["Totales"]["promedioLlamada"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $sal["Totales"]["tiempoCola"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $sal["Totales"]["promedioCola"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $sal["Totales"]["maximoCola"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            $sal["Totales"]["totalAbandonados"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

            while ($row = sv_mysqli_fetch_array($result)) {
                $group_name[$i] = $row[0];
                $agent_alert_delay[$i] = round($row[1] / 1000);
                $out_of_call_time = 0;
                $length_in_sec[$i] = 0;
                $queue_seconds[$i] = 0;
                $talk_sec[$i] = 0;
                $calls_count[$i] = 0;
                $drop_count[$i] = 0;
                $answer_count[$i] = 0;
                $max_queue_seconds[$i] = 0;
                $Hlength_in_sec = $MT;
                $Hqueue_seconds = $MT;
                $Hcalltime = $MT;
                $Htalk_sec = $MT;
                $Hcalls_count = $MT;
                $Hdrop_count = $MT;
                $Hanswer_count = $MT;
                $Hmax_queue_seconds = $MT;
                $hTOTALcalls = 0;
                $hANSWERcalls = 0;
                $hSUMtalk = 0;
                $hAVGtalk = 0;
                $hSUMqueue = 0;
                $hAVGqueue = 0;
                $hMAXqueue = 0;
                $hDROPcalls = 0;
                $hPRINT = 0;
                $hTOTcalls_count = 0;
                $hTOTanswer_count = 0;
                $hTOTtalk_sec = 0;
                $hTOTtalk_avg = 0;
                $hTOTqueue_seconds = 0;
                $hTOTqueue_avg = 0;
                $hTOTmax_queue_seconds = 0;
                $hTOTdrop_count = 0;
                $otroProm = 0;
                $otroProm2 = 0;
                $Gct_default_start = 0;
                $Gct_default_stop = 0;
                $query = "SELECT status,length_in_sec,queue_seconds,call_date,UNIX_TIMESTAMP(call_date),phone_number,campaign_id,HOUR(TIME(call_date)) from vicidial_closer_log where DATE(call_date) >= DATE('$fechaInicio') and DATE(call_date) <= DATE('$fechaFin') and campaign_id='$row[2]' $and";
                if ($archived) {
                    $query = "SELECT status,length_in_sec,queue_seconds,call_date,UNIX_TIMESTAMP(call_date),phone_number,campaign_id,HOUR(TIME(call_date)) from vicidial_closer_log_archive where DATE(call_date) >= DATE('$fechaInicio') and DATE(call_date) <= DATE('$fechaFin') and campaign_id='$row[2]' $and";
                }
                $result2 = sv_mysqli_query($con, $query);
                $calls_to_parse = sv_mysqli_num_rows($result2);
                $p = 0;

                $sal["Grupos"][$i]["grupo"] = $row[0];
                $sal["Grupos"][$i]["tiempoCharla"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                $sal["Grupos"][$i]["totalContestadas"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                $sal["Grupos"][$i]["totalLlamadas"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                $sal["Grupos"][$i]["promedioLlamada"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                $sal["Grupos"][$i]["tiempoCola"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                $sal["Grupos"][$i]["promedioCola"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                $sal["Grupos"][$i]["maximoCola"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                $sal["Grupos"][$i]["totalAbandonados"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

                while ($p < $calls_to_parse) {
                    $row2 = sv_mysqli_fetch_array($result2);
                    $call_date = explode(" ", $row2[3]);
                    $call_time = preg_replace('/[^0-9]/', '', $call_date[1]);
                    $epoch = $row2[4];
                    $Chour = 0;
                    $calls_count[$i]++;
                    $length_in_sec[$i] = ($length_in_sec[$i] + $row2[1]);

                    $TEMPtalk = (($row2[1] - $row2[2]) - $agent_alert_delay[$i]);
                    if ($TEMPtalk < 0) {
                        $TEMPtalk = 0;
                    }

                    $sal["Grupos"][$i]["tiempoCharla"][$row2[7]] += $TEMPtalk;
                    $sal["Totales"]["tiempoCharla"][$row2[7]] += $TEMPtalk;
                    $queue_seconds[$i] = ($queue_seconds[$i] + $row2[2]);
                    $sal["Grupos"][$i]["tiempoCola"][$row2[7]] += $row2[2];
                    $sal["Grupos"][$i]["maximoCola"][$row2[7]] = max($sal["Grupos"][$i]["maximoCola"][$row2[7]], $row2[2]);
                    $sal["Totales"]["tiempoCola"][$row2[7]] += $row2[2];
                    $sal["Totales"]["maximoCola"][$row2[7]] = max($sal["Totales"]["maximoCola"][$row2[7]], $row2[2]);

                    $talk_sec[$i] = ($talk_sec[$i] + $TEMPtalk);

                    if ($max_queue_seconds[$i] < $row2[2]) {
                        $max_queue_seconds[$i] = $row2[2];
                    }

                    if (preg_match("/DROP/i", $row2[0])) {
                        $drop_count[$i]++;
                        $sal["Grupos"][$i]["totalAbandonados"][$row2[7]]++;
                        $sal["Totales"]["totalAbandonados"][$row2[7]]++;
                    } else {
                        $answer_count[$i]++;
                        $sal["Grupos"][$i]["totalContestadas"][$row2[7]]++;
                        $sal["Totales"]["totalContestadas"][$row2[7]]++;
                    }
                    $Hcalls_count[$Chour]++;
                    $Hlength_in_sec[$Chour] = ($Hlength_in_sec[$Chour] + $row2[1]);
                    $Hqueue_seconds[$Chour] = ($Hqueue_seconds[$Chour] + $row2[2]);
                    $Htalk_sec[$Chour] = ($Htalk_sec[$Chour] + $TEMPtalk);
                    if ($Hmax_queue_seconds[$Chour] < $row2[2]) {
                        $Hmax_queue_seconds[$Chour] = $row2[2];
                    }

                    if (preg_match("/DROP/i", $row[0])) {
                        $Hdrop_count[$Chour]++;
                    } else {
                        $Hanswer_count[$Chour]++;
                    }

                    $Hcalltime[$Chour]++;
                    if ($print_calls > 0) {
                        $ASCII_text .= "$row2[5]\t$row2[6]\t$TEMPtalk\n";
                        $PCtemptalk = ($PCtemptalk + $TEMPtalk);
                    }
                    $p++;
                    $sal["Grupos"][$i]["totalLlamadas"][$row2[7]]++;
                    $sal["Totales"]["totalLlamadas"][$row2[7]]++;
                }
                if (($answer_count[$i] > 0) and ($talk_sec[$i] > 0)) {
                    $talk_avg[$i] = ($talk_sec[$i] / $answer_count[$i]);
                } else {
                    $talk_avg[$i] = 0;
                }

                if (($calls_count[$i] > 0) and ($queue_seconds[$i] > 0)) {
                    $queue_avg[$i] = ($queue_seconds[$i] / $calls_count[$i]);
                } else {
                    $queue_avg[$i] = 0;
                }

                for ($hori = 0; $hori < 24; $hori++) {
                    if ($sal["Grupos"][$i]["totalLlamadas"][$hori] != 0) {
                        $sal["Grupos"][$i]["promedioCola"][$hori] = $sal["Grupos"][$i]["tiempoCola"][$hori] / $sal["Grupos"][$i]["totalLlamadas"][$hori];
                    }

                    if ($sal["Grupos"][$i]["totalContestadas"][$hori] != 0) {
                        $sal["Grupos"][$i]["promedioLlamada"][$hori] = $sal["Grupos"][$i]["tiempoCharla"][$hori] / $sal["Grupos"][$i]["totalContestadas"][$hori];
                    }
                    if ($sal["Totales"]["totalLlamadas"][$hori] != 0) {
                        $sal["Totales"]["promedioCola"][$hori] = $sal["Totales"]["tiempoCola"][$hori] / $sal["Totales"]["totalLlamadas"][$hori];
                    }

                    if ($sal["Totales"]["totalContestadas"][$hori] != 0) {
                        $sal["Totales"]["promedioLlamada"][$hori] = $sal["Totales"]["tiempoCharla"][$hori] / $sal["Totales"]["totalContestadas"][$hori];
                    }

                }
                if ($print_calls > 0) {
                    $PCtemptalkmin = ($PCtemptalk / 60);
                }
                $TOTcalls_count = ($TOTcalls_count + $calls_count[$i]);
                $TOTanswer_count = ($TOTanswer_count + $answer_count[$i]);
                $TOTtalk_sec = ($TOTtalk_sec + $talk_sec[$i]);
                $TOTqueue_seconds = ($TOTqueue_seconds + $queue_seconds[$i]);
                $TOTdrop_count = ($TOTdrop_count + $drop_count[$i]);
                if ($max_queue_seconds[$i] > $TOTmax_queue_seconds) {
                    $TOTmax_queue_seconds = $max_queue_seconds[$i];
                }

                if ($calls_count[$i] > $max_calls) {
                    $max_calls = $calls_count[$i];
                }

                if ($answer_count[$i] > $max_answer) {
                    $max_answer = $answer_count[$i];
                }

                if ($talk_sec[$i] > $max_talk) {
                    $max_talk = $talk_sec[$i];
                }

                if ($talk_avg[$i] > $max_avgtalk) {
                    $max_avgtalk = $talk_avg[$i];
                }

                if ($queue_seconds[$i] > $max_queue) {
                    $max_queue = $queue_seconds[$i];
                }

                if ($queue_avg[$i] > $max_avgqueue) {
                    $max_avgqueue = $queue_avg[$i];
                }

                if ($max_queue_seconds[$i] > $max_maxqueue) {
                    $max_maxqueue = $max_queue_seconds[$i];
                }

                if ($drop_count[$i] > $max_totalabandons) {
                    $max_totalabandons = $drop_count[$i];
                }

                $talk_sec[$i] = $talk_sec[$i];
                $talk_avg[$i] = $talk_avg[$i];
                $queue_seconds[$i] = $queue_seconds[$i];
                $queue_avg[$i] = $queue_avg[$i];
                if (!array_key_exists($i, $max_queue_seconds)) {
                    $max_queue_seconds[$i] = 0;
                }

                $max_queue_seconds[$i] = $max_queue_seconds[$i];
                $gTOTALcalls = sprintf("%6s", $calls_count[$i]);
                $gANSWERcalls = sprintf("%6s", $answer_count[$i]);
                $gSUMtalk = sprintf("%9s", $talk_sec[$i]);
                $gAVGtalk = sprintf("%7s", $talk_avg[$i]);
                $otroProm = $otroProm + $gAVGtalk;
                $gSUMqueue = sprintf("%9s", $queue_seconds[$i]);
                $gAVGqueue = sprintf("%7s", $queue_avg[$i]);
                $gMAXqueue = sprintf("%7s", $max_queue_seconds[$i]);
                $otroProm2 = $otroProm2 + $gMAXqueue;
                $gDROPcalls = sprintf("%6s", $drop_count[$i]);
                $sal["general"][$i]["grupo"] = $row[0];
                $sal["general"][$i]["totalLlamadas"] = $gTOTALcalls;
                $sal["general"][$i]["totalContestadas"] = $gANSWERcalls;
                $sal["general"][$i]["totalLlamada"] = $gSUMtalk;
                $sal["general"][$i]["promedioLlamada"] = $gAVGtalk;
                $sal["general"][$i]["totalCola"] = $gSUMqueue;
                $sal["general"][$i]["promedioCola"] = $gAVGqueue;
                $sal["general"][$i]["maximoCola"] = $gMAXqueue;
                $sal["general"][$i]["totalAbandono"] = $gDROPcalls;
                // No estoy seguro que esto va aqui - BEGIN
                // $sal["Totales"]["totalLlamadas"] = $gTOTALcalls;
                // $sal["Totales"]["totalContestadas"] = $gANSWERcalls;
                // $sal["Totales"]["totalLlamada"] = $gSUMtalk;
                // $sal["Totales"]["promedioLlamada"] = $gAVGtalk;
                // $sal["Totales"]["totalCola"] = $gSUMqueue;
                // $sal["Totales"]["promedioCola"] = $gAVGqueue;
                // $sal["Totales"]["maximoCola"] = $gMAXqueue;
                // $sal["Totales"]["totalAbandono"] = $gDROPcalls;
                // No estoy seguro que esto va aqui - END

                $i++;
            }
            for ($hori = 0; $hori < 24; $hori++) {
                if ($sal["Totales"]["totalLlamadas"][$hori] != 0) {
                    $sal["Totales"]["promedioCola"][$hori] = $sal["Totales"]["tiempoCola"][$hori] / $sal["Totales"]["totalLlamadas"][$hori];
                }

                if ($sal["Totales"]["totalContestadas"][$hori] != 0) {
                    $sal["Totales"]["promedioLlamada"][$hori] = $sal["Totales"]["tiempoCharla"][$hori] / $sal["Totales"]["totalContestadas"][$hori];
                }

            }

            $sal["total"]["totalLlamadas"] = $TOTcalls_count;
            $sal["total"]["totalContestadas"] = $TOTanswer_count;
            $sal["total"]["totalLlamada"] = $TOTtalk_sec;
            $sal["total"]["totalCola"] = $TOTqueue_seconds;
            $sal["total"]["maximoCola"] = $TOTmax_queue_seconds;
            $sal["total"]["totalAbandono"] = $TOTdrop_count;
            $sal["total"]["promedioTiempoLlamada"] = $otroProm;
            $sal["total"]["promedioTiempoColaEspera"] = $otroProm2;
            sv_mysqli_close($con);
            if (!isset($_GET["csv"])) {
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                $sal["general"][count($sal["general"])] = array();
                $sal["general"][count($sal["general"]) - 1]["grupo"] = "Total:";
                $sal["general"][count($sal["general"]) - 1]["totalLlamadas"] = $TOTcalls_count;
                $sal["general"][count($sal["general"]) - 1]["totalContestadas"] = $TOTanswer_count;
                $sal["general"][count($sal["general"]) - 1]["totalLlamada"] = $TOTtalk_sec;
                $sal["general"][count($sal["general"]) - 1]["promedioLlamada"] = $otroProm;
                $sal["general"][count($sal["general"]) - 1]["totalCola"] = $TOTqueue_seconds;
                $sal["general"][count($sal["general"]) - 1]["promedioCola"] = $otroProm2;
                $sal["general"][count($sal["general"]) - 1]["maximoCola"] = $TOTmax_queue_seconds;
                $sal["general"][count($sal["general"]) - 1]["totalAbandono"] = $TOTdrop_count;
                for ($i = 0; $i < count($sal["general"]); $i++) {

                    $sal["general"][$i][$this->lang->line("header_1")] = $sal["general"][$i]["grupo"];
                    unset($sal["general"][$i]["grupo"]);

                    $sal["general"][$i][$this->lang->line("header_2")] = $sal["general"][$i]["totalLlamadas"];
                    unset($sal["general"][$i]["totalLlamadas"]);

                    $sal["general"][$i][$this->lang->line("header_3")] = $sal["general"][$i]["totalContestadas"];
                    unset($sal["general"][$i]["totalContestadas"]);

                    $sal["general"][$i][$this->lang->line("header_4")] = $sal["general"][$i]["totalLlamada"];
                    unset($sal["general"][$i]["totalLlamada"]);

                    $sal["general"][$i][$this->lang->line("header_5")] = $sal["general"][$i]["promedioLlamada"];
                    unset($sal["general"][$i]["promedioLlamada"]);

                    $sal["general"][$i][$this->lang->line("header_6")] = $sal["general"][$i]["totalCola"];
                    unset($sal["general"][$i]["totalCola"]);

                    $sal["general"][$i][$this->lang->line("header_7")] = $sal["general"][$i]["promedioCola"];
                    unset($sal["general"][$i]["promedioCola"]);

                    $sal["general"][$i][$this->lang->line("header_8")] = $sal["general"][$i]["maximoCola"];
                    unset($sal["general"][$i]["maximoCola"]);

                    $sal["general"][$i][$this->lang->line("header_9")] = $sal["general"][$i]["totalAbandono"];
                    unset($sal["general"][$i]["totalAbandono"]);
                }
                ob_clean();
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=ReportePorHora(" . $fechaInicio . "-" . $fechaFin . ").csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');
                $test = array();
                $this->trata($out, $sal["general"], $test);
                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('reporteHora/head');
        $this->load->view('reporteHora/vw_reporte_hora');
        $this->load->view('reporteHora/foot');
    }
}
