<?php
// categorias.php
include '../includes/session_control.php';
require_once '../cotizaciones/api/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

function cpn_is_ajax_request(): bool
{
    $hdr = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '';
    return is_string($hdr) && strtolower($hdr) === 'xmlhttprequest';
}

// POST: insertar o eliminar
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'insert') {
        $nombre     = trim((string)($_POST['nombre'] ?? ''));
        $noOrden    = intval($_POST['noOrden'] ?? 0);
        $esEtiqueta = isset($_POST['esEtiqueta']) ? 1 : 0;
        $idEstado   = intval($_POST['idEstado'] ?? 0);

        $resp = cpn_node_request(
            'POST',
            $base . '/api/productos/categorias/create',
            $token,
            [
                'nombre' => $nombre,
                'noOrden' => $noOrden,
                'esEtiqueta' => $esEtiqueta,
                'idEstado' => $idEstado,
            ]
        );

        if (cpn_is_ajax_request()) {
            header('Content-Type: application/json');
            if (!($resp['ok'] ?? false)) {
                http_response_code(($resp['_http'] ?? 500) ?: 500);
                echo json_encode(['error' => ($resp['error']['message'] ?? 'Error creando categoría')]);
                exit;
            }
            echo json_encode(['success' => true]);
            exit;
        }

        header('Location: categorias.php');
        exit;
    }
    if ($action === 'delete' && isset($_POST['id'])) {
        $id = intval($_POST['id'] ?? 0);
        $resp = cpn_node_request(
            'POST',
            $base . '/api/productos/categorias/delete',
            $token,
            ['id' => $id]
        );

        if (cpn_is_ajax_request()) {
            header('Content-Type: application/json');
            if (!($resp['ok'] ?? false)) {
                http_response_code(($resp['_http'] ?? 500) ?: 500);
                echo json_encode(['error' => ($resp['error']['message'] ?? 'Error eliminando categoría')]);
                exit;
            }
            echo json_encode(['success' => true]);
            exit;
        }

        header('Location: categorias.php');
        exit;
    }
}

// GET: obtengo lista de categorías + estados
$view = cpn_node_request('GET', $base . '/api/productos/categorias/view', $token);
if (!($view['ok'] ?? false)) {
    $msg = $view['error']['message'] ?? 'No se pudo cargar categorías.';
    http_response_code(($view['_http'] ?? 500) ?: 500);
    exit($msg);
}

$categorias = $view['data']['categorias'] ?? [];
$estados = $view['data']['estados'] ?? [];
?>
<?php 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>
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Árbol de Categorías</h1>
    <button class="btn btn-primary" data-toggle="modal" data-target="#modalNew">
        <i class="fas fa-plus"></i> Nueva categoría
    </button>
</div>

<div class="card shadow mb-4">
    <div class="card-body p-0">
        <table class="table table-hover mb-0 tree">
            <thead class="thead-light">
                <tr>
                    <th>ID</th>
                    <th>Categoría completa</th>
                    <th>Orden</th>
                    <th>Etiqueta</th>
                    <th>Estado</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($categorias as $row):
                    $nivel = substr_count((string)($row['nombre'] ?? ''), '>');
                ?>
                    <tr class="level-<?= $nivel ?>">
                        <td><?= $row['id'] ?></td>
                        <td><?= htmlspecialchars($row['nombre']) ?></td>
                        <td><?= $row['noOrden'] ?></td>
                        <td><?= $row['esEtiqueta'] ? 'Sí' : 'No' ?></td>
                        <td><?= htmlspecialchars($row['estadoNombre']) ?></td>
                        <td>
                            <form method="POST" class="d-inline frm-delete">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</div>
</div>

<!-- Modal: nueva categoría -->
<div class="modal fade" id="modalNew" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" class="modal-content" id="frmNewCategoria">
            <input type="hidden" name="action" value="insert">
            <div class="modal-header">
                <h5 class="modal-title">Crear nueva categoría</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>Categoría completa</label>
                    <input name="nombre" class="form-control"
                        placeholder="Ej: Hogar>Bebidas>Vasos" required>
                </div>
                <div class="form-row">
                    <div class="form-group col">
                        <label>No. Orden</label>
                        <input name="noOrden" type="number" min="1"
                            class="form-control" value="1" required>
                    </div>
                    <div class="form-group col d-flex align-items-center">
                        <div class="form-check mt-2">
                            <input name="esEtiqueta" type="checkbox" class="form-check-input" id="chkEtiqueta">
                            <label class="form-check-label" for="chkEtiqueta">Es etiqueta</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Estado</label>
                    <select name="idEstado" class="form-control" id="selEstado" required>
                        <?php foreach ($estados as $e): ?>
                            <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['nombre']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-primary">Guardar</button>
            </div>
        </form>
    </div>
</div>

<script>
    $(function() {
        try {
            $('#selEstado').select2({
                width: '100%'
            });
        } catch (e) {
            // continuar sin romper
        }

        $('#frmNewCategoria').on('submit', function(e) {
            e.preventDefault();
            $.ajax({
                url: 'categorias.php',
                method: 'POST',
                data: $(this).serialize(),
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            }).done(function(resp) {
                if (resp && resp.error) {
                    alert(resp.error);
                    return;
                }
                location.reload();
            }).fail(function(xhr) {
                alert('Error al guardar');
            });
        });

        $('.frm-delete').on('submit', function(e) {
            e.preventDefault();
            if (!confirm('¿Eliminar esta categoría?')) return;
            $.ajax({
                url: 'categorias.php',
                method: 'POST',
                data: $(this).serialize(),
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            }).done(function(resp) {
                if (resp && resp.error) {
                    alert(resp.error);
                    return;
                }
                location.reload();
            }).fail(function(xhr) {
                alert('Error al eliminar');
            });
        });
    });
</script>

<?php include '../templates/footer.php'; ?>