<?php
// variacionesproducto.php
include '../includes/session_control.php';
require_once '../cotizaciones/api/_node.php';

function htmlOptionsFromList($items, $selected)
{
    $html = '';
    if (!is_array($items)) return $html;
    foreach ($items as $r) {
        $id = (int)($r['id'] ?? 0);
        $label = (string)($r['nombre'] ?? '');
        if (!$id) continue;
        $sel = $id === (int)$selected ? 'selected' : '';
        $html .= "<option value=\"" . htmlspecialchars((string)$id) . "\" {$sel}>"
            . htmlspecialchars($label)
            . "</option>";
    }
    return $html;
}

$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();

$rMeta = cpn_node_request('GET', $base . '/api/productos/meta/variaciones', $token, null);
$meta = !empty($rMeta['ok']) ? ($rMeta['data'] ?? []) : [];

$r = cpn_node_request('GET', $base . '/api/productos/' . urlencode((string)$idProducto) . '/variaciones', $token, null);
if (empty($r['ok'])) {
    echo "No se pudieron cargar las variaciones.";
    exit;
}

$hasOferta = (bool)($r['data']['hasOferta'] ?? false);
$rows = $r['data']['rows'] ?? [];

// 4) Colores de estado
$estadoColors = [
    1 => '#28a745',
    2 => '#6c757d',
    3 => '#dc3545',
    4 => '#6c757d',
];
?>
<div class="table-responsive table-variaciones">
    <table class="table table-bordered table-sm">
        <thead>
            <tr>
                <th class="col-cpn" rowspan="2">CPN</th>
                <th rowspan="2">V</th>
                <th class="col-refprov" rowspan="2">Ref Prov</th>
                <th rowspan="2">Img</th>
                <th class="col-color" rowspan="2">Color</th>
                <th rowspan="2">Estado</th>
                <th rowspan="2">Tipo</th>
                <th class="conf-inv" rowspan="2">Conf Inv</th>
                <th class="col-inv" rowspan="2">Stock</th>

                <th class="header-precio-lista" colspan="4">Precio Lista (Antes de IVA)</th>

                <?php if ($hasOferta): ?>
                    <th class="header-antes-iva-first-row" colspan="2">Precio de Venta al Público</th>
                <?php else: ?>
                    <th class="header-antes-iva-first-row" rowspan="2">Precio de Venta al Público</th>
                <?php endif; ?>

                <th class="fecha-act" rowspan="2">Act.</th>
                <th rowspan="2">A</th>
                <th rowspan="2">Eliminar</th>
            </tr>
            <tr>
                <th class="sub-precio-lista">$ Lista</th>
                <th class="sub-precio-prov">% Prov</th>
                <th class="sub-precio-desc">Desc</th>
                <th class="sub-precio-lista">$ Neto</th>

                <?php if ($hasOferta): ?>
                    <th class="sub-iva">$ Normal</th>

                    <th class="sub-iva">$ Oferta</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($rows as $v):
                // formateos
                $fmtNum        = fn($x) => '$' . number_format($x, 0, ',', '.');
                $fmtInt        = fn($x) => (int)$x;
                $fmtPercLine   = fn($x) => number_format($x * 100, 0) . '%';
                $fmtPercPlain  = fn($x) => number_format($x, 0) . '%';
                $fecha         = date('d-M-y g:i a', strtotime($v['fechaActualizacion']));
                $bgEstado      = $estadoColors[$v['idEstado']] ?? '';
                $bgVinc        = $v['vinculado'] ? '#28a745' : '#dc3545';
                $bgA           = $v['wp_id']      ? '#28a745' : '#dc3545';
            ?>
                <tr data-id="<?= $v['id'] ?>">
                    <td class="col-cpn" rowspan="2">
                        <input type="text" class="form-control form-control-sm live-field text-center"
                            data-id="<?= $v['id'] ?>" data-field="referenciaCPN"
                            value="<?= htmlspecialchars($v['referenciaCPN']) ?>">
                    </td>
                    <td rowspan="2" style="width:20px; padding:0; background:<?= $bgVinc ?>"></td>
                    <td class="col-refprov" rowspan="2">
                        <input type="text" class="form-control form-control-sm live-field text-center"
                            data-id="<?= $v['id'] ?>" data-field="referenciaProveedor"
                            value="<?= htmlspecialchars($v['referenciaProveedor']) ?>">
                    </td>
                    <td rowspan="2">
                        <?php if ($v['linkImagen']):
                            $url = str_replace('J:/', 'https://sistema.compranet.com.co/', $v['linkImagen']);
                        ?>
                            <img src="<?= htmlspecialchars($url) ?>" style="height:40px; max-width:80px;">
                        <?php endif; ?>
                    </td>
                    <td class="col-color" rowspan="2">
                        <input type="text" class="form-control form-control-sm live-field text-center"
                            data-id="<?= $v['id'] ?>" data-field="txtColor"
                            value="<?= htmlspecialchars($v['txtColor']) ?>">
                    </td>
                    <td rowspan="2">
                        <select class="form-control form-control-sm live-field text-center"
                            data-id="<?= $v['id'] ?>" data-field="idEstado"
                            style="background:<?= $bgEstado ?>; color:#fff;">
                            <?= htmlOptionsFromList($meta['estados'] ?? [], $v['idEstado']) ?>
                        </select>
                    </td>
                    <td rowspan="2">
                        <select class="form-control form-control-sm live-field text-center"
                            data-id="<?= $v['id'] ?>" data-field="idLinea">
                            <?= htmlOptionsFromList($meta['lineas'] ?? [], $v['idLinea']) ?>
                        </select>
                    </td>
                    <td rowspan="2">
                        <div class="mb-1">
                            <select class="form-control form-control-sm live-field text-center"
                                data-id="<?= $v['id'] ?>" data-field="idTipoMinInventario">
                                <?= htmlOptionsFromList($meta['tiposMinInventario'] ?? [], $v['idTipoMinInventario']) ?>
                            </select>
                        </div>
                        <div class="form-row no-gutters">
                            <div class="col px-1">
                                <input type="number" class="form-control form-control-sm live-field text-center"
                                    data-id="<?= $v['id'] ?>" data-field="minVenta"
                                    value="<?= $v['minVenta'] ?>">
                            </div>
                            <div class="col px-1">
                                <input type="number" class="form-control form-control-sm live-field text-center"
                                    data-id="<?= $v['id'] ?>" data-field="multiploVenta"
                                    value="<?= $v['multiploVenta'] ?>">
                            </div>
                        </div>
                    </td>

                    <td class="col-inv text-right <?= $v['inventario'] > 0 ? 'bg-inv-verde' : 'bg-inv-rojo' ?>" rowspan="2" style="max-width:80px;">
                        <input type="text" class="form-control form-control-sm live-field text-right"
                            data-id="<?= $v['id'] ?>" data-field="inventario"
                            value="<?= $v['inventario'] === null || (int)$v['inventario'] === 0 ? '-' : $fmtInt($v['inventario']) ?>">
                    </td>

                    <!-- Precio Lista -->
                    <?php if ((float)$v['precioListaProveedor'] > 0): ?>
                        <td rowspan="2">
                            <input type="text" class="form-control form-control-sm live-field text-right bg-precio-lista"
                                data-id="<?= $v['id'] ?>" data-field="precioListaProveedor"
                                value="<?= $fmtNum($v['precioListaProveedor']) ?>"
                                onfocus="this.value=this.dataset.raw"
                                onblur="this.value='$' + (parseInt(this.value)||0).toLocaleString('es-CO')"
                                data-raw="<?= $v['precioListaProveedor'] ?>">
                        </td>
                    <?php else: ?>
                        <td rowspan="2" class="text-center">-</td>
                    <?php endif; ?>

                    <td rowspan="2" class="text-right sub-precio-prov">
                        <?= ((float)$v['descuentoGeneral'] === 0 ? '-' : $fmtPercLine($v['descuentoGeneral'])) ?>
                    </td>

                    <td rowspan="2" class="text-right sub-precio-desc">
                        <?= ((float)$v['descuentoOutletProveedor'] === 0 ? '-' : $fmtPercPlain($v['descuentoOutletProveedor'])) ?>
                    </td>

                    <?php if ((float)$v['precioNetoProveedor'] > 0): ?>
                        <td rowspan="2">
                            <input type="text" class="form-control form-control-sm live-field text-right bg-precio-neto"
                                data-id="<?= $v['id'] ?>" data-field="precioNetoProveedor"
                                value="<?= $fmtNum($v['precioNetoProveedor']) ?>"
                                onfocus="this.value=this.dataset.raw"
                                onblur="this.value='$' + (parseInt(this.value)||0).toLocaleString('es-CO')"
                                data-raw="<?= $v['precioNetoProveedor'] ?>">
                        </td>
                    <?php else: ?>
                        <td rowspan="2" class="text-center">-</td>
                    <?php endif; ?>

                    <!-- Precio de Venta al Público antes IVA -->
                    <?php if ((float)$v['PVPantesImpuestos'] > 0): ?>
                        <td>
                            <input type="text" class="form-control form-control-sm live-field text-right bg-antes-iva"
                                data-id="<?= $v['id'] ?>" data-field="PVPantesImpuestos"
                                value="<?= $fmtNum($v['PVPantesImpuestos']) ?>"
                                onfocus="this.value=this.dataset.raw"
                                onblur="this.value='$' + (parseInt(this.value)||0).toLocaleString('es-CO')"
                                data-raw="<?= $v['PVPantesImpuestos'] ?>">
                        </td>
                    <?php else: ?>
                        <td class="text-center">-</td>
                    <?php endif; ?>

                    <?php if ($hasOferta): ?>
                        <?php if ((float)$v['PVPreducidoantesImpuestos'] > 0): ?>
                            <td>
                                <input type="text" class="form-control form-control-sm live-field text-right bg-antes-iva"
                                    data-id="<?= $v['id'] ?>" data-field="PVPreducidoantesImpuestos"
                                    value="<?= $fmtNum($v['PVPreducidoantesImpuestos']) ?>"
                                    onfocus="this.value=this.dataset.raw"
                                    onblur="this.value='$' + (parseInt(this.value)||0).toLocaleString('es-CO')"
                                    data-raw="<?= $v['PVPreducidoantesImpuestos'] ?>">
                            </td>
                        <?php else: ?>
                            <td class="text-center">-</td>
                        <?php endif; ?>
                    <?php endif; ?>

                    <td class="fecha-act" rowspan="2"><small><?= $fecha ?></small></td>
                    <td rowspan="2" style="width:20px; padding:0; background:<?= $bgA ?>"></td>
                    <td rowspan="2">
                        <button class="btn btn-sm btn-danger delete-variant" data-id="<?= $v['id'] ?>">×</button>
                    </td>
                </tr>
                <tr>
                    <!-- Precio de Venta al Público después IVA -->
                    <?php if ((float)$v['PVP'] > 0): ?>
                        <td>
                            <input type="text" class="form-control form-control-sm live-field text-right bg-despues-iva"
                                data-id="<?= $v['id'] ?>" data-field="PVP"
                                value="<?= $fmtNum($v['PVP']) ?>"
                                onfocus="this.value=this.dataset.raw"
                                onblur="this.value='$' + (parseInt(this.value)||0).toLocaleString('es-CO')"
                                data-raw="<?= $v['PVP'] ?>">
                        </td>
                    <?php else: ?>
                        <td class="text-center">-</td>
                    <?php endif; ?>

                    <?php if ($hasOferta): ?>
                        <?php if ((float)$v['PVPReducido'] > 0): ?>
                            <td>
                                <input type="text" class="form-control form-control-sm live-field text-right bg-despues-iva"
                                    data-id="<?= $v['id'] ?>" data-field="PVPReducido"
                                    value="<?= $fmtNum($v['PVPReducido']) ?>"
                                    onfocus="this.value=this.dataset.raw"
                                    onblur="this.value='$' + (parseInt(this.value)||0).toLocaleString('es-CO')"
                                    data-raw="<?= $v['PVPReducido'] ?>">
                            </td>
                        <?php else: ?>
                            <td class="text-center">-</td>
                        <?php endif; ?>
                    <?php endif; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>