<?php

require_once "BASEPATH.php";

class ReporteEntranteDID extends MY_Controller
{
    private function addZero($valor = 0)
    {
        if ($valor < 10) {
            return "0$valor";
        }

        return $valor;
    }
    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 DIDReport()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reporteentrantedid', "spanish");
                break;
            case "en":
                $this->lang->load('reporteentrantedid', "english");
                break;
            default:
                $this->lang->load('reporteentrantedid', "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();
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $cliente = $_SESSION["Cliente"];
            $sal = array("DIDS" => array(), "fechas" => array());
            $archived = false;
            if (isset($_GET["archived"]) && limpia($_GET["archived"]) == 1) {
                $archived = true;
            }
            $fechaInicial = limpia($_GET["fechaInicial"]);
            $fechaFinal = limpia($_GET["fechaFinal"]);

            $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 did_id FROM vicidial_inbound_dids WHERE user_group  = '$cliente'";
                } else {
                    $gruposStr = "SELECT did_id FROM vicidial_inbound_dids ";
                }

            }
            $query = "SELECT DATE(call_date) AS fecha,DATE_FORMAT(call_date,'%k') AS hora,DATE_FORMAT(call_date,'%i') AS minuto,extension from vicidial_did_log where call_date >= '$fechaInicial 00:00:00' and call_date <= '$fechaFinal 23:59:59' and did_id IN($gruposStr)";

            if ($archived == 1) {
                $query = "SELECT DATE(call_date) AS fecha,DATE_FORMAT(call_date,'%k') AS hora,DATE_FORMAT(call_date,'%i') AS minuto,extension from vicidial_did_log_archive where call_date >= '$fechaInicial 00:00:00' and call_date <= '$fechaFinal 23:59:59' and did_id IN($gruposStr)";
            }
            $result = sv_mysqli_query($con, $query);
            $sal["Hora"] = array();
            for ($i = 0; $i < 24; $i++) {
                $sal["Hora"][$i] = array("0" => 0, "15" => 0, "30" => 0, "45" => 0);
            }
            while ($row = sv_mysqli_fetch_array($result)) {
                if (!isset($sal["DIDS"][$row["extension"]])) {
                    $sal["DIDS"][$row["extension"]] = 0;
                }
                if (!isset($sal["fechas"][$row["fecha"]])) {
                    $sal["fechas"][$row["fecha"]] = 0;
                }
                $sal["DIDS"][$row["extension"]]++;
                $sal["fechas"][$row["fecha"]]++;

                if ($row["minuto"] < 15) {
                    $sal["Hora"][$row["hora"]]["0"]++;
                } elseif ($row["minuto"] < 30) {
                    $sal["Hora"][$row["hora"]]["15"]++;
                } elseif ($row["minuto"] < 45) {
                    $sal["Hora"][$row["hora"]]["30"]++;
                } else {
                    $sal["Hora"][$row["hora"]]["45"]++;
                }

            }
            sv_mysqli_close($con);
            if (!isset($_GET["csv"])) {
                header('Content-type: application/json');
                $sal["Estado"] = "ok";
                $this->output->set_output(json_encode($sal));
            } else {
                ob_clean();
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=ReporteEntrantePorDID(" . $fechaInicial . "-" . $fechaFinal . ").csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                $out = fopen('php://output', 'w');

                fwrite($out, "{$this->lang->line('header_1')}\n");
                fwrite($out, "{$this->lang->line('header_2')},{$this->lang->line('header_3')}\n");
                foreach ($sal["DIDS"] as $key => $value) {
                    fwrite($out, "$key,$value\n");
                }
                fwrite($out, "\n\n");

                fwrite($out, "{$this->lang->line('header_4')}\n");
                fwrite($out, "{$this->lang->line('header_5')},{$this->lang->line('header_3')}\n");
                foreach ($sal["fechas"] as $key => $value) {
                    fwrite($out, "$key,$value\n");
                }
                fwrite($out, "\n\n");

                fwrite($out, "{$this->lang->line('header_6')}\n");
                fwrite($out, "{$this->lang->line('header_7')},{$this->lang->line('header_3')}\n");
                foreach ($sal["Hora"] as $key => $value) {
                    foreach ($value as $key2 => $value2) {
                        $inicio = $key2 - 15;
                        $fin = $key - 1;
                        fwrite($out, $this->addZero($key) . ":" . $this->addZero($inicio) . ":00 - " . $this->addZero($key) . ":" . $this->addZero($fin) . "59,$value2");
                    }
                }
                fwrite($out, "\n\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('reporteEntrantesDID/head');
        $this->load->view('reporteEntrantesDID/vw_reporte_entrantes_did');
        $this->load->view('reporteEntrantesDID/foot');
    }
}
