<?php

require_once __DIR__ . '/jwt.php';

/**
 * 🔐 AMBIL HEADER AUTHORIZATION
 */
function getAuthorizationHeader() {
    $headers = null;

    if (isset($_SERVER['Authorization'])) {
        $headers = trim($_SERVER["Authorization"]);
    } 
    else if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    } 
    else if (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();

        // fix case-sensitive
        foreach ($requestHeaders as $key => $value) {
            if (strtolower($key) == 'authorization') {
                $headers = trim($value);
                break;
            }
        }
    }

    return $headers;
}

/**
 * 🔐 AMBIL TOKEN BEARER
 */
function getBearerToken() {
    $headers = getAuthorizationHeader();

    if (!$headers) return null;

    if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
        return $matches[1];
    }

    return null;
}

/**
 * 🔥 REQUIRE AUTH (WAJIB LOGIN)
 */
function requireAuth() {
    $token = getBearerToken();

    if (!$token) {
        http_response_code(401);
        echo json_encode([
            "success" => false,
            "message" => "Unauthorized (Token tidak ditemukan)"
        ]);
        exit;
    }

    $user = verifyJWT($token);

    if (!$user) {
        http_response_code(401);
        echo json_encode([
            "success" => false,
            "message" => "Token tidak valid / expired"
        ]);
        exit;
    }

    return $user; // 🔥 RETURN DATA USER DARI JWT
}

/**
 * 🔥 REQUIRE ROLE
 */
function requireRole($roles = []) {
    $user = requireAuth();

    if (!in_array($user['role'], $roles)) {
        http_response_code(403);
        echo json_encode([
            "success" => false,
            "message" => "Forbidden (Role tidak diizinkan)"
        ]);
        exit;
    }

    return $user;
}

/**
 * 🔥 HELPER: AMBIL COMPANY ID
 */
function getCompanyId() {
    $user = requireAuth();
    return $user['company_id'] ?? null;
}

/**
 * 🔥 HELPER: AMBIL USER ID
 */
function getUserId() {
    $user = requireAuth();
    return $user['user_id'] ?? null;
}

/**
 * 🔥 HELPER: AMBIL FULL USER
 */
function getAuthUser() {
    return requireAuth();
}