<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

header('Content-Type: application/json');
// Este archivo se consume por AJAX (jQuery). Evitar 4xx/5xx aquí para que no caiga en callbacks .fail().
http_response_code(200);
$action = $_REQUEST['action'] ?? '';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

switch ($action) {
    case 'get_user':
        $id = intval($_REQUEST['id'] ?? 0);
        if (!$id) {
            echo json_encode(['error' => 'ID inválido']);
            exit;
        }

        $url = $base . '/api/usuarios/' . urlencode((string)$id);
        $r = cpn_node_request('GET', $url, $token);
        if (!isset($r['ok']) || $r['ok'] !== true) {
            $msg = $r['error']['message'] ?? 'Error consultando usuario.';
            // Importante: no devolver 4xx/5xx aquí, porque la UI usa $.getJSON()
            // y en esos casos entra por .fail() y deja la pantalla en blanco.
            echo json_encode(['error' => $msg, 'http' => (int)($r['_http'] ?? 500)]);
            exit;
        }

        echo json_encode($r['data'] ?? []);
        exit;

        // —————————————
    case 'update_field':
        $tabla = $_POST['tabla']  ?? '';
        $id    = intval($_POST['id']    ?? 0);
        $field = $_POST['field']  ?? '';
        $value = $_POST['value']  ?? '';

        // Campos permitidos por tabla
        $allowed = [
            'tb_usuarios' => [
                'nombre',
                'apellido',
                'email',
                'telefono',
                'idCiudad'
            ],
            'tb_usuarios_direcciones' => [
                'identificacion',
                'nombre',
                'apellido',
                'razonSocial',
                'direccion',
                'direccionLinea2',
                'idCiudad',
                'telefono',
                'email'
            ],
            'tb_terceros' => [
                'idTipoTercero',
                'idRegimen',
                'idTipoDocumento',
                'idDireccion',
                'noDocumento',
                'dv',
                'nombre',
                'apellido',
                'razonSocial',
                'emailFactura'
            ]
        ];

        if (!isset($allowed[$tabla]) || !in_array($field, $allowed[$tabla], true)) {
            echo json_encode(['success' => false, 'error' => 'Tabla o campo inválido']);
            exit;
        }

        if (!$id) {
            echo json_encode(['success' => false, 'error' => 'ID inválido']);
            exit;
        }

        // Enrutamiento hacia Node según tabla
        if ($tabla === 'tb_usuarios') {
            $url = $base . '/api/usuarios/' . urlencode((string)$id);
        } elseif ($tabla === 'tb_usuarios_direcciones') {
            $url = $base . '/api/usuarios/direcciones/' . urlencode((string)$id);
        } elseif ($tabla === 'tb_terceros') {
            $url = $base . '/api/usuarios/terceros/' . urlencode((string)$id);
        } else {
            echo json_encode(['success' => false, 'error' => 'Tabla no soportada']);
            exit;
        }

        $r = cpn_node_request('PATCH', $url, $token, ['field' => $field, 'value' => $value]);
        if (!isset($r['ok']) || $r['ok'] !== true) {
            $msg = $r['error']['message'] ?? 'Error actualizando.';
            echo json_encode(['success' => false, 'error' => $msg]);
            exit;
        }
        echo json_encode(['success' => true]);
        exit;

        // —————————————
    case 'delete_address':
        $id = intval($_POST['id'] ?? 0);
        if (!$id) {
            echo json_encode(['success' => false, 'error' => 'ID inválido']);
            exit;
        }
        $url = $base . '/api/usuarios/direcciones/' . urlencode((string)$id);
        $r = cpn_node_request('DELETE', $url, $token);
        if (!isset($r['ok']) || $r['ok'] !== true) {
            $msg = $r['error']['message'] ?? 'Error eliminando dirección.';
            echo json_encode(['success' => false, 'error' => $msg]);
            exit;
        }
        echo json_encode(['success' => true]);
        exit;

        // —————————————
    case 'add_address':
        $u = intval($_POST['userId'] ?? 0);
        if (!$u) {
            echo json_encode(['success' => false, 'error' => 'ID inválido']);
            exit;
        }

        $payload = [
            'identificacion' => (string)($_POST['identificacion'] ?? ''),
            'nombre' => (string)($_POST['nombre'] ?? ''),
            'apellido' => (string)($_POST['apellido'] ?? ''),
            'razonSocial' => (string)($_POST['razonSocial'] ?? ''),
            'direccion' => (string)($_POST['direccion'] ?? ''),
            'direccionLinea2' => (string)($_POST['direccionLinea2'] ?? ''),
            'idCiudad' => (int)($_POST['idCiudad'] ?? 0),
            'telefono' => (string)($_POST['telefono'] ?? ''),
            'email' => (string)($_POST['email'] ?? ''),
        ];

        $url = $base . '/api/usuarios/' . urlencode((string)$u) . '/direcciones';
        $r = cpn_node_request('POST', $url, $token, $payload);
        if (!isset($r['ok']) || $r['ok'] !== true) {
            $msg = $r['error']['message'] ?? 'Error agregando dirección.';
            echo json_encode(['success' => false, 'error' => $msg]);
            exit;
        }
        echo json_encode(['success' => true]);
        exit;

        // —————————————
    case 'add_tercero':
        $u  = intval($_POST['userId'] ?? 0);
        if (!$u) {
            echo json_encode(['success' => false, 'error' => 'ID inválido']);
            exit;
        }

        $payload = [
            'idTipoTercero' => (int)($_POST['idTipoTercero'] ?? 0),
            'idRegimen' => (int)($_POST['idRegimen'] ?? 0),
            'idTipoDocumento' => (int)($_POST['idTipoDocumento'] ?? 0),
            'idDireccion' => (int)($_POST['idDireccion'] ?? 0),
            'noDocumento' => (string)($_POST['noDocumento'] ?? ''),
            'dv' => (string)($_POST['dv'] ?? ''),
            'nombre' => (string)($_POST['nombre'] ?? ''),
            'apellido' => (string)($_POST['apellido'] ?? ''),
            'razonSocial' => (string)($_POST['razonSocial'] ?? ''),
            'emailFactura' => (string)($_POST['emailFactura'] ?? ''),
        ];

        $url = $base . '/api/usuarios/' . urlencode((string)$u) . '/terceros';
        $r = cpn_node_request('POST', $url, $token, $payload);
        if (!isset($r['ok']) || $r['ok'] !== true) {
            $msg = $r['error']['message'] ?? 'Error agregando tercero.';
            echo json_encode(['success' => false, 'error' => $msg]);
            exit;
        }
        echo json_encode(['success' => true]);
        exit;

        // —————————————
    case 'create_user':
        $payload = [
            'nombre' => (string)($_POST['nombre'] ?? ''),
            'apellido' => (string)($_POST['apellido'] ?? ''),
            'email' => (string)($_POST['email'] ?? ''),
            'telefono' => (string)($_POST['telefono'] ?? ''),
            'idCiudad' => (int)($_POST['idCiudad'] ?? 0),
        ];

        $r = cpn_node_request('POST', $base . '/api/usuarios', $token, $payload);
        if (!isset($r['ok']) || $r['ok'] !== true) {
            $msg = $r['error']['message'] ?? 'Error creando usuario.';
            echo json_encode(['success' => false, 'error' => $msg]);
            exit;
        }

        $newId = (int)($r['data']['id'] ?? 0);
        echo json_encode([
            'success' => true,
            'newId' => $newId,
            'name' => trim($payload['nombre'] . ' ' . $payload['apellido']),
        ]);
        exit;

        // —————————————
    default:
        echo json_encode(['success' => false, 'error' => 'Acción no válida']);
        exit;
}
