<?php
// File: API_KONEKSI/config/middleware.php
require_once __DIR__ . '/../auth/jwt_helper.php';

function authenticateJWT() {
    $headers = null;
    
    // Nginx / Apache
    if (isset($_SERVER['Authorization'])) {
        $headers = trim($_SERVER["Authorization"]);
    } else if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }

    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            $token = $matches[1];
            $payload = decodeJWT($token);
            
            if ($payload) {
                return $payload; // Return payload array (berisi user_id, dll)
            }
        }
    }
    
    // Jika token tidak ada / tidak valid
    http_response_code(401);
    echo json_encode([
        "status" => "gagal",
        "pesan" => "Akses Ditolak: Token KTP Digital (JWT) tidak valid atau kadaluarsa. Silakan login ulang.",
        "data" => []
    ]);
    exit;
}
?>
