<?php
session_start();

header('Content-Type: application/json; charset=utf-8');

$user = $_SESSION['user'] ?? null;
$isSuper = is_array($user) && isset($user['isSuper']) && (int)$user['isSuper'] === 1;
if (!$isSuper) {
    echo json_encode(['error' => 'No autorizado.']);
    exit;
}

$token = $_SESSION['node_token'] ?? '';
if (!is_string($token) || trim($token) === '') {
    echo json_encode(['error' => 'Token de sesión no disponible. Vuelva a iniciar sesión.']);
    exit;
}

$nodeApiBase = getenv('COMPRANET_NODE_API_BASE');
if (!$nodeApiBase) {
    $nodeApiBase = 'https://app.compranet.com.co';
}

function cpn_node_request(string $method, string $url, string $token, ?array $payload = null): array
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $token,
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);

    if ($payload !== null) {
        $json = json_encode($payload);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    }

    $resp = curl_exec($ch);
    $err = curl_error($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($resp === false) {
        return ['ok' => false, 'error' => ['message' => 'Error conectando a Node: ' . ($err ?: 'desconocido')], '_http' => $http];
    }

    $data = json_decode($resp, true);
    if (!is_array($data)) {
        $snippet = substr((string)$resp, 0, 500);
        return ['ok' => false, 'error' => ['message' => 'Respuesta inválida de Node', 'raw' => $snippet], '_http' => $http];
    }
    $data['_http'] = $http;
    return $data;
}

$action = $_POST['action'] ?? '';

// GET -> list
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $url = rtrim($nodeApiBase, '/') . '/api/admin-users';
    $r = cpn_node_request('GET', $url, $token, null);
    if (!isset($r['ok']) || $r['ok'] !== true) {
        $msg = $r['error']['message'] ?? 'Error consultando usuarios.';
        $details = $r['error']['details'] ?? ($r['error']['raw'] ?? null);
        echo json_encode(['error' => $msg, 'details' => $details, 'http' => $r['_http'] ?? null]);
        exit;
    }
    echo json_encode(['data' => $r['data'] ?? []]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Método no permitido.']);
    exit;
}

if ($action === 'create') {
    $payload = [
        'nombre' => trim($_POST['nombre'] ?? ''),
        'apellido' => trim($_POST['apellido'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'password' => (string)($_POST['password'] ?? ''),
        'roleId' => (int)($_POST['roleId'] ?? 0),
        'activo' => (int)($_POST['activo'] ?? 0),
        'isSuper' => 0,
    ];

    $url = rtrim($nodeApiBase, '/') . '/api/admin-users';
    $r = cpn_node_request('POST', $url, $token, $payload);
    if (!isset($r['ok']) || $r['ok'] !== true) {
        $msg = $r['error']['message'] ?? 'Error creando usuario.';
        $details = $r['error']['details'] ?? ($r['error']['raw'] ?? null);
        echo json_encode(['error' => $msg, 'details' => $details, 'http' => $r['_http'] ?? null]);
        exit;
    }

    echo json_encode(['data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'update') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(['error' => 'ID inválido.']);
        exit;
    }

    $payload = [
        'nombre' => trim($_POST['nombre'] ?? ''),
        'apellido' => trim($_POST['apellido'] ?? ''),
        'roleId' => (int)($_POST['roleId'] ?? 0),
        'activo' => (int)($_POST['activo'] ?? 0),
    ];
    if (isset($_POST['password']) && trim((string)$_POST['password']) !== '') {
        $payload['password'] = (string)$_POST['password'];
    }

    $url = rtrim($nodeApiBase, '/') . '/api/admin-users/' . $id;
    $r = cpn_node_request('PATCH', $url, $token, $payload);
    if (!isset($r['ok']) || $r['ok'] !== true) {
        $msg = $r['error']['message'] ?? 'Error actualizando usuario.';
        $details = $r['error']['details'] ?? ($r['error']['raw'] ?? null);
        echo json_encode(['error' => $msg, 'details' => $details, 'http' => $r['_http'] ?? null]);
        exit;
    }

    echo json_encode(['data' => $r['data'] ?? null]);
    exit;
}

if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(['error' => 'ID inválido.']);
        exit;
    }

    $url = rtrim($nodeApiBase, '/') . '/api/admin-users/' . $id;
    $r = cpn_node_request('DELETE', $url, $token, null);
    if (!isset($r['ok']) || $r['ok'] !== true) {
        $msg = $r['error']['message'] ?? 'Error eliminando usuario.';
        $details = $r['error']['details'] ?? ($r['error']['raw'] ?? null);
        echo json_encode(['error' => $msg, 'details' => $details, 'http' => $r['_http'] ?? null]);
        exit;
    }

    echo json_encode(['data' => $r['data'] ?? null]);
    exit;
}

echo json_encode(['error' => 'Acción inválida.']);
