<?php

require_once "BASEPATH.php";

class ReporteHorarioAgente extends MY_Controller
{
    public function trata(&$out, $arreglo, &$lastLinePrinted)
    {
        $llaves = array_keys($arreglo);
        $llavesNoArreglos = array();
        $temp = array();
        for ($i = 0; $i < count($llaves); $i++) {
            if (!is_array($arreglo[$llaves[$i]])) {
                $llavesNoArreglos[] = $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);
            }
        }
    }
    private function ponZero($Cant)
    {
        return $Cant < 10 ? "0$Cant" : $Cant;
    }
    private function convertTime($tiempoSeg)
    {
        $Horas = intval($tiempoSeg / 3600);
        $tiempoSeg -= $Horas * 3600;
        $Minutos = intval($tiempoSeg / 60);
        $tiempoSeg -= $Minutos * 60;
        return $this->ponZero($Horas) . ":" . $this->ponZero($Minutos) . ":" . $this->ponZero($tiempoSeg);
    }
    public function agentTimeSheet()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportehorarioagente', "spanish");
                break;
            case "en":
                $this->lang->load('reportehorarioagente', "english");
                break;
            default:
                $this->lang->load('reportehorarioagente', "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"]);
            $agente = limpia($_GET["agente"]);
            $and = "";
            $campana = limpia($_GET["campana"]);
            $andCampana = "";
            $and2 = "";
            $and3 = "";
            $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"]."%' AND user = '$agente')";
            }*/
            if ($_SESSION["Cliente"] != -1) {
                $campanasXD = "";
                $query = "SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '" . $_SESSION["Cliente"] . "'";
                $result = sv_mysqli_query($con, $query);
                while ($row = sv_mysqli_fetch_array($result)) {
                    $campanasXD = $campanasXD . "'" . $row["campaign_id"] . "',";
                }
                if ($campanasXD != "") {
                    $campanasXD = substr($campanasXD, 0, -1);
                    $and2 = "AND campaign_id IN ($campanasXD)";
                } else {
                    $and2 = "AND 1 = 2";
                }
                $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)) {
                    $usuariosXD = $usuariosXD . "'" . $row["user"] . "',";
                }
                if ($usuariosXD != "") {
                    $usuariosXD = substr($usuariosXD, 0, -1);
                    $and3 = "AND user IN ($usuariosXD)";
                } else {
                    $and3 = "AND 1 = 2";
                }
            }
            $andAgente = "";
            $grupo = "";
            $sal = array();
            if ($agente != -1) {
                $andAgente = "AND user = '$agente'";
            } else {
                $grupo = "GROUP BY user";
            }
            $campoOrdenamiento = "nombre";
            $tipoOrdnamiento = "DESC";
            if (!empty($_GET["campoOrdenamiento"])) {
                $campoOrdenamiento = limpia($_GET["campoOrdenamiento"]);
            }
            if (!empty($_GET["tipoOrdenamiento"])) {
                $tipoOrdenamiento = limpia($_GET["tipoOrdenamiento"]);
            }

            if ($tipoOrdenamiento != "DESC") {
                $tipoOrdenamiento = "ASC";
            }

            $campoOrdenamieno = str_replace(" ", "", $campoOrdenamiento);
            $query = "select SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )) as calls,sum(IF(talk_sec<65000,talk_sec,0)) as talk,sum(IF(talk_sec<65000,talk_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),sum(IF(pause_sec<65000,pause_sec,0)) as tiempoPausa,sum(IF(pause_sec<65000,pause_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),sum(IF(wait_sec<65000,wait_sec,0)) as tiempoEspera,sum(IF(wait_sec<65000,wait_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),sum(IF(dispo_sec<65000,dispo_sec,0)) as tiempoWrapup,sum(talk_sec)+sum(pause_sec)+sum(wait_sec)+sum(dispo_sec)  as tiempoTotalEnActivo,sum(IF(dispo_sec<65000,dispo_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),user,(SELECT full_name FROM vicidial_users WHERE user=vicidial_agent_log.user) AS nombre FROM vicidial_agent_log where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' $andAgente $and3 $and $and2 $andCampana  $grupo ORDER BY $campoOrdenamiento $tipoOrdenamiento";
            if ($archived) {
                $query = "select SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )) as calls,sum(IF(talk_sec<65000,talk_sec,0)) as talk,sum(IF(talk_sec<65000,talk_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),sum(IF(pause_sec<65000,pause_sec,0)) as tiempoPausa,sum(IF(pause_sec<65000,pause_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),sum(IF(wait_sec<65000,wait_sec,0)) as tiempoEspera,sum(IF(wait_sec<65000,wait_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),sum(IF(dispo_sec<65000,dispo_sec,0)) as tiempoWrapup,sum(talk_sec)+sum(pause_sec)+sum(wait_sec)+sum(dispo_sec)  as tiempoTotalEnActivo,sum(IF(dispo_sec<65000,dispo_sec,0))/SUM(IF(lead_id > 0 AND status IS NOT NULL AND LENGTH(status) > 0, 1, 0 )),user,(SELECT full_name FROM vicidial_users WHERE user=vicidial_agent_log_archive.user) AS nombre FROM vicidial_agent_log_archive where event_time <= '$fechaFin 23:59:59' and event_time >= '$fechaInicio 00:00:00' $andAgente $and3 $and $and2 $andCampana  $grupo ORDER BY $campoOrdenamiento $tipoOrdenamiento";
            }
            $sal["Resultados"] = array();
            $result = sv_mysqli_query($con, $query);
            // echo mysqli_error($con);
            $donde = 0;
            $totalLlamadas = $totalTiempoCharla = $totalTiempoPausa = $totalTiempoWrapup = $totalTiempoEspera = $totalTiempoEnActivo = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $TOTAL_TIME = $row[8];

                //Actualmente calcula el tiempo conectado,pero no coincide con
                //el tiempo entre el primer inicio de sesión y el último cierre de sesión
                // Dado que el tiempo conectado es mayor que el tiempo entre el primer inicio de sesión y el último cierre de sesión

                $TOTAL_TIME_HMS = $row[1] + $row[5];
                $TALK_TIME_HMS = $row[1];
                $PAUSE_TIME_HMS = $row[3];
                $WAIT_TIME_HMS = $row[5];
                $WRAPUP_TIME_HMS = $row[7];
                $TALK_AVG_MS = $row[2];
                $PAUSE_AVG_MS = $row[4];
                $WAIT_AVG_MS = $row[6];
                $WRAPUP_AVG_MS = $row[9];
                $user = $sal["Resultados"][$donde]["usuario"] = $row[10];

                $query2 = "SELECT DATE(event_date) as fecha,MAX(event_date) as maximo,MIN(event_date) as minimo  FROM vicidial_user_log AS vul WHERE event  IN ('LOGIN','LOGOUT') AND user='$user' AND DATE(event_date) BETWEEN DATE('$fechaInicio') AND DATE('$fechaFin')  GROUP BY DATE(event_date) ORDER BY DATE(event_date) DESC";
                $sal["Resultados"][$donde]["HoraEntradaSalida"] = array();
                $result2 = sv_mysqli_query($con, $query2);
                while ($row2 = sv_mysqli_fetch_array($result2)) {
                    $tiempoInicio = new DateTime($row2["maximo"]);
                    $tiempoFinal = new DateTime($row2["minimo"]);
                    $resultado = $tiempoInicio->diff($tiempoFinal);
                    if ($resultado === false) {
                        $resultado = "Ay drake, valio verga";
                    }

                    $sal["Resultados"][$donde]["HoraEntradaSalida"][] = array_merge($row2,
                     array(
                        "Diferencia" => $resultado->format("%H:%I:%S"),
                        //Esto debe devolver la cantidad de segundos
                        "DiferenciaTiempo" =>  $resultado->format("%H")*3600 + $resultado->format("%I")*60 + $resultado->format("%S"),
                        )
                    );
                }
                $sal["Resultados"][$donde]["nombre"] = $row[11];
                $sal["Resultados"][$donde]["total"] = $row[0];
                $sal["Resultados"][$donde]["tiempoCharla"] = $TALK_TIME_HMS;
                $sal["Resultados"][$donde]["promedioTiempoCharla"] = $TALK_AVG_MS;
                $sal["Resultados"][$donde]["tiempoPausa"] = $PAUSE_TIME_HMS;
                $sal["Resultados"][$donde]["promedioTiempoPausa"] = $PAUSE_AVG_MS;
                $sal["Resultados"][$donde]["tiempoWrapup"] = $WRAPUP_TIME_HMS;
                $sal["Resultados"][$donde]["promedioTiempoWrapup"] = $WRAPUP_AVG_MS;
                $sal["Resultados"][$donde]["tiempoEspera"] = $WAIT_TIME_HMS;
                $sal["Resultados"][$donde]["promedioTiempoEspera"] = $WAIT_AVG_MS;
                $sal["Resultados"][$donde++]["tiempoTotalEnActivo"] = $TOTAL_TIME_HMS;
                $totalTiempoCharla += $TALK_TIME_HMS;
                $totalTiempoPausa += $PAUSE_TIME_HMS;
                $totalTiempoWrapup += $WRAPUP_TIME_HMS;
                $totalTiempoEspera += $WAIT_TIME_HMS;
                $totalTiempoEnActivo += $TOTAL_TIME_HMS;
                $totalLlamadas += $row[0];
            }
            $sal["TotalTiempoCharla"] = $totalTiempoCharla;
            $sal["TotalTiempoPausa"] = $totalTiempoPausa;
            $sal["TotalTiempoWrapup"] = $totalTiempoWrapup;
            $sal["TotalTiempoEspera"] = $totalTiempoEspera;
            $sal["TotalTiempoEnActivo"] = $totalTiempoEnActivo;
            $sal["TotalLlamadasHechas"] = $totalLlamadas;
            sv_mysqli_close($con);
            if (!isset($_GET["csv"])) {
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                $sal["TotalTiempoEnActivo"] = $this->convertTime($sal["TotalTiempoEnActivo"]);
                $sal["TotalTiempoPausa"] = $this->convertTime($sal["TotalTiempoPausa"]);
                $sal["TotalTiempoCharla"] = $this->convertTime($sal["TotalTiempoCharla"]);
                $sal["TotalTiempoWrapup"] = $this->convertTime($sal["TotalTiempoWrapup"]);
                $sal["TotalTiempoEspera"] = $this->convertTime($sal["TotalTiempoEspera"]);
                foreach ($sal["Resultados"] as &$reg) {
                    $reg["tiempoCharla"] = $this->convertTime($reg["tiempoCharla"]);
                    $reg["promedioTiempoCharla"] = $this->convertTime($reg["promedioTiempoCharla"]);
                    $reg["tiempoPausa"] = $this->convertTime($reg["tiempoPausa"]);
                    $reg["promedioTiempoPausa"] = $this->convertTime($reg["promedioTiempoPausa"]);
                    $reg["tiempoWrapup"] = $this->convertTime($reg["tiempoWrapup"]);
                    $reg["promedioTiempoWrapup"] = $this->convertTime($reg["promedioTiempoWrapup"]);
                    $reg["tiempoEspera"] = $this->convertTime($reg["tiempoEspera"]);
                    $reg["promedioTiempoEspera"] = $this->convertTime($reg["promedioTiempoEspera"]);
                    $reg["tiempoTotalEnActivo"] = $this->convertTime($reg["tiempoTotalEnActivo"]);
                }
                header('Content-Type: application/csv');
                header("Content-Disposition: attachment; filename=ReporteHorarioAgente.csv");
                ob_clean();
                $out = fopen('php://output', 'w');
                fwrite($out, "{$this->lang->line('header_1')},{$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')},{$this->lang->line('header_12')}\n");
                foreach ($sal["Resultados"] as $value) {
                    fwrite($out, "{$value['usuario']},{$value['nombre']},{$value['tiempoCharla']},{$value['promedioTiempoCharla']},{$value['tiempoPausa']},{$value['promedioTiempoPausa']},{$value['tiempoEspera']},{$value['promedioTiempoEspera']},{$value['tiempoWrapup']},{$value['promedioTiempoWrapup']},{$value['tiempoTotalEnActivo']},{$value['total']}\n");
                }
                fwrite($out, ",,{$sal['TotalTiempoCharla']},,{$sal['TotalTiempoPausa']},,{$sal['TotalTiempoEspera']},,{$sal['TotalTiempoWrapup']},,{$sal['TotalTiempoEnActivo']},{$sal['TotalLlamadasHechas']}\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('reporteHorarioAgente/head');
        $this->load->view('reporteHorarioAgente/vw_reporte_horario_agente');
        $this->load->view('reporteHorarioAgente/foot');
    }
}
