<?php
/**
 * API Middleware
 * Handles JWT authentication, CORS, and request validation
 */

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/JWTHelper.php';
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/RBAC.php';

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

/**
 * Authenticate request and return user data
 */
function authenticateRequest() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? null;
    
    if (!$authHeader) {
        http_response_code(401);
        echo json_encode(['error' => 'Authorization header missing']);
        exit();
    }
    
    // Extract token from "Bearer <token>"
    $token = null;
    if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
        $token = $matches[1];
    }
    
    if (!$token) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid authorization format']);
        exit();
    }
    
    // Validate token
    $payload = JWTHelper::validate($token);
    
    if (!$payload) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        exit();
    }
    
    // Verify user still exists and is active
    $db = Database::getInstance();
    $sql = "SELECT u.*, r.role_name FROM users u 
            LEFT JOIN roles r ON u.role_id = r.id 
            WHERE u.id = ? AND u.status = 'active'";
    
    $result = $db->query($sql, [$payload['user_id']]);
    $user = $result->fetch_assoc();
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['error' => 'User not found or inactive']);
        exit();
    }
    
    return [
        'user_id' => $user['id'],
        'email' => $user['email'],
        'role_id' => $user['role_id'],
        'role_name' => $user['role_name']
    ];
}

/**
 * Check if user has permission
 */
function requirePermission($permissionName) {
    $user = authenticateRequest();
    
    $rbac = new RBAC();
    if (!$rbac->hasPermission($user['user_id'], $permissionName)) {
        http_response_code(403);
        echo json_encode(['error' => 'Insufficient permissions']);
        exit();
    }
    
    return $user;
}

/**
 * Check if user has role
 */
function requireRole($roleName) {
    $user = authenticateRequest();
    
    if ($user['role_name'] !== $roleName) {
        http_response_code(403);
        echo json_encode(['error' => 'Insufficient role privileges']);
        exit();
    }
    
    return $user;
}

/**
 * Get JSON request body
 */
function getJsonBody() {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON']);
        exit();
    }
    
    return $data;
}

/**
 * Send JSON response
 */
function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit();
}

/**
 * Send error response
 */
function sendError($message, $statusCode = 400) {
    http_response_code($statusCode);
    echo json_encode(['error' => $message]);
    exit();
}

/**
 * Validate required fields
 */
function validateRequired($data, $requiredFields) {
    $missing = [];
    
    foreach ($requiredFields as $field) {
        if (!isset($data[$field]) || empty($data[$field])) {
            $missing[] = $field;
        }
    }
    
    if (!empty($missing)) {
        sendError('Missing required fields: ' . implode(', ', $missing));
    }
}
?>
