<?php
/**
 * Admin B2B Groups API
 * B2B groups and product pricing management
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/Database.php';
require_once __DIR__ . '/../../includes/Auth.php';
require_once __DIR__ . '/../../includes/B2B.php';

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

// Check admin authentication
$auth = new Auth();
if (!$auth->isAdmin()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$b2b = new B2B();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'list') {
                $groups = $b2b->getB2BGroups();
                echo json_encode(['success' => true, 'groups' => $groups]);
            } elseif ($action === 'get') {
                $id = $_GET['id'] ?? 0;
                $group = $b2b->getB2BGroupById($id);
                
                if ($group) {
                    $users = $b2b->getGroupUsers($id);
                    $group['users'] = $users;
                    echo json_encode(['success' => true, 'group' => $group]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Group not found']);
                }
            }
            break;

        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            if ($action === 'create') {
                $groupId = $b2b->createB2BGroup($data);
                echo json_encode(['success' => true, 'group_id' => $groupId]);
            } elseif ($action === 'update') {
                $id = $data['id'] ?? 0;
                $b2b->updateB2BGroup($id, $data);
                echo json_encode(['success' => true]);
            } elseif ($action === 'delete') {
                $id = $data['id'] ?? 0;
                $b2b->deleteB2BGroup($id);
                echo json_encode(['success' => true]);
            } elseif ($action === 'add-user') {
                $userId = $data['user_id'] ?? 0;
                $groupId = $data['b2b_group_id'] ?? 0;
                $b2b->addUserToGroup($userId, $groupId);
                echo json_encode(['success' => true]);
            } elseif ($action === 'remove-user') {
                $userId = $data['user_id'] ?? 0;
                $groupId = $data['b2b_group_id'] ?? 0;
                $b2b->removeUserFromGroup($userId, $groupId);
                echo json_encode(['success' => true]);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

