<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/auth.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? '';
    $result = match ($action) {
        'npm_proxies'    => vv_npm_list_proxies(),
        'npm_certs'      => ['ok' => true, 'certs' => vv_npm_list_certs()],
        'lldap_users'    => vv_lldap_list_users(),
        'lldap_groups'   => vv_lldap_list_groups(),
        'authelia_rules' => vv_authelia_read_rules(),
        default          => ['ok' => false, 'error' => 'Unknown action: ' . $action],
    };
    echo json_encode($result);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'GET or POST only']);
    exit;
}

$action = trim($_POST['action'] ?? '');

$result = match ($action) {
    // NPM
    'npm_create'              => vv_npm_create_proxy(json_decode($_POST['data'] ?? '{}', true) ?: []),
    'npm_update'              => vv_npm_update_proxy((int)($_POST['id'] ?? 0), json_decode($_POST['data'] ?? '{}', true) ?: []),
    'npm_delete'              => vv_npm_delete_proxy((int)($_POST['id'] ?? 0)),
    'npm_toggle'              => vv_npm_toggle_proxy((int)($_POST['id'] ?? 0), ($_POST['enabled'] ?? '0') === '1'),
    // lldap
    'lldap_create_user'       => vv_lldap_create_user($_POST['uid'] ?? '', $_POST['email'] ?? '', $_POST['display_name'] ?? '', $_POST['password'] ?? ''),
    'lldap_update_user'       => vv_lldap_update_user($_POST['uid'] ?? '', $_POST['email'] ?? '', $_POST['display_name'] ?? ''),
    'lldap_delete_user'       => vv_lldap_delete_user($_POST['uid'] ?? ''),
    'lldap_set_password'      => vv_lldap_set_password($_POST['uid'] ?? '', $_POST['password'] ?? ''),
    'lldap_create_group'      => vv_lldap_create_group($_POST['name'] ?? ''),
    'lldap_delete_group'      => vv_lldap_delete_group((int)($_POST['id'] ?? 0)),
    'lldap_add_to_group'      => vv_lldap_add_to_group($_POST['uid'] ?? '', (int)($_POST['gid'] ?? 0)),
    'lldap_remove_from_group' => vv_lldap_remove_from_group($_POST['uid'] ?? '', (int)($_POST['gid'] ?? 0)),
    // Authelia
    'authelia_save'           => vv_authelia_write_rules(json_decode($_POST['rules'] ?? '[]', true) ?: [], $_POST['default_policy'] ?? 'deny'),
    default                   => ['ok' => false, 'error' => 'Unknown action: ' . $action],
};

echo json_encode($result);
