<?php

require_once "BASEPATH.php";

class ReporteSalientesHora extends MY_Controller
{
    private function addZero($valor)
    {
        if ($valor < 10) {
            return "0$valor";
        }
        return $valor;
    }
    private function convertSecToTime($segundos)
    {
        $horas = intdiv($segundos, 3600);
        $horas = $this->addZero($horas);
        $segundos %= 3600;
        $minutos = intdiv($segundos, 60);
        $minutos = $this->addZero($minutos);
        $segundos %= 60;
        $segundos = $this->addZero($segundos);
        return "$horas:$minutos:$segundos";
    }
    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('reportesalienteshora', "spanish");
                break;
            case "en":
                $this->lang->load('reportesalienteshora', "english");
                break;
            default:
                $this->lang->load('reportesalienteshora', "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"]);
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }
            $campana = limpia($_GET["campana"]);
            $con = getConnection();
            $usuario = $_SESSION["Usuario"];

            $sales = array();
            $dncs = array();
            $systemStatus = array("NA", "NEW", "QUEUE", "INCALL", "DROP", "XDROP", "AA", "AM", "AL", "AFAX", "AB", "ADC", "DNCL", "DNCC", "PU", "PM", "SVYEXT", "SVYHU", "SVYVM", "SVYREC", "QVMAIL");

            $query = "SELECT status FROM vicidial_campaign_statuses WHERE sale='Y' AND campaign_id='$campana' UNION SELECT status FROM vicidial_statuses WHERE sale='Y'";
            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $sales[] = $row[0];
            }

            $query = "SELECT status FROM vicidial_campaign_statuses WHERE dnc='Y' AND campaign_id='$campana' UNION SELECT status FROM vicidial_statuses WHERE dnc='Y'";
            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $dncs[] = $row[0];
            }

            $agent_pause = 0;
            $agent_total = 0;

            $agent_pauseH = array();
            $agent_totalH = array();

            $totalCalls = 0;
            $systemCalls = 0;

            $systemCalls = 0;

            $totalCallsH = array();
            $systemCallsH = array();

            $notAnswered = 0;
            $notAnsweredH = array();

            $saleCalls = 0;
            $saleCallsH = array();

            $dncCalls = 0;
            $dncCallsH = array();

            $dncCalls = 0;
            $dncCallsH = array();

            $dropCalls = 0;
            $dropCallsH = array();

            for ($i = 0; $i < 24; $i++) {
                $agent_pauseH[$i] = 0;
                $agent_totalH[$i] = 0;
                $systemCallsH[$i] = 0;
                $totalCallsH[$i] = 0;
                $notAnsweredH[$i] = 0;
                $saleCallsH[$i] = 0;
                $dncCallsH[$i] = 0;
                $dropCallsH[$i] = 0;
            }

            $query = "SELECT HOUR(event_time) AS hora,pause_sec,wait_sec,talk_sec,dispo_sec from vicidial_agent_log where event_time >= '$fechaInicio 00:00:00' and event_time <= '$fechaFin 23:59:59' and campaign_id ='$campana'";
            if ($archived) {
                $query = "SELECT HOUR(event_time) AS hora,pause_sec,wait_sec,talk_sec,dispo_sec from vicidial_agent_log_archive where event_time >= '$fechaInicio 00:00:00' and event_time <= '$fechaFin 23:59:59' and campaign_id ='$campana'";
            }

            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $agent_total += $row[1] + $row[2] + $row[3] + $row[4];
                $agent_pause += $row[1];
                $agent_pauseH[$row[0]] += $row[1];
                $agent_totalH[$row[0]] += $row[1] + $row[2] + $row[3] + $row[4];
            }

            $query = "SELECT status,HOUR(call_date) from vicidial_log where call_date >= '$fechaInicio 00:00:00' and call_date <= '$fechaFin 23:59:59' and campaign_id='$campana'";
            if ($archived) {
                $query = "SELECT status,HOUR(call_date) from vicidial_log_archive where call_date >= '$fechaInicio 00:00:00' and call_date <= '$fechaFin 23:59:59' and campaign_id='$campana'";
            }

            $result = sv_mysqli_query($con, $query);
            while ($row = sv_mysqli_fetch_array($result)) {
                $status = $row[0];
                $hour = $row[1];
                $totalCalls++;
                $totalCallsH[$hour]++;
                if (in_array($status, $systemStatus)) {
                    $systemCalls++;
                    $systemCallsH[$hour]++;
                }
                if (in_array($status, $sales)) {
                    $saleCalls++;
                    $saleCallsH[$hour]++;
                }
                if (in_array($status, $dncs)) {
                    $dncCalls++;
                    $dncCallsH[$hour]++;
                }

                if (strtoupper($status) == 'NA') {
                    $notAnswered++;
                    $notAnsweredH[$hour]++;
                }

                if (strtoupper($status) == 'DROP') {
                    $dropCalls++;
                    $dropCallsH[$hour]++;
                }
            }

            $sal = array();
            $notAnsweredPer = $totalCalls == 0 ? 0 : round(($notAnswered / $totalCalls) * 100, 2);
            $dropPer = $totalCalls == 0 ? 0 : round(($dropCalls / $totalCalls) * 100, 2);
            $sal["General"] = array(
                "Totales" => $totalCalls,
                "TotalSistema" => $systemCalls,
                "TotalAgentCalls" => ($totalCalls - $systemCalls),
                "LlamadasVenta" => $saleCalls,
                "LlamadaDNC" => $dncCalls,
                "NoContestadasPorcentaje" => $notAnsweredPer,
                "DropPorcentaje" => $dropPer,
                "TotalTiempo" => $this->convertSecToTime($agent_total),
                "TotalTiempoPause" => $this->convertSecToTime($agent_pause),
            );

            $sal["Desglose"] = array();
            for ($i = 0; $i < 24; $i++) {
                $notAnsweredPer = $totalCallsH[$i] == 0 ? 0 : round(($notAnsweredH[$i] / $totalCallsH[$i]) * 100, 2);
                $dropPer = $totalCallsH[$i] == 0 ? 0 : round(($dropCallsH[$i] / $totalCallsH[$i]) * 100, 2);

                $fila = array(
                    "Totales" => $totalCallsH[$i],
                    "TotalSistema" => $systemCallsH[$i],
                    "TotalAgentCalls" => ($totalCallsH[$i] - $systemCallsH[$i]),
                    "LlamadasVenta" => $saleCallsH[$i],
                    "LlamadaDNC" => $dncCallsH[$i],
                    "NoContestadasPorcentaje" => $notAnsweredH[$i],
                    "DropPorcentaje" => $dropCallsH[$i],
                    "TotalTiempo" => $this->convertSecToTime($agent_totalH[$i]),
                    "TotalTiempoPause" => $this->convertSecToTime($agent_pauseH[$i]),
                );
                $sal["Desglose"][$i] = $fila;
            }
            $sal["Estado"] = "ok";
            if (isset($_GET["csv"]) && $_GET["csv"] == 1) {
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=ReporteSalientePorHora.csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');
                fwrite($out, "{$this->lang->line("header_2")},{$this->lang->line("header_3")},{$this->lang->line("header_4")},{$this->lang->line("header_5")},{$this->lang->line("header_6")},{$this->lang->line("header_7")},{$this->lang->line("header_8")},{$this->lang->line("header_9")},{$this->lang->line("header_10")},{$this->lang->line("header_11")}\n");
                for ($i = 0; $i < 24; $i++) {
                    $fila = $sal["Desglose"][$i];
                    fwrite($out, "{$this->lang->line("header_1")} " . $this->addZero($i) . ":," . $fila["Totales"] . "," . $fila["TotalSistema"] . "," . $fila["TotalAgentCalls"] . "," . $fila["LlamadasVenta"] . "," . $fila["LlamadaDNC"] . "," . $fila["NoContestadasPorcentaje"] . "," . $fila["DropPorcentaje"] . "," . $fila["TotalTiempo"] . "," . $fila["TotalTiempoPause"] . "\n");
                }
                $fila = $sal["General"];
                fwrite($out, "Total:," . $fila["Totales"] . "," . $fila["TotalSistema"] . "," . $fila["TotalAgentCalls"] . "," . $fila["LlamadasVenta"] . "," . $fila["LlamadaDNC"] . "," . $fila["NoContestadasPorcentaje"] . "," . $fila["DropPorcentaje"] . "," . $fila["TotalTiempo"] . "," . $fila["TotalTiempoPause"]);
                fclose($out);
            } else {
                $this->output->set_output(json_encode($sal));
            }

        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosSalientesHora");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function index()
    {
        $this->load->view('reporteSalientesHora/head');
        $this->load->view('reporteSalientesHora/vw_reporte_hora');
        $this->load->view('reporteSalientesHora/foot');
    }
}
