<?php
    header("Content-Type:application/json");
    include("../connection.php");
    

    // validar que hay paginacion del easyui
    $page = 1;
    $rows = 99;
    $order = "";
    $value = "";
    $name = "";
    $sort = "";
    if (isset($_REQUEST['page']))
        $page = intval($db->real_escape_string($_REQUEST['page']));
    if (isset($_REQUEST['rows']))
        $rows = intval($db->real_escape_string($_REQUEST['rows']));
    if (isset($_REQUEST['sort']))
        $sort = strval($db->real_escape_string($_REQUEST['sort']));
    if (isset($_REQUEST['order']))
        $order = strval($db->real_escape_string($_REQUEST['order']));
    if (isset($_REQUEST['value']))
        $value = strval($db->real_escape_string($_REQUEST['value']));
    if (isset($_REQUEST['name']))
        $name = strval($db->real_escape_string($_REQUEST['name']));
    if ($name == "all"){
        $name = "";
    }
    //Limite maximo para evitar explotaci¨®n de muchos datos
    $rows = ($rows > 50) ? 50 : $rows;

    $errMsg = "";
    if (!isset($_REQUEST["sessid"]) || empty($_REQUEST["sessid"]) ) { $errMsg .= "No se recibio el Parametro sessid. "; }
    
    $salida = new stdClass();
    
    if (!empty($errMsg) ){
        http_response_code(400);
        $salida->msg = $errMsg;
        echo (json_encode($salida));
        return;
    }
    $sessid = preg_replace("/[^a-zA-Z0-9]/", "", $db->real_escape_string($_REQUEST["sessid"]));

    /* Se valida el usuario y la session */
    $sql =  "SELECT id, name, rif, accs_users " .
            "FROM   users " .
            "WHERE  sessionid = ? " .
            "  AND  IF(CURDATE()<sessionvalidthru, 1, 0)" ;

            
    //Preparamos el statement
    $stmt =  $db->prepare($sql);
    //Remplazamos los parametros en la consulta almacenada
    $stmt->bind_param("s", $sessid);

    //Validamos la ejecuciÃ³n
    if (!($stmt->execute())){
        http_response_code(500);
        $salida->rsp = false ;
        $salida->msg = mysqli_error($db);
        echo (json_encode($salida));
        return;
    }

    //Obtenemos los resultados y recorremos
    $result = $stmt->get_result();
    if (!($rs = mysqli_fetch_array($result))){
        switch (mysqli_errno($db)){
            case 0:
                http_response_code(401);
                $salida->rsp = true ;
                $salida->msg = "Sesion invalida o terminada";
                $salida->sql = $sql;
                $salida->errno = 0;
                echo (json_encode($salida));
                return;
                break;
            default:
                http_response_code(500);
                $salida->rsp = false ;
                $salida->msg = mysqli_error($db);
                echo (json_encode($salida));
                return;
                break;
        }
    }

    // Se verifica si tiene permiso
    if ($rs["accs_users"]*1 < 1){
        http_response_code(401);
        $salida->rsp = false ;
        $salida->msg = "No tiene los privilegios para visualizar los usuarios";
        $salida->name = $rs["name"];
        $salida->accs = $rs["accs_users"]*1;
        $salida->sessid = $sessid;
        echo (json_encode($salida));
        return;
    }

    // contar nummero de documentos para la paginacion
    $sql = "SELECT * FROM users ORDER BY user " ;
    if (!($qry = mysqli_query($db, $sql))){
        http_response_code(500);
        $salida->msg = mysqli_error($db);
        $salida->sql = $sql;
    }else{
        $numofrecords = mysqli_num_rows($qry);
        mysqli_free_result($qry);
        
        $where = "";
        if ($name != ""){
            if ($value != ""){
                $where = " WHERE " . $name . " LIKE '%" . $value . "%' ";
            }
        }else{
            if ($value != ""){
                $where = " WHERE user   LIKE '%" . $value . "%' OR " .
                         "       name   LIKE '%" . $value . "%' OR " .
                         "       rif    LIKE '%" . $value . "%' OR " .
                         "       email  LIKE '%" . $value . "%' OR " .
                         "       status LIKE '%" . $value . "%' ";
            }
        }
        if ($sort != "" && !empty($sort)){
            $order = "ORDER BY " . $sort ." " . $order . " ";
        }

        // realizar query limitando paginacion actual
        $sql   =  "SELECT A.* FROM (" .
                      "SELECT  users.id, ". 
                              "users.user,  ".
                              "users.name, " .
                              "users.rif, " .
                              "users.email, " .
                              "users.status,".
                              "users.accs_customers," .
                              "users.accs_users," .
                              "users.accs_invoices," .
                              "users.accs_reports," .  
                              "users.accs_approve " .   
                      "FROM   users " .
                  ") A " .
                  $where . 
                  $order ." " .
                  "LIMIT  " . ($page-1)*$rows . "," . $rows;
                  
        if (!($qry = mysqli_query($db, $sql))){
            http_response_code(500);
            $salida->msg = mysqli_error($db);
            $salida->sql = $sql;
        }else{
            $records = array();
            while ($row = mysqli_fetch_array($qry)){
                array_push($records, 
                                array( 
                                "id"      => $row["id"]*1, 
                                "user"    => $row["user"], 
                                "name"    => $row["name"],
                                "email"   => $row["email"],
                                "status"  => $row["status"]*1,
                                "accs_customers" => $row["accs_customers"]*1,
                                "accs_users"     => $row["accs_users"]*1,
                                "accs_invoices"  => $row["accs_invoices"]*1,
                                "accs_reports"   => $row["accs_reports"]*1,
                                "accs_approve"   => $row["accs_approve"]*1
                                )
                );
            }
            mysqli_free_result($qry);
            http_response_code(200);
            $salida->total        = $numofrecords;
            $salida->rows         = $records;
        }
    }
    
    echo (json_encode($salida));
?>