<?php
/**
 * Auth Middleware
 * Handles authentication and authorization
 */

require_once('jwt-utils.php');

class AuthMiddleware {
    /**
     * Validate JWT token from request
     * 
     * @return array [success, user_data]
     */
    public function validateRequest() {
        $headers = getallheaders();
        
        if (!isset($headers['Authorization'])) {
            return [false, 'No authorization token provided'];
        }
        
        $token = str_replace('Bearer ', '', $headers['Authorization']);
        return onesignal_validateToken($token);
    }
    
    /**
     * Check if user is authenticated
     * 
     * @return bool
     */
    public function isAuthenticated() {
        list($success, $user) = $this->validateRequest();
        return $success;
    }
    
    /**
     * Get authenticated user
     * 
     * @return array|null User data or null if not authenticated
     */
    public function getAuthenticatedUser() {
        list($success, $user) = $this->validateRequest();
        return $success ? $user : null;
    }
    
    /**
     * Require authentication
     * Dies with 401 if not authenticated
     */
    public function requireAuth() {
        if (!$this->isAuthenticated()) {
            http_response_code(401);
            die(json_encode(['error' => 'Authentication required']));
        }
    }
    
    /**
     * Require specific role
     * Dies with 403 if user doesn't have required role
     * 
     * @param string $role Required role
     */
    public function requireRole($role) {
        $this->requireAuth();
        
        $user = $this->getAuthenticatedUser();
        if ($user['role'] !== $role) {
            http_response_code(403);
            die(json_encode(['error' => 'Insufficient permissions']));
        }
    }
} 