<?php
$products = is_array($products ?? null) ? $products : [];
$productVariantsMap = is_array($product_variants_map ?? null) ? $product_variants_map : [];
$movements = is_array($movements ?? null) ? $movements : [];
$transferHistory = is_array($transfer_history ?? null) ? $transfer_history : [];
$pendingAdjustments = is_array($pending_adjustments ?? null) ? $pending_adjustments : [];
$adjustmentHistory = is_array($adjustment_history ?? null) ? $adjustment_history : [];
$branches = is_array($branches ?? null) ? $branches : [];
$userBranchId = (int) ($user_branch_id ?? 0);
$lowStockProducts = is_array($low_stock_products ?? null) ? $low_stock_products : [];

$branchCount = count($branches);
$canTransfer = $branchCount >= 2;

$inventoryModalOld = trim((string) old('_inventory_modal', ''));
$transferContext = $inventoryModalOld === 'transfer';
$adjustmentContext = $inventoryModalOld === 'adjustment_request';

$transferSelectedProduct = (int) ($transferContext ? old('producto_id', 0) : 0);
$transferSelectedVariant = (int) ($transferContext ? old('variante_id', 0) : 0);
$transferOrigin = (int) ($transferContext ? old('sucursal_origen_id', $userBranchId > 0 ? $userBranchId : 0) : ($userBranchId > 0 ? $userBranchId : 0));
$transferDestination = (int) ($transferContext ? old('sucursal_destino_id', 0) : 0);
$transferQuantity = (string) ($transferContext ? old('cantidad', '1') : '1');
$transferObservation = (string) ($transferContext ? old('observacion', '') : '');

$adjustmentSelectedBranch = (int) ($adjustmentContext ? old('sucursal_id', $userBranchId > 0 ? $userBranchId : 0) : ($userBranchId > 0 ? $userBranchId : 0));
$adjustmentSelectedProduct = (int) ($adjustmentContext ? old('producto_id', 0) : 0);
$adjustmentSelectedVariant = (int) ($adjustmentContext ? old('variante_id', 0) : 0);
$adjustmentNewStock = (string) ($adjustmentContext ? old('stock_nuevo', '0') : '0');
$adjustmentReason = (string) ($adjustmentContext ? old('motivo', '') : '');

$autoOpenModalId = '';
if ($inventoryModalOld === 'transfer') {
    $autoOpenModalId = 'inventoryTransferModal';
} elseif ($inventoryModalOld === 'adjustment_request') {
    $autoOpenModalId = 'inventoryAdjustmentRequestModal';
}
?>

<div class="row g-3 mb-3">
    <div class="col-md-4">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Productos en inventario</span>
                <h2 class="h4 mb-0"><?= e((string) count($products)) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div
            class="card metric-card border-0 shadow-sm vx-clickable-card"
            role="button"
            tabindex="0"
            data-bs-toggle="modal"
            data-bs-target="#inventoryLowStockModal"
            aria-label="Ver productos con stock bajo"
        >
            <div class="card-body">
                <span class="metric-label">Stock bajo</span>
                <h2 class="h4 mb-0 text-danger"><?= e((string) $low_stock) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Valor inventario (costo)</span>
                <h2 class="h4 mb-0"><?= e(money($stock_value)) ?></h2>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
            <h1 class="h6 mb-0">Gestión de inventario por módulos</h1>
            <small class="text-muted">Cada opción abre un modal independiente.</small>
        </div>
        <div class="row g-3">
            <div class="col-md-6 col-xl-4">
                <div class="card border h-100">
                    <div class="card-body d-flex flex-column">
                        <h2 class="h6">Traslado entre sucursales</h2>
                        <p class="text-muted small mb-3">Mueve inventario entre sedes con referencia automática.</p>
                        <div class="mt-auto d-flex justify-content-between align-items-center">
                            <span class="badge text-bg-light border"><?= e((string) $branchCount) ?> sedes</span>
                            <button class="btn btn-sm btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#inventoryTransferModal">Abrir</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-xl-4">
                <div class="card border h-100">
                    <div class="card-body d-flex flex-column">
                        <h2 class="h6">Solicitud de ajuste</h2>
                        <p class="text-muted small mb-3">Solicita cambios de stock por sucursal con motivo obligatorio.</p>
                        <div class="mt-auto d-flex justify-content-between align-items-center">
                            <span class="badge text-bg-light border"><?= e((string) count($pendingAdjustments)) ?> pendientes</span>
                            <button class="btn btn-sm btn-warning" type="button" data-bs-toggle="modal" data-bs-target="#inventoryAdjustmentRequestModal">Abrir</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-xl-4">
                <div class="card border h-100">
                    <div class="card-body d-flex flex-column">
                        <h2 class="h6">Movimientos recientes</h2>
                        <p class="text-muted small mb-3">Consulta kardex reciente de entradas, salidas y ajustes.</p>
                        <div class="mt-auto d-flex justify-content-between align-items-center">
                            <span class="badge text-bg-light border"><?= e((string) count($movements)) ?> registros</span>
                            <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#inventoryMovementsModal">Ver</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-xl-4">
                <div class="card border h-100">
                    <div class="card-body d-flex flex-column">
                        <h2 class="h6">Historial de traslados</h2>
                        <p class="text-muted small mb-3">Revisa traslados entre origen y destino por fecha y referencia.</p>
                        <div class="mt-auto d-flex justify-content-between align-items-center">
                            <span class="badge text-bg-light border"><?= e((string) count($transferHistory)) ?> traslados</span>
                            <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#inventoryTransferHistoryModal">Ver</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-xl-4">
                <div class="card border h-100">
                    <div class="card-body d-flex flex-column">
                        <h2 class="h6">Ajustes pendientes</h2>
                        <p class="text-muted small mb-3">Aprueba o rechaza solicitudes pendientes con observación.</p>
                        <div class="mt-auto d-flex justify-content-between align-items-center">
                            <span class="badge text-bg-light border"><?= e((string) count($pendingAdjustments)) ?> por gestionar</span>
                            <button class="btn btn-sm btn-outline-warning" type="button" data-bs-toggle="modal" data-bs-target="#inventoryPendingAdjustmentsModal">Gestionar</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-xl-4">
                <div class="card border h-100">
                    <div class="card-body d-flex flex-column">
                        <h2 class="h6">Historial de ajustes</h2>
                        <p class="text-muted small mb-3">Consulta trazabilidad completa de ajustes aprobados o rechazados.</p>
                        <div class="mt-auto d-flex justify-content-between align-items-center">
                            <span class="badge text-bg-light border"><?= e((string) count($adjustmentHistory)) ?> registros</span>
                            <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#inventoryAdjustmentHistoryModal">Ver</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h2 class="h6 mb-3">Stock actual por producto</h2>
        <div class="table-responsive">
            <table class="table table-striped table-sm">
                <thead>
                <tr>
                    <th>Producto</th>
                    <th>Stock</th>
                    <th>Mínimo</th>
                    <th>Costo</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($products as $product): ?>
                    <?php $isLow = (float) ($product['stock_actual'] ?? 0) <= (float) ($product['stock_minimo'] ?? 0); ?>
                    <tr>
                        <td><?= e((string) ($product['nombre'] ?? '')) ?></td>
                        <td class="<?= $isLow ? 'text-danger fw-semibold' : '' ?>">
                            <?= e((string) ($product['stock_actual'] ?? '0')) ?>
                        </td>
                        <td><?= e((string) ($product['stock_minimo'] ?? '0')) ?></td>
                        <td><?= e(money((float) ($product['precio_compra'] ?? 0))) ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($products)): ?>
                    <tr>
                        <td colspan="4" class="text-center text-muted">No hay productos registrados.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="inventoryLowStockModal" tabindex="-1" aria-labelledby="inventoryLowStockModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="inventoryLowStockModalLabel">Productos con stock bajo</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped table-sm align-middle">
                        <thead>
                        <tr>
                            <th>Producto</th>
                            <th>SKU</th>
                            <th class="text-end">Stock actual</th>
                            <th class="text-end">Stock mínimo</th>
                            <th class="text-end">Faltante</th>
                            <th class="text-end">Costo</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($lowStockProducts as $product): ?>
                            <tr>
                                <td>
                                    <?= e((string) ($product['nombre'] ?? '')) ?>
                                    <small class="d-block text-muted">ID: <?= e((string) ($product['id'] ?? 0)) ?></small>
                                </td>
                                <td><?= e((string) ($product['sku'] !== '' ? $product['sku'] : '-')) ?></td>
                                <td class="text-end text-danger fw-semibold"><?= e(number_format((float) ($product['stock_actual'] ?? 0), 2, ',', '.')) ?></td>
                                <td class="text-end"><?= e(number_format((float) ($product['stock_minimo'] ?? 0), 2, ',', '.')) ?></td>
                                <td class="text-end fw-semibold"><?= e(number_format((float) ($product['faltante'] ?? 0), 2, ',', '.')) ?></td>
                                <td class="text-end"><?= e(money((float) ($product['precio_compra'] ?? 0))) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if ($lowStockProducts === []): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-3">No hay productos con stock bajo en este momento.</td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="inventoryTransferModal" tabindex="-1" aria-labelledby="inventoryTransferModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="inventoryTransferModalLabel">Traslado de inventario entre sucursales</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <?php if (!$canTransfer): ?>
                    <div class="alert alert-warning mb-0">
                        Debes tener al menos dos sucursales activas para realizar traslados.
                    </div>
                <?php else: ?>
                    <form action="<?= e(url('inventario/traslados')) ?>" method="post">
                        <?= csrf_field() ?>
                        <input type="hidden" name="_inventory_modal" value="transfer">
                        <div class="mb-2">
                            <label class="form-label">Producto</label>
                            <select class="form-select inventory-product-select" name="producto_id" required>
                                <option value="">Seleccione...</option>
                                <?php foreach ($products as $product): ?>
                                    <?php
                                    $productId = (int) ($product['id'] ?? 0);
                                    $productVariants = is_array($productVariantsMap[$productId] ?? null) ? $productVariantsMap[$productId] : [];
                                    $productVariants = array_values(array_filter($productVariants, static function (array $variant): bool {
                                        return (int) ($variant['activo'] ?? 0) === 1;
                                    }));
                                    $variantsPayload = array_map(static function (array $variant): array {
                                        $variantStockRaw = $variant['cantidad'] ?? null;
                                        $variantStock = null;
                                        if ($variantStockRaw !== null && $variantStockRaw !== '') {
                                            $variantStock = (int) $variantStockRaw;
                                        }

                                        return [
                                            'id' => (int) ($variant['id'] ?? 0),
                                            'nombre' => (string) ($variant['nombre'] ?? ''),
                                            'cantidad' => $variantStock,
                                        ];
                                    }, $productVariants);
                                    $variantsJson = json_encode($variantsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                    if (!is_string($variantsJson)) {
                                        $variantsJson = '[]';
                                    }
                                    ?>
                                    <option
                                        value="<?= e((string) $productId) ?>"
                                        data-has-variants="<?= count($variantsPayload) > 0 ? '1' : '0' ?>"
                                        data-variants="<?= e($variantsJson) ?>"
                                        <?= $transferSelectedProduct === $productId ? 'selected' : '' ?>
                                    >
                                        <?= e((string) $product['nombre']) ?> (Stock global: <?= e((string) ($product['stock_actual'] ?? 0)) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-2">
                            <label class="form-label">Variación</label>
                            <select
                                class="form-select inventory-variant-select"
                                name="variante_id"
                                data-selected-variant="<?= e((string) $transferSelectedVariant) ?>"
                                disabled
                            >
                                <option value="">Sin variación</option>
                            </select>
                            <small class="text-muted d-block mt-1">Si el producto tiene variaciones activas, la variación es obligatoria.</small>
                        </div>
                        <div class="row g-2">
                            <div class="col-md-6">
                                <label class="form-label">Sucursal origen</label>
                                <select class="form-select" name="sucursal_origen_id" required>
                                    <option value="">Seleccione...</option>
                                    <?php foreach ($branches as $branch): ?>
                                        <option value="<?= e((string) $branch['id']) ?>" <?= $transferOrigin === (int) $branch['id'] ? 'selected' : '' ?>>
                                            <?= e((string) $branch['nombre']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Sucursal destino</label>
                                <select class="form-select" name="sucursal_destino_id" required>
                                    <option value="">Seleccione...</option>
                                    <?php foreach ($branches as $branch): ?>
                                        <option value="<?= e((string) $branch['id']) ?>" <?= $transferDestination === (int) $branch['id'] ? 'selected' : '' ?>>
                                            <?= e((string) $branch['nombre']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="mb-2 mt-2">
                            <label class="form-label">Cantidad</label>
                            <input type="number" step="0.01" min="0.01" class="form-control" name="cantidad" value="<?= e($transferQuantity) ?>" required>
                        </div>
                        <div class="mb-0">
                            <label class="form-label">Observación</label>
                            <textarea class="form-control" name="observacion" rows="2" placeholder="Motivo del traslado (opcional)"><?= e($transferObservation) ?></textarea>
                        </div>
                        <div class="d-flex justify-content-end mt-3">
                            <button class="btn btn-primary" type="submit">Registrar traslado</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="inventoryAdjustmentRequestModal" tabindex="-1" aria-labelledby="inventoryAdjustmentRequestModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="inventoryAdjustmentRequestModalLabel">Solicitud de ajuste por sucursal</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <form action="<?= e(url('inventario/ajustes')) ?>" method="post">
                    <?= csrf_field() ?>
                    <input type="hidden" name="_inventory_modal" value="adjustment_request">
                    <div class="mb-2">
                        <label class="form-label">Sucursal</label>
                        <select class="form-select" name="sucursal_id" required>
                            <option value="">Seleccione...</option>
                            <?php foreach ($branches as $branch): ?>
                                <option value="<?= e((string) $branch['id']) ?>" <?= $adjustmentSelectedBranch === (int) $branch['id'] ? 'selected' : '' ?>>
                                    <?= e((string) $branch['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Producto</label>
                        <select class="form-select inventory-product-select" name="producto_id" required>
                            <option value="">Seleccione...</option>
                            <?php foreach ($products as $product): ?>
                                <?php
                                $productId = (int) ($product['id'] ?? 0);
                                $productVariants = is_array($productVariantsMap[$productId] ?? null) ? $productVariantsMap[$productId] : [];
                                $productVariants = array_values(array_filter($productVariants, static function (array $variant): bool {
                                    return (int) ($variant['activo'] ?? 0) === 1;
                                }));
                                $variantsPayload = array_map(static function (array $variant): array {
                                    $variantStockRaw = $variant['cantidad'] ?? null;
                                    $variantStock = null;
                                    if ($variantStockRaw !== null && $variantStockRaw !== '') {
                                        $variantStock = (int) $variantStockRaw;
                                    }

                                    return [
                                        'id' => (int) ($variant['id'] ?? 0),
                                        'nombre' => (string) ($variant['nombre'] ?? ''),
                                        'cantidad' => $variantStock,
                                    ];
                                }, $productVariants);
                                $variantsJson = json_encode($variantsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                if (!is_string($variantsJson)) {
                                    $variantsJson = '[]';
                                }
                                ?>
                                <option
                                    value="<?= e((string) $productId) ?>"
                                    data-has-variants="<?= count($variantsPayload) > 0 ? '1' : '0' ?>"
                                    data-variants="<?= e($variantsJson) ?>"
                                    <?= $adjustmentSelectedProduct === $productId ? 'selected' : '' ?>
                                >
                                    <?= e((string) $product['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Variación</label>
                        <select
                            class="form-select inventory-variant-select"
                            name="variante_id"
                            data-selected-variant="<?= e((string) $adjustmentSelectedVariant) ?>"
                            disabled
                        >
                            <option value="">Sin variación</option>
                        </select>
                        <small class="text-muted d-block mt-1">Si el producto tiene variaciones activas, la variación es obligatoria.</small>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Stock nuevo</label>
                        <input type="number" step="0.01" min="0" class="form-control" name="stock_nuevo" value="<?= e($adjustmentNewStock) ?>" required>
                    </div>
                    <div class="mb-0">
                        <label class="form-label">Motivo (obligatorio)</label>
                        <textarea class="form-control" name="motivo" rows="2" maxlength="255" required><?= e($adjustmentReason) ?></textarea>
                    </div>
                    <div class="d-flex justify-content-end mt-3">
                        <button class="btn btn-warning" type="submit">Enviar a aprobación</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="inventoryMovementsModal" tabindex="-1" aria-labelledby="inventoryMovementsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="inventoryMovementsModalLabel">Movimientos recientes (kardex)</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped table-sm align-middle">
                        <thead>
                        <tr>
                            <th>Fecha</th>
                            <th>Sucursal</th>
                            <th>Producto</th>
                            <th>Tipo</th>
                            <th>Referencia</th>
                            <th>Cantidad</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($movements as $movement): ?>
                            <?php
                            $type = (string) ($movement['tipo'] ?? '');
                            $typeClass = $type === 'entrada'
                                ? 'text-bg-success'
                                : ($type === 'salida' ? 'text-bg-warning' : 'text-bg-secondary');
                            ?>
                            <tr>
                                <td><?= e((string) ($movement['created_at'] ?? '')) ?></td>
                                <td><?= e((string) ($movement['sucursal'] ?? 'Sin sucursal')) ?></td>
                                <td>
                                    <?= e((string) ($movement['producto'] ?? '')) ?>
                                    <?php if (!empty($movement['variante_nombre'])): ?>
                                        <small class="d-block text-muted">Variante: <?= e((string) $movement['variante_nombre']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><span class="badge <?= $typeClass ?>"><?= e($type) ?></span></td>
                                <td><?= e((string) ($movement['referencia'] ?? '')) ?></td>
                                <td><?= e((string) ($movement['cantidad'] ?? 0)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($movements)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted">Sin movimientos registrados.</td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="inventoryTransferHistoryModal" tabindex="-1" aria-labelledby="inventoryTransferHistoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="inventoryTransferHistoryModalLabel">Historial de traslados</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped table-sm align-middle">
                        <thead>
                        <tr>
                            <th>Fecha</th>
                            <th>Referencia</th>
                            <th>Producto</th>
                            <th>Origen</th>
                            <th>Destino</th>
                            <th>Cantidad</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($transferHistory as $transfer): ?>
                            <tr>
                                <td><?= e((string) ($transfer['created_at'] ?? '')) ?></td>
                                <td><?= e((string) ($transfer['referencia'] ?? '')) ?></td>
                                <td>
                                    <?= e((string) ($transfer['producto'] ?? '')) ?>
                                    <?php if (!empty($transfer['variante_nombre'])): ?>
                                        <small class="d-block text-muted">Variante: <?= e((string) $transfer['variante_nombre']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><?= e((string) ($transfer['sucursal_origen'] ?? 'Sin sucursal')) ?></td>
                                <td><?= e((string) ($transfer['sucursal_destino'] ?? 'Sin sucursal')) ?></td>
                                <td><?= e((string) ($transfer['cantidad'] ?? 0)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($transferHistory)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted">Aún no hay traslados registrados.</td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="inventoryPendingAdjustmentsModal" tabindex="-1" aria-labelledby="inventoryPendingAdjustmentsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="inventoryPendingAdjustmentsModalLabel">Ajustes pendientes (requieren aprobación)</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped table-sm align-middle">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>Sucursal</th>
                            <th>Producto</th>
                            <th>Anterior</th>
                            <th>Nuevo</th>
                            <th>Motivo</th>
                            <th>Acción</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($pendingAdjustments as $adjustment): ?>
                            <tr>
                                <td><?= e((string) ($adjustment['id'] ?? '')) ?></td>
                                <td><?= e((string) ($adjustment['sucursal'] ?? 'Sin sucursal')) ?></td>
                                <td>
                                    <?= e((string) ($adjustment['producto'] ?? '')) ?>
                                    <?php if (!empty($adjustment['variante_nombre'])): ?>
                                        <small class="d-block text-muted">Variante: <?= e((string) $adjustment['variante_nombre']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><?= e((string) ($adjustment['stock_anterior'] ?? 0)) ?></td>
                                <td><?= e((string) ($adjustment['stock_nuevo'] ?? 0)) ?></td>
                                <td><?= e((string) ($adjustment['motivo'] ?? '')) ?></td>
                                <td style="min-width: 220px;">
                                    <form action="<?= e(url('inventario/ajustes/' . (int) $adjustment['id'] . '/aprobar')) ?>" method="post" class="mb-1">
                                        <?= csrf_field() ?>
                                        <input type="text" class="form-control form-control-sm mb-1" name="observacion_aprobacion" placeholder="Observación (opcional)">
                                        <button class="btn btn-sm btn-outline-success w-100" type="submit">Aprobar</button>
                                    </form>
                                    <form action="<?= e(url('inventario/ajustes/' . (int) $adjustment['id'] . '/rechazar')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <input type="text" class="form-control form-control-sm mb-1" name="observacion_rechazo" placeholder="Motivo rechazo" required>
                                        <button class="btn btn-sm btn-outline-danger w-100" type="submit">Rechazar</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($pendingAdjustments)): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted">No hay solicitudes pendientes.</td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="inventoryAdjustmentHistoryModal" tabindex="-1" aria-labelledby="inventoryAdjustmentHistoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="inventoryAdjustmentHistoryModalLabel">Historial de ajustes</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped table-sm align-middle">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>Fecha solicitud</th>
                            <th>Sucursal</th>
                            <th>Producto</th>
                            <th>Tipo</th>
                            <th>Anterior</th>
                            <th>Nuevo</th>
                            <th>Estado</th>
                            <th>Solicitó</th>
                            <th>Aprobó</th>
                            <th>Obs aprobación</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($adjustmentHistory as $row): ?>
                            <?php
                            $status = (string) ($row['estado'] ?? 'pendiente');
                            $statusClass = $status === 'aprobado'
                                ? 'text-bg-success'
                                : ($status === 'rechazado' ? 'text-bg-danger' : 'text-bg-warning');
                            ?>
                            <tr>
                                <td><?= e((string) ($row['id'] ?? '')) ?></td>
                                <td><?= e((string) ($row['created_at'] ?? '')) ?></td>
                                <td><?= e((string) ($row['sucursal'] ?? 'Sin sucursal')) ?></td>
                                <td>
                                    <?= e((string) ($row['producto'] ?? '')) ?>
                                    <?php if (!empty($row['variante_nombre'])): ?>
                                        <small class="d-block text-muted">Variante: <?= e((string) $row['variante_nombre']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><?= e((string) ($row['tipo_ajuste'] ?? 'correccion')) ?></td>
                                <td><?= e((string) ($row['stock_anterior'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['stock_nuevo'] ?? 0)) ?></td>
                                <td><span class="badge <?= e($statusClass) ?>"><?= e($status) ?></span></td>
                                <td><?= e((string) ($row['solicitado_por'] ?? '-')) ?></td>
                                <td><?= e((string) ($row['aprobado_por'] ?? '-')) ?></td>
                                <td><?= e((string) ($row['observacion_aprobacion'] ?? '-')) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($adjustmentHistory)): ?>
                            <tr>
                                <td colspan="11" class="text-center text-muted">Sin ajustes registrados.</td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const parseVariants = (rawValue) => {
        let variants = [];
        try {
            const parsed = JSON.parse(String(rawValue || '[]'));
            variants = Array.isArray(parsed) ? parsed : [];
        } catch (error) {
            variants = [];
        }

        return variants
            .map((variant) => {
                const variantId = Number(variant && variant.id ? variant.id : 0);
                const variantName = String(variant && variant.nombre ? variant.nombre : '').trim();
                if (!Number.isFinite(variantId) || variantId <= 0 || variantName === '') {
                    return null;
                }

                const stockRaw = variant && variant.cantidad !== undefined ? Number(variant.cantidad) : null;
                const stock = Number.isFinite(stockRaw) ? Math.max(0, Math.floor(stockRaw)) : null;

                return {
                    id: String(variantId),
                    nombre: variantName,
                    cantidad: stock,
                };
            })
            .filter((variant) => variant !== null);
    };

    const syncVariantSelect = (productSelect, keepCurrentValue = true) => {
        if (!productSelect) {
            return;
        }

        const form = productSelect.closest('form');
        const variantSelect = form ? form.querySelector('.inventory-variant-select') : null;
        if (!variantSelect) {
            return;
        }

        const previousValue = keepCurrentValue
            ? String(variantSelect.dataset.selectedVariant || variantSelect.value || '')
            : '';
        const selectedOption = productSelect.options[productSelect.selectedIndex];
        const variants = parseVariants(selectedOption ? selectedOption.getAttribute('data-variants') || '[]' : '[]');
        const hasVariants = String(selectedOption ? selectedOption.getAttribute('data-has-variants') || '0' : '0') === '1'
            && variants.length > 0;

        variantSelect.innerHTML = '';
        const placeholder = document.createElement('option');
        placeholder.value = '';
        placeholder.textContent = hasVariants ? 'Selecciona variación...' : 'Sin variación';
        variantSelect.appendChild(placeholder);

        if (!hasVariants) {
            variantSelect.disabled = true;
            variantSelect.required = false;
            variantSelect.value = '';
            variantSelect.dataset.selectedVariant = '';
            return;
        }

        variants.forEach((variant) => {
            const option = document.createElement('option');
            option.value = variant.id;
            option.textContent = variant.cantidad === null
                ? variant.nombre
                : `${variant.nombre} (Stock: ${variant.cantidad})`;
            variantSelect.appendChild(option);
        });

        variantSelect.disabled = false;
        variantSelect.required = true;

        if (previousValue !== '') {
            const hasPrevious = Array.from(variantSelect.options).some((option) => option.value === previousValue);
            variantSelect.value = hasPrevious ? previousValue : '';
        } else {
            variantSelect.value = '';
        }
        variantSelect.dataset.selectedVariant = variantSelect.value;
    };

    document.querySelectorAll('.inventory-product-select').forEach((productSelect) => {
        syncVariantSelect(productSelect, true);
        productSelect.addEventListener('change', () => syncVariantSelect(productSelect, false));
    });

    document.querySelectorAll('.vx-clickable-card[data-bs-toggle="modal"]').forEach((card) => {
        card.addEventListener('keydown', (event) => {
            const key = event.key;
            if (key !== 'Enter' && key !== ' ') {
                return;
            }

            event.preventDefault();
            card.click();
        });
    });

    <?php if ($autoOpenModalId !== ''): ?>
    if (typeof bootstrap === 'undefined') {
        return;
    }
    const modalElement = document.getElementById('<?= e($autoOpenModalId) ?>');
    if (modalElement) {
        const modalInstance = new bootstrap.Modal(modalElement);
        modalInstance.show();
    }
    <?php endif; ?>
});
</script>
