<?php

function authenticate() {
    $headers     = getallheaders();
    $authHeader  = $headers['Authorization'] ?? $headers['authorization'] ?? '';

    if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
        sendError('Unauthorized. Token missing.', 401);
    }

    $token   = substr($authHeader, 7);
    $payload = verifyJWT($token);

    if (!$payload) {
        sendError('Unauthorized. Invalid or expired token.', 401);
    }

    // Validate token against devices table and fetch user role/status
    $db   = getDB();
    $stmt = $db->prepare("
        SELECT d.user_id, u.role, u.status
        FROM devices d
        JOIN users u ON u.id = d.user_id
        WHERE d.user_id = ? AND d.token = ?
    ");
    $stmt->bind_param("is", $payload['user_id'], $token);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $db->close();

    if (!$result) {
        sendError('Unauthorized. Session expired.', 401);
    }

    if ($result['status'] === 'INACTIVE') {
        sendError('Account is inactive.', 403);
    }

    $payload['role'] = $result['role'];
    return $payload;
}

function requireAdmin($payload) {
    if ($payload['role'] !== 'SUPER_ADMIN') {
        sendError('Forbidden. Admin access required.', 403);
    }
}
