<?php

require_once "BASEPATH.php";

class ReporteCambiosAdmin 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 systemLog()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reportecambiosadmin', "spanish");
                break;
            case "en":
                $this->lang->load('reportecambiosadmin', "english");
                break;
            default:
                $this->lang->load('reportecambiosadmin', "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';
            header('Content-type: application/json');
            $fechaInicial = limpia($_GET["fechaInicial"]);
            $fechaFinal = limpia($_GET["fechaFinal"]);
            $usuario = $_SESSION["Usuario"];
            $con = getConnection();
            $sal = array();
            $query = "SELECT user_level,user_group from vicidial_users WHERE user = '$usuario'";
            $result = sv_mysqli_query($con, $query);
            $row = sv_mysqli_fetch_array($result);
            $and = "";
            if ($_SESSION["Cliente"] != -1) {
                $and = "AND user IN (SELECT user FROM vicidial_users WHERE user_group LIKE '" . $_SESSION["Cliente"] . "%')";
            }
            $sal["and"] = $and;
            if ($row["user_level"] >= 9) {
                $LOGuser_group = $row["user_group"];
                $LIMITE = "";
                if (isset($_GET["pagina"])) {
                    $registros = 10;
                    $pagina = $_GET["pagina"] - 1;
                    $skip = $pagina * $registros;
                    $LIMITE = "LIMIT $skip,$registros";
                }
                $categoria = limpia($_GET["categoria"]);
                $cual = limpia($_GET["cual"]);
                if ((int) $cual == -1) {
                    $cual = "record_id";
                } else {
                    $cual = "'$cual'";
                }
                $sectionSQL = "event_section='$categoria'";
                if (preg_match("/CAMPAIGNS/", $categoria)) {
                    $sectionSQL = "event_section IN('CAMPAIGNS','CAMPAIGN_SURVEY','CAMPAIGN_LISTMIX','CAMPAIGN_PRESET','CAMPAIGN_QC','CAMPAIGN_PAUSECODE','CAMPAIGN_RECYCLE','CAMPAIGN_HOTKEY','CAMPAIGN_STATUS','CAMPAIGN_DIALSTATUSES','CAMPAIGN_DIALSTATUS','CAMPAIGN_AC-CID')";
                }
                if (preg_match("/DIDS/", $categoria)) {
                    $sectionSQL = "event_section IN('DIDS','DID_RA-EXTEN')";
                }
                if ((int) $categoria == -1) {
                    $sectionSQL = "event_section = event_section";
                }
                $stmt = "SELECT admin_log_id,event_date,user,ip_address,event_section,event_type,record_id,event_code,user_group from vicidial_admin_log where $sectionSQL and record_id=$cual AND DATE(event_date)>=DATE('$fechaInicial') AND DATE(event_date)<=DATE('$fechaFinal') $and order by event_date desc $LIMITE";
                $result = sv_mysqli_query($con, $stmt);
                $sal["Log"] = array();
                while ($row = sv_mysqli_fetch_array($result)) {
                    $sal["Log"][] = $row;
                }
                $query = "SELECT COUNT(admin_log_id)from vicidial_admin_log where $sectionSQL AND DATE(event_date)>=DATE('$fechaInicial') AND DATE(event_date)<=DATE('$fechaFinal') and record_id=$cual $and";
                $result = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($result);
                sv_mysqli_close($con);
                if (!isset($_GET["csv"])) {
                    $sal["Cuenta"] = $row[0];
                    $sal["Estado"] = "ok";
                    $this->output->set_output(json_encode($sal));
                } else {
                    header('Content-Type: application/csv');
                    header("Content-Disposition: attachment; filename=Registro de cambios de administracion.csv");
                    header("Pragma: no-cache");
                    header("Expires: 0");
                    ob_clean();
                    $out = fopen('php://output', 'w');
                    fwrite($out, "ID,{$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")}\n");
                    foreach ($sal["Log"] as $value) {
                        fwrite($out, "{$value['admin_log_id']},{$value['event_date']},{$value['user']},{$value['ip_address']},{$value['event_section']},{$value['event_type']},{$value['record_id']},{$value['event_code']}\n");
                    }
                    fclose($out);
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_SinPermisosCambios");
                $this->output->set_output(json_encode($sal));
            }

        } 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('reporteCambiosAdmin/head');
        $this->load->view('reporteCambiosAdmin/vw_reporte_cambios_admin');
        $this->load->view('reporteCambiosAdmin/foot');
    }
}
