<?php
// Application middleware

// e.g: $app->add(new \Slim\Csrf\Guard);

// middleware untuk validasi api key
$app->add(function ($request, $response, $next) {
    
    $key = $request->getQueryParam("nik");

    if(!isset($key)){
        return $response->withJson(["status" => "API Key required"], 401);
    }
    
    $sql = "SELECT * FROM login WHERE nik=:nik";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nik" => $key]);
    
    if($stmt->rowCount() > 0){
        $result = $stmt->fetch();
        if($key == $result["nik"]){
        
            // update hit
        //    $sql = "UPDATE api_users SET hit=hit+1 WHERE api_key=:api_key";
        //    $stmt = $this->db->prepare($sql);
        //    $stmt->execute([":api_key" => $key]);
            
            return $response = $next($request, $response);
        }
    }

    return $response->withJson(["status" => "Unauthorized"], 401);

});