<?php
// TokenMiddleware.php - patched to validate Authorization Bearer tokens and fallback to session auth
require_once __DIR__ . '/bootstrap.php';
class TokenMiddleware {
  public static function authenticate(){
    $hdr = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if ($hdr){
      list($type,$token) = explode(' ', $hdr, 2) + [null,null];
      if (strtolower($type)==='bearer' && $token){
        $data = Helpers::isTokenValid($token);
        if ($data){
          $pdo = Database::getConnection();
          $stmt = $pdo->prepare('SELECT revoked FROM user_devices WHERE user_id = ? AND device_id = ? LIMIT 1');
          $stmt->execute([$data['uid'], $data['did']]);
          $row = $stmt->fetch(PDO::FETCH_ASSOC);
          if (!$row || $row['revoked']){ http_response_code(401); echo json_encode(['status'=>0,'error'=>'device_revoked']); exit; }
          $_SERVER['AUTH_USER_ID'] = $data['uid'];
          $_SERVER['AUTH_DEVICE_ID'] = $data['did'];
          return true;
        }
      }
    }
    session_start();
    if (!empty($_SESSION['user_id'])){ $_SERVER['AUTH_USER_ID'] = $_SESSION['user_id']; return true; }
    return false;
  }
}
?>