<?php
// categoriasproducto.php
include '../includes/session_control.php';
require_once '../cotizaciones/api/_node.php';

$idProducto = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$idProducto) {
    echo "ID de producto inválido.";
    exit;
}

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

// Manejo AJAX: agregar / eliminar
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $idCategoria = intval($_POST['idCategoria'] ?? 0);

    if ($action === 'add' && $idCategoria) {
        cpn_node_request(
            'POST',
            $base . '/api/productos/' . urlencode((string)$idProducto) . '/categorias/add',
            $token,
            ['idCategoria' => $idCategoria]
        );
    }

    if ($action === 'delete' && $idCategoria) {
        cpn_node_request(
            'POST',
            $base . '/api/productos/' . urlencode((string)$idProducto) . '/categorias/delete',
            $token,
            ['idCategoria' => $idCategoria]
        );
    }

    echo json_encode(['success' => true]);
    exit;
}

$r = cpn_node_request('GET', $base . '/api/productos/' . urlencode((string)$idProducto) . '/categorias', $token, null);
$all = (!empty($r['ok']) && isset($r['data']['all']) && is_array($r['data']['all'])) ? $r['data']['all'] : [];
$selected = (!empty($r['ok']) && isset($r['data']['selected']) && is_array($r['data']['selected'])) ? $r['data']['selected'] : [];
?>

<div id="categorias-contenedor">
    <div class="form-inline mb-2">
        <select id="newCategoria" class="form-control mr-2" style="width:100%">
            <?php
            foreach ($all as $r) {
                $rid = (int)($r['id'] ?? 0);
                $rnom = (string)($r['nombre'] ?? '');
                if (!$rid) continue;
                echo "<option value=\"" . htmlspecialchars((string)$rid) . "\">" . htmlspecialchars($rnom) . "</option>";
            }
            ?>
        </select>
        <button id="addCategoria" class="btn btn-primary">Agregar</button>
    </div>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Nombre</th>
                <th>Orden</th>
                <th>Eliminar</th>
            </tr>
        </thead>
        <tbody>
            <?php
            foreach ($selected as $r): ?>
                <tr data-idcategoria="<?= $r['id'] ?>">
                    <td><?= htmlspecialchars($r['nombre']) ?></td>
                    <td><?= $r['noOrden'] ?></td>
                    <td><button class="btn btn-danger btn-sm delete-cat">&times;</button></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>