<?php

require_once "BASEPATH.php";

class ReportePausaCampa 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 pauseReport()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportepausacampa', "spanish");
                break;
            case "en":
                $this->lang->load('reportepausacampa', "english");
                break;
            default:
                $this->lang->load('reportepausacampa', "spanish");
                break;
        }

        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $fechaInicio = limpia($_GET["fechaInicial"]);
            $fechaFin = limpia($_GET["fechaFinal"]);
            $and = "";
            $campana = limpia($_GET["campana"]);
            $andCampana = "";
            $tipoOrdenamiento = "";
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }

            if ($campana != -1) {
                $andCampana = "AND campaign_id = '$campana'";
            }
            if ($_SESSION["Cliente"] != -1) {
                $and = "AND user IN (SELECT user FROM vicidial_users WHERE user_group LIKE '" . $_SESSION["Cliente"] . "%' )";
            }
            $sal = array("Registros" => array());

            if ($_SESSION["Cliente"] != -1) {

                $usuariosXD = "";
                $query = "SELECT user FROM vicidial_users WHERE user_group LIKE '" . $_SESSION["Cliente"] . "_%'";
                $result = sv_mysqli_query($con, $query);
                while ($row = sv_mysqli_fetch_array($result)) {

                    $sal["Registros"][$row["user"]] = array("status" => array());
                    $usuariosXD = $usuariosXD . "'" . $row["user"] . "',";
                }
                if ($usuariosXD != "") {
                    $usuariosXD = substr($usuariosXD, 0, -1);
                    $and3 = "AND T.user IN ($usuariosXD)";
                } else {
                    $and3 = "AND 1 = 2";
                }
            }

            $query = "SELECT distinct if(sub_status is null, '*', sub_status) as all_subs from vicidial_agent_log as T where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' and pause_sec >= 0 and pause_sec < 65000 $and3 $andCampana $and order by all_subs asc";
            if ($archived) {
                $query = "SELECT distinct if(sub_status is null, '*', sub_status) as all_subs from vicidial_agent_log_archive as T where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' and pause_sec >= 0 and pause_sec < 65000 $and3 $andCampana $and order by all_subs asc";
            }
            $sal["Resultados"] = array();
            $result = sv_mysqli_query($con, $query);

            $donde = 0;
            $statuses = array();
            while ($row = sv_mysqli_fetch_array($result)) {

                $query2 = "SELECT full_name,T.user,SEC_TO_TIME(sum(pause_sec)) AS tiempo,sub_status,SEC_TO_TIME(sum(wait_sec + talk_sec + dispo_sec)) AS total, T.user_group from vicidial_users as T,vicidial_agent_log as U where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' and sub_status='" . $row["all_subs"] . "' and T.user=U.user and pause_sec<65000  $andCampana $and3 group by T.user,full_name,sub_status order by T.user,full_name,sub_status desc";
                if ($row["all_subs"] == "*") {
                    $query2 = "SELECT full_name,T.user,SEC_TO_TIME(sum(pause_sec)) AS tiempo,sub_status,SEC_TO_TIME(sum(wait_sec + talk_sec + dispo_sec)) AS total, T.user_group from vicidial_users as T,vicidial_agent_log as U where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' and sub_status IS NULL and T.user=U.user and pause_sec<65000  $andCampana $and3 group by T.user,full_name,sub_status order by U.user,full_name,sub_status desc";
                }

                if ($archived) {
                    $query2 = "SELECT full_name,T.user,SEC_TO_TIME(sum(pause_sec)) AS tiempo,sub_status,SEC_TO_TIME(sum(wait_sec + talk_sec + dispo_sec)) AS total, T.user_group from vicidial_users as T,vicidial_agent_log_archive as U where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' and sub_status='" . $row["all_subs"] . "' and T.user=U.user and pause_sec<65000  $andCampana $and3    group by T.user,full_name,sub_status order by T.user,full_name,sub_status desc";
                    if ($row["all_subs"] == "*") {
                        $query2 = "SELECT full_name,T.user,SEC_TO_TIME(sum(pause_sec)) AS tiempo,sub_status,SEC_TO_TIME(sum(wait_sec + talk_sec + dispo_sec)) AS total, T.user_group from vicidial_users as T,vicidial_agent_log_archive as U where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' and sub_status IS NULL and T.user=U.user and pause_sec<65000  $andCampana $and3    group by T.user,full_name,sub_status order by T.user,full_name,sub_status desc";
                    }

                }
                $result2 = sv_mysqli_query($con, $query2);
                while ($row2 = sv_mysqli_fetch_array($result2)) {
                    $real_sub_status = $row2["sub_status"] ? $row2["sub_status"] : $this->lang->line("headerReporte"); //Pause status not selected
                    if (!in_array($real_sub_status, $statuses)) {
                        $statuses[] = $real_sub_status;

                    }
                    $sal["Registros"][$row2["user"]]["full_name"] = $row2["full_name"];
                    $sal["Registros"][$row2["user"]]["status"][$real_sub_status] = array();
                    $sal["Registros"][$row2["user"]]["status"][$real_sub_status]["tiempoPausa"] = $row2["tiempo"];
                    $sal["Registros"][$row2["user"]]["status"][$real_sub_status]["tiempoTotal"] = $row2["total"];
                }

            }

            sv_mysqli_close($con);
            if (!isset($_GET["csv"])) {
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                ob_clean();
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=ReportePausaPorCampania(" . $fechaInicio . "-" . $fechaFin . ").csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');
                fputcsv($out, array_merge(array($this->lang->line("header_1"), $this->lang->line("header_2")), $statuses));
                foreach ($sal["Registros"] as $usuario => &$valores) {
                    $tiempos = array();
                    foreach ($statuses as $status) {
                        if (array_key_exists($status, $valores["status"])) {
                            $tiempos[] = $valores["status"][$status]["tiempoPausa"];
                        } else {
                            $tiempos[] = $this->convertSecToTime(0);

                        }
                    }
                    fputcsv($out, array_merge(array($usuario, (array_key_exists("full_name", $valores) ? $valores["full_name"] : "")), $tiempos));

                }
                fclose($out);

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