<?php
// imagenesproducto.php
include '../includes/session_control.php';
require_once '../cotizaciones/api/_node.php';

// Obtener ID del producto (desde GET)
$idProducto = isset($_GET['id']) ? intval($_GET['id']) : 0;

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

// Handle AJAX actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Eliminar imagen principal
    if ($action === 'deletePrincipal' && isset($_POST['id'])) {
        $id = intval($_POST['id']);
        $r = cpn_node_request('DELETE', $base . '/api/productos/imagenes/principal/' . urlencode((string)$id), $token, null);
        echo json_encode(['success' => !empty($r['ok'])]);
        exit;
    }

    // Marcar como principal
    if ($action === 'setPrincipal' && isset($_POST['id'], $_POST['idProducto'])) {
        $id    = intval($_POST['id']);
        $idProd = intval($_POST['idProducto']);
        $r = cpn_node_request('POST', $base . '/api/productos/imagenes/principal/' . urlencode((string)$id) . '/set-principal', $token, [
            'idProducto' => $idProd,
        ]);
        echo json_encode(['success' => !empty($r['ok'])]);
        exit;
    }

    // Pegar imagen en variante (insert o update)
    if ($action === 'pasteVariant' && isset($_POST['idVariante'], $_POST['link'])) {
        $idVar = intval($_POST['idVariante']);
        $link  = $_POST['link'];
        $r = cpn_node_request('POST', $base . '/api/productos/imagenes/variante/' . urlencode((string)$idVar) . '/paste', $token, [
            'link' => (string)$link,
        ]);
        echo json_encode(['success' => !empty($r['ok'])]);
        exit;
    }

    // Eliminar imágenes de variante
    if ($action === 'deleteVariant' && isset($_POST['idVariante'])) {
        $idVar = intval($_POST['idVariante']);
        $r = cpn_node_request('DELETE', $base . '/api/productos/imagenes/variante/' . urlencode((string)$idVar), $token, null);
        echo json_encode(['success' => !empty($r['ok'])]);
        exit;
    }

    echo json_encode(['success' => false]);
    exit;
}

// Consultas para GET (Node)
$r = cpn_node_request('GET', $base . '/api/productos/' . urlencode((string)$idProducto) . '/imagenes', $token, null);
if (empty($r['ok'])) {
    echo '<div class="alert alert-danger">No se pudieron cargar las imágenes.</div>';
    exit;
}
$prim = $r['data']['principales'] ?? [];
$res2 = $r['data']['variantes'] ?? [];
?>
<div id="imagenes-contenedor">
    <div class="mb-3">
        <form id="uploadForm" class="d-flex align-items-center">
            <input type="text" id="urlImagen" class="form-control" placeholder="URL de la imagen">
            <button type="submit" class="btn btn-primary ml-2">Subir</button>
        </form>
    </div>

    <div class="row">
        <!-- Tabla imágenes principales -->
        <div class="col-md-6 bg-left p-2">
            <table class="table table-sm table-imagenes">
                <thead>
                    <tr>
                        <th>Imagen</th>
                        <th>Ruta</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($prim as $row):
                        $public = str_replace('J:/', 'https://sistema.compranet.com.co/', (string)($row['linkImagen'] ?? ''));
                    ?>
                        <tr data-id="<?= $row['id'] ?>">
                            <td><img src="<?= htmlspecialchars($public) ?>" class="img-thumb"></td>
                            <td class="small"><?= htmlspecialchars((string)($row['linkImagen'] ?? '')) ?></td>
                            <td>
                                <button class="btn btn-sm btn-danger btn-delete-principal"
                                    data-id="<?= $row['id'] ?>">Borrar</button>

                                <?php if (!$row['esPrincipal']): ?>
                                    <button class="btn btn-sm btn-secondary btn-principal"
                                        data-id="<?= $row['id'] ?>"
                                        data-producto="<?= $idProducto ?>">Convertir en Principal</button>
                                <?php endif; ?>

                                <button class="btn btn-sm btn-info btn-copy"
                                    data-link="<?= htmlspecialchars((string)($row['linkImagen'] ?? '')) ?>">Copiar ruta</button>
                            </td>

                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Tabla variantes -->
        <div class="col-md-6 bg-right p-2">
            <table class="table table-sm table-variants">
                <thead>
                    <tr>
                        <th>CPN</th>
                        <th>Ref Prov</th>
                        <th>Color</th>
                        <th>Imagen</th>
                        <th>Ruta</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($res2 as $v):
                        $pubVar = !empty($v['linkImagen'])
                            ? str_replace('J:/', 'https://sistema.compranet.com.co/', (string)$v['linkImagen'])
                            : '';
                    ?>
                        <tr data-id="<?= $v['idVar'] ?>">
                            <td><?= htmlspecialchars($v['referenciaCPN']) ?></td>
                            <td><?= htmlspecialchars($v['referenciaProveedor']) ?></td>
                            <td><?= htmlspecialchars($v['txtColor']) ?></td>
                            <td>
                                <?php if ($pubVar): ?>
                                    <img src="<?= htmlspecialchars($pubVar) ?>" class="img-thumb">
                                <?php endif; ?>
                            </td>
                            <td class="small"><?= htmlspecialchars((string)($v['linkImagen'] ?? '')) ?></td>
                            <td>
                                <button class="btn btn-sm btn-success btn-action btn-paste-variant" data-id="<?= $v['idVar'] ?>" data-link="<?= htmlspecialchars((string)($v['linkImagen'] ?? '')) ?>">Pegar Ruta</button>
                                <button class="btn btn-sm btn-danger btn-action btn-delete-variant" data-id="<?= $v['idVar'] ?>">Eliminar</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>