<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

// AJAX: crear usuario (mantiene UX actual sin archivos extra)
if (isset($_POST['action']) && $_POST['action'] === 'create_user') {
    header('Content-Type: application/json');
    $token = cpn_node_token_or_fail();
    $base = cpn_node_api_base();

    $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) {
        http_response_code($r['_http'] ?? 500);
        $msg = $r['error']['message'] ?? 'Error creando usuario.';
        echo json_encode(['success' => false, 'error' => $msg]);
        exit;
    }

    $newId = (int)($r['data']['id'] ?? 0);
    $name = trim($payload['nombre'] . ' ' . $payload['apellido']);
    echo json_encode(['success' => true, 'newId' => $newId, 'name' => $name]);
    exit;
}

// — PAGINACIÓN —
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit  = 50;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

$listUrl = $base . '/api/usuarios?' . http_build_query([
    'page' => $page,
    'limit' => $limit,
    'search' => $search,
]);
$resp = cpn_node_request('GET', $listUrl, $token);
if (!isset($resp['ok']) || $resp['ok'] !== true) {
    http_response_code($resp['_http'] ?? 500);
    die('Error consultando usuarios en Node');
}

$data = $resp['data'] ?? [];
$items = $data['items'] ?? [];
$totalPages = (int)($data['totalPages'] ?? 1);

$ciudadesResp = cpn_node_request('GET', $base . '/api/usuarios/ciudades', $token);
if (!isset($ciudadesResp['ok']) || $ciudadesResp['ok'] !== true) {
    http_response_code($ciudadesResp['_http'] ?? 500);
    die('Error consultando ciudades en Node');
}
$ciudades = $ciudadesResp['data'] ?? [];

include '../templates/header.php';
?>

<style>
    /* Compacto (solo esta pantalla) */
    #content .container-fluid .table {
        font-size: 12px;
    }

    #content .container-fluid .table th,
    #content .container-fluid .table td {
        padding: .25rem .35rem;
        line-height: 1.15;
    }

    #content .container-fluid .form-control,
    #content .container-fluid .custom-select,
    #content .container-fluid .form-select {
        font-size: 12px !important;
        padding: .2rem .4rem;
        height: calc(1.2em + .5rem + 2px);
    }

    #content .container-fluid .btn {
        font-size: 12px;
        padding: .25rem .5rem;
    }

    #content .container-fluid h1.h3,
    #content .container-fluid .h3 {
        font-size: 1.1rem;
    }
</style>

<h1 class="h3 mb-4 text-gray-800">Lista de Usuarios</h1>
<!-- **AÑADE** aquí el botón para Crear Usuario -->
<div class="mb-3">
    <button
        class="btn btn-success"
        data-bs-toggle="modal"
        data-bs-target="#newUserModal">Crear Usuario</button>
</div>

<form method="get" class="form-inline mb-3">
    <input
        type="text"
        name="search"
        class="form-control mr-2"
        placeholder="Buscar por nombre, apellido o email"
        value="<?= htmlspecialchars($search) ?>">
    <button type="submit" class="btn btn-primary">Buscar</button>
</form>


<div class="table-responsive mb-3">
    <table id="userTable" class="table table-bordered table-sm">
        <thead class="thead-light">
            <tr>
                <th>Nombre</th>
                <th>Apellido</th>
                <th>Email</th>
                <th>Teléfono</th>
                <th>Ciudad</th>
                <th>Acciones</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $r): ?>
                <tr>
                    <td><?= htmlspecialchars($r['nombre']) ?></td>
                    <td><?= htmlspecialchars($r['apellido']) ?></td>
                    <td><?= htmlspecialchars($r['email']) ?></td>
                    <td><?= htmlspecialchars($r['telefono']) ?></td>
                    <td><?= htmlspecialchars($r['ciudad']) ?></td>
                    <td>
                        <a
                            href="administrar_usuario.php?id=<?= $r['id'] ?>"
                            class="btn btn-sm btn-primary">Editar</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<nav>
    <ul class="pagination justify-content-center">
        <?php if ($page > 1): ?>
            <li class="page-item">
                <a
                    class="page-link"
                    href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">&laquo;</a>
            </li>
        <?php endif; ?>

        <?php
        $start = max(1, $page - 2);
        $end   = min($totalPages, $page + 2);
        for ($p = $start; $p <= $end; $p++):
            $act = $p == $page ? ' active' : '';
        ?>
            <li class="page-item<?= $act ?>">
                <a
                    class="page-link"
                    href="?<?= http_build_query(array_merge($_GET, ['page' => $p])) ?>"><?= $p ?></a>
            </li>
        <?php endfor; ?>

        <?php if ($page < $totalPages): ?>
            <li class="page-item">
                <a
                    class="page-link"
                    href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">&raquo;</a>
            </li>
        <?php endif; ?>
    </ul>
</nav>

<?php include '../templates/footer.php'; ?>
<!-- **AÑADE** al final de este archivo: el modal de Crear Usuario -->
<div class="modal fade" id="newUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form id="newUserForm" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Crear Usuario</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label>Nombre o Razón Social</label>
                    <input name="nombre" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label>Apellido</label>
                    <input name="apellido" class="form-control">
                </div>
                <div class="mb-3">
                    <label>Email</label>
                    <input name="email" type="email" class="form-control">
                </div>
                <div class="mb-3">
                    <label>Teléfono</label>
                    <input name="telefono" class="form-control">
                </div>
                <div class="mb-3">
                    <label>Ciudad</label>
                    <select name="idCiudad" class="form-control" required>
                        <?php foreach ($ciudades as $c): ?>
                            <option value="<?= (int)$c['id'] ?>">
                                <?= htmlspecialchars($c['text']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button"
                    class="btn btn-secondary"
                    data-bs-dismiss="modal">Cerrar</button>
                <button type="submit"
                    class="btn btn-primary">Crear</button>
            </div>
        </form>
    </div>
</div>
<script>
    $(document).ready(function() {
        $('#search').on('keyup', function() {
            var val = $(this).val().toLowerCase();
            $('#userTable tbody tr').filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(val) > -1);
            });
        });
    });
    $(function() {
        $('#newUserForm').on('submit', function(e) {
            e.preventDefault();
            $.post('lista_usuarios.php',
                $(this).serialize() + '&action=create_user',
                function(res) {
                    if (res.success) {
                        // redirige a la edición del nuevo usuario
                        window.location = 'administrar_usuario.php?id=' + res.newId;
                    } else {
                        alert(res.error);
                    }
                }, 'json'
            );
        });
    });
</script>