<?php
/**
 * API Authentication Guard
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/session_boot.php';

header('Content-Type: application/json');

// Check if user is authenticated
if (!isset($_SESSION['user_id']) || ($_SESSION['user_status'] ?? 'inactive') !== 'active') {
    http_response_code(401);
    echo json_encode([
        'success' => false, 
        'message' => 'Authentication required',
        'redirect' => BASE_PATH . 'pages/login.php'
    ]);
    exit();
}

/**
 * Require specific user role
 */
function requireRole($requiredRole) {
    $userRole = $_SESSION['user_role'] ?? 'user';
    $roles = ['user' => 1, 'admin' => 2, 'superuser' => 3];
    
    if (($roles[$userRole] ?? 0) < ($roles[$requiredRole] ?? 0)) {
        http_response_code(403);
        echo json_encode([
            'success' => false, 
            'message' => 'Insufficient permissions. Required role: ' . $requiredRole
        ]);
        exit();
    }
}

/**
 * Check data ownership
 */
function checkOwnership($createdBy) {
    if ($_SESSION['user_role'] === 'superuser') return true;
    if ($createdBy == $_SESSION['user_id']) return true;
    
    http_response_code(403);
    echo json_encode([
        'success' => false, 
        'message' => 'Access denied to this resource'
    ]);
    exit();
}
?>