@extends('layouts.app')

@section('title', 'Inventario | Veltrix v2')
@section('page_title', 'Inventario')
@section('page_subtitle', 'Gestion operativa en tiempo real')
@section('page_icon', 'bx bxs-package')

@section('content')
    @php
        $stats = is_array($inventoryStats ?? null) ? $inventoryStats : [];
        $productsTotal = (int) ($stats['products_total'] ?? (method_exists($inventario, 'total') ? $inventario->total() : count($inventario)));
        $lowStockCount = (int) ($stats['low_stock'] ?? 0);
        $stockValue = (float) ($stats['stock_value'] ?? 0);
        $lowStockRows = $lowStockProducts instanceof \Illuminate\Support\Collection
            ? $lowStockProducts
            : collect($lowStockProducts ?? []);
        $branchesRows = $branches instanceof \Illuminate\Support\Collection
            ? $branches
            : collect($branches ?? []);
        $movementsRows = $movementsModal instanceof \Illuminate\Support\Collection
            ? $movementsModal
            : collect($movementsModal ?? []);
        $transferHistoryRows = $transferHistory instanceof \Illuminate\Support\Collection
            ? $transferHistory
            : collect($transferHistory ?? []);
        $pendingAdjustmentsRows = $pendingAdjustments instanceof \Illuminate\Support\Collection
            ? $pendingAdjustments
            : collect($pendingAdjustments ?? []);
        $adjustmentHistoryRows = $adjustmentHistory instanceof \Illuminate\Support\Collection
            ? $adjustmentHistory
            : collect($adjustmentHistory ?? []);
        $variantsByProduct = is_array($productVariantsMap ?? null) ? $productVariantsMap : [];
        $activeUserBranchId = (int) ($userBranchId ?? 0);
        $branchCount = $branchesRows->count();
        $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', $activeUserBranchId > 0 ? $activeUserBranchId : 0) : ($activeUserBranchId > 0 ? $activeUserBranchId : 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', $activeUserBranchId > 0 ? $activeUserBranchId : 0) : ($activeUserBranchId > 0 ? $activeUserBranchId : 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';
        }
    @endphp

    <div class="container-fluid px-4 py-4">
        <div class="row g-3 mb-4">
            <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">{{ $productsTotal }}</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-vx-open-low-stock
                    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">{{ $lowStockCount }}</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">{{ money($stockValue) }}</h2>
                    </div>
                </div>
            </div>
        </div>

        @if ($errors->any())
            <div class="alert alert-danger">
                {{ $errors->first() }}
            </div>
        @endif

        <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 w-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">{{ $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 w-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">{{ $pendingAdjustmentsRows->count() }} 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 w-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">{{ $movementsRows->count() }} 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 w-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">{{ $transferHistoryRows->count() }} 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 w-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">{{ $pendingAdjustmentsRows->count() }} 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 w-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">{{ $adjustmentHistoryRows->count() }} 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 mb-4">
            <div class="card-body">
                <form method="GET" action="{{ route('inventario.index') }}" class="row g-2 align-items-end">
                    <div class="col-12 col-md-8">
                        <label class="form-label" for="q">Buscar producto (nombre, SKU, codigo)</label>
                        <input class="form-control" id="q" name="q" value="{{ $search }}">
                    </div>
                    <div class="col-12 col-md-4">
                        <button class="btn btn-outline-primary w-100">Buscar</button>
                    </div>
                </form>
            </div>
        </div>

            <div class="card border-0 shadow-sm">
                <div class="table-responsive">
                    <table class="table align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Categoria</th>
                            <th>Stock</th>
                            <th>Costo prom.</th>
                            <th>Actualizado</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($inventario as $row)
                            <tr>
                                <td>{{ $row->producto?->nombre ?? 'N/A' }}</td>
                                <td>{{ $row->producto?->categoria?->nombre ?? 'N/A' }}</td>
                                <td>
                                    {{ number_format((float) $row->stock, 2) }}
                                    @if ($row->producto && (float) $row->stock <= (float) $row->producto->stock_minimo)
                                        <span class="badge text-bg-warning ms-1">Minimo</span>
                                    @endif
                                </td>
                                <td>{{ number_format((float) $row->costo_promedio, 2) }}</td>
                                <td>{{ optional($row->updated_at)->format('Y-m-d H:i') ?: 'N/A' }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center py-4">No hay registros de inventario para el contexto actual.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-3">
            {{ $inventario->links() }}
        </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>
                                @forelse ($lowStockRows as $product)
                                    <tr>
                                        <td>
                                            {{ (string) ($product['nombre'] ?? 'Producto') }}
                                            <small class="d-block text-muted">ID: {{ (int) ($product['id'] ?? 0) }}</small>
                                        </td>
                                        <td>{{ (string) (($product['sku'] ?? '') !== '' ? $product['sku'] : '-') }}</td>
                                        <td class="text-end text-danger fw-semibold">
                                            {{ number_format((float) ($product['stock_actual'] ?? 0), 2, ',', '.') }}
                                        </td>
                                        <td class="text-end">
                                            {{ number_format((float) ($product['stock_minimo'] ?? 0), 2, ',', '.') }}
                                        </td>
                                        <td class="text-end fw-semibold">
                                            {{ number_format((float) ($product['faltante'] ?? 0), 2, ',', '.') }}
                                        </td>
                                        <td class="text-end">{{ money((float) ($product['costo_promedio'] ?? 0)) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="6" class="text-center text-muted py-3">
                                            No hay productos con stock bajo en este momento.
                                        </td>
                                    </tr>
                                @endforelse
                            </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">
                    @if (! $canTransfer)
                        <div class="alert alert-warning mb-0">
                            Debes tener al menos dos sucursales activas para realizar traslados.
                        </div>
                    @else
                        <form action="{{ route('inventario.transfers.store') }}" method="post">
                            @csrf
                            <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>
                                    @foreach ($productos as $producto)
                                        @php
                                            $productId = (int) $producto->id;
                                            $productVariants = array_values(array_filter((array) ($variantsByProduct[$productId] ?? []), static fn (array $variant): bool => (int) ($variant['activo'] ?? 0) === 1));
                                            $variantsPayload = array_map(static function (array $variant): array {
                                                return [
                                                    'id' => (int) ($variant['id'] ?? 0),
                                                    'nombre' => (string) ($variant['nombre'] ?? ''),
                                                    'cantidad' => isset($variant['cantidad']) ? (int) $variant['cantidad'] : null,
                                                ];
                                            }, $productVariants);
                                            $variantsJson = json_encode($variantsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                            if (! is_string($variantsJson)) {
                                                $variantsJson = '[]';
                                            }
                                        @endphp
                                        <option
                                            value="{{ $productId }}"
                                            data-has-variants="{{ count($variantsPayload) > 0 ? '1' : '0' }}"
                                            data-variants="{{ e($variantsJson) }}"
                                            {{ $transferSelectedProduct === $productId ? 'selected' : '' }}
                                        >
                                            {{ $producto->nombre }} (Stock global: {{ number_format((float) $producto->stock_actual, 2, '.', '') }})
                                        </option>
                                    @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="{{ (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>
                                        @foreach ($branchesRows as $branch)
                                            @php $branchId = (int) ($branch->id ?? $branch['id'] ?? 0); @endphp
                                            <option value="{{ $branchId }}" {{ $transferOrigin === $branchId ? 'selected' : '' }}>
                                                {{ (string) ($branch->nombre ?? $branch['nombre'] ?? '') }}
                                            </option>
                                        @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>
                                        @foreach ($branchesRows as $branch)
                                            @php $branchId = (int) ($branch->id ?? $branch['id'] ?? 0); @endphp
                                            <option value="{{ $branchId }}" {{ $transferDestination === $branchId ? 'selected' : '' }}>
                                                {{ (string) ($branch->nombre ?? $branch['nombre'] ?? '') }}
                                            </option>
                                        @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="{{ $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)">{{ $transferObservation }}</textarea>
                            </div>

                            <div class="d-flex justify-content-end mt-3">
                                <button class="btn btn-primary" type="submit">Registrar traslado</button>
                            </div>
                        </form>
                    @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="{{ route('inventario.adjustments.store') }}" method="post">
                        @csrf
                        <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>
                                @foreach ($branchesRows as $branch)
                                    @php $branchId = (int) ($branch->id ?? $branch['id'] ?? 0); @endphp
                                    <option value="{{ $branchId }}" {{ $adjustmentSelectedBranch === $branchId ? 'selected' : '' }}>
                                        {{ (string) ($branch->nombre ?? $branch['nombre'] ?? '') }}
                                    </option>
                                @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>
                                @foreach ($productos as $producto)
                                    @php
                                        $productId = (int) $producto->id;
                                        $productVariants = array_values(array_filter((array) ($variantsByProduct[$productId] ?? []), static fn (array $variant): bool => (int) ($variant['activo'] ?? 0) === 1));
                                        $variantsPayload = array_map(static function (array $variant): array {
                                            return [
                                                'id' => (int) ($variant['id'] ?? 0),
                                                'nombre' => (string) ($variant['nombre'] ?? ''),
                                                'cantidad' => isset($variant['cantidad']) ? (int) $variant['cantidad'] : null,
                                            ];
                                        }, $productVariants);
                                        $variantsJson = json_encode($variantsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                        if (! is_string($variantsJson)) {
                                            $variantsJson = '[]';
                                        }
                                    @endphp
                                    <option
                                        value="{{ $productId }}"
                                        data-has-variants="{{ count($variantsPayload) > 0 ? '1' : '0' }}"
                                        data-variants="{{ e($variantsJson) }}"
                                        {{ $adjustmentSelectedProduct === $productId ? 'selected' : '' }}
                                    >
                                        {{ $producto->nombre }}
                                    </option>
                                @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="{{ (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="{{ $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>{{ $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>
                                @forelse ($movementsRows as $movement)
                                    @php
                                        $type = (string) ($movement['tipo'] ?? '');
                                        $typeClass = $type === 'entrada'
                                            ? 'text-bg-success'
                                            : ($type === 'salida' ? 'text-bg-warning' : 'text-bg-secondary');
                                    @endphp
                                    <tr>
                                        <td>{{ (string) ($movement['created_at'] ?? '') }}</td>
                                        <td>{{ (string) ($movement['sucursal'] ?? 'Sin sucursal') }}</td>
                                        <td>
                                            {{ (string) ($movement['producto'] ?? '') }}
                                            @if (!empty($movement['variante_nombre']))
                                                <small class="d-block text-muted">Variante: {{ (string) $movement['variante_nombre'] }}</small>
                                            @endif
                                        </td>
                                        <td><span class="badge {{ $typeClass }}">{{ $type }}</span></td>
                                        <td>{{ (string) ($movement['referencia'] ?? '') }}</td>
                                        <td>{{ (string) ($movement['cantidad'] ?? '0.00') }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="6" class="text-center text-muted">Sin movimientos registrados.</td>
                                    </tr>
                                @endforelse
                            </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>
                                @forelse ($transferHistoryRows as $transfer)
                                    <tr>
                                        <td>{{ (string) ($transfer['created_at'] ?? '') }}</td>
                                        <td>{{ (string) ($transfer['referencia'] ?? '') }}</td>
                                        <td>
                                            {{ (string) ($transfer['producto'] ?? '') }}
                                            @if (!empty($transfer['variante_nombre']))
                                                <small class="d-block text-muted">Variante: {{ (string) $transfer['variante_nombre'] }}</small>
                                            @endif
                                        </td>
                                        <td>{{ (string) ($transfer['sucursal_origen'] ?? 'Sin sucursal') }}</td>
                                        <td>{{ (string) ($transfer['sucursal_destino'] ?? 'Sin sucursal') }}</td>
                                        <td>{{ (string) ($transfer['cantidad'] ?? '0.00') }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="6" class="text-center text-muted">Aún no hay traslados registrados.</td>
                                    </tr>
                                @endforelse
                            </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>
                                @forelse ($pendingAdjustmentsRows as $adjustment)
                                    <tr>
                                        <td>{{ (string) ($adjustment['id'] ?? '') }}</td>
                                        <td>{{ (string) ($adjustment['sucursal'] ?? 'Sin sucursal') }}</td>
                                        <td>
                                            {{ (string) ($adjustment['producto'] ?? '') }}
                                            @if (!empty($adjustment['variante_nombre']))
                                                <small class="d-block text-muted">Variante: {{ (string) $adjustment['variante_nombre'] }}</small>
                                            @endif
                                        </td>
                                        <td>{{ (string) ($adjustment['stock_anterior'] ?? '0.00') }}</td>
                                        <td>{{ (string) ($adjustment['stock_nuevo'] ?? '0.00') }}</td>
                                        <td>{{ (string) ($adjustment['motivo'] ?? '') }}</td>
                                        <td style="min-width: 220px;">
                                            <form action="{{ route('inventario.adjustments.approve', ['ajuste' => (int) ($adjustment['id'] ?? 0)]) }}" method="post" class="mb-1">
                                                @csrf
                                                <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="{{ route('inventario.adjustments.reject', ['ajuste' => (int) ($adjustment['id'] ?? 0)]) }}" method="post">
                                                @csrf
                                                <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>
                                @empty
                                    <tr>
                                        <td colspan="7" class="text-center text-muted">No hay solicitudes pendientes.</td>
                                    </tr>
                                @endforelse
                            </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>
                                @forelse ($adjustmentHistoryRows as $row)
                                    @php
                                        $status = (string) ($row['estado'] ?? 'pendiente');
                                        $statusClass = $status === 'aprobado'
                                            ? 'text-bg-success'
                                            : ($status === 'rechazado' ? 'text-bg-danger' : 'text-bg-warning');
                                    @endphp
                                    <tr>
                                        <td>{{ (string) ($row['id'] ?? '') }}</td>
                                        <td>{{ (string) ($row['created_at'] ?? '') }}</td>
                                        <td>{{ (string) ($row['sucursal'] ?? 'Sin sucursal') }}</td>
                                        <td>
                                            {{ (string) ($row['producto'] ?? '') }}
                                            @if (!empty($row['variante_nombre']))
                                                <small class="d-block text-muted">Variante: {{ (string) $row['variante_nombre'] }}</small>
                                            @endif
                                        </td>
                                        <td>{{ (string) ($row['tipo_ajuste'] ?? 'correccion') }}</td>
                                        <td>{{ (string) ($row['stock_anterior'] ?? '0.00') }}</td>
                                        <td>{{ (string) ($row['stock_nuevo'] ?? '0.00') }}</td>
                                        <td><span class="badge {{ $statusClass }}">{{ $status }}</span></td>
                                        <td>{{ (string) ($row['solicitado_por'] ?? '-') }}</td>
                                        <td>{{ (string) ($row['aprobado_por'] ?? '-') }}</td>
                                        <td>{{ (string) ($row['observacion_aprobacion'] ?? '-') }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="11" class="text-center text-muted">Sin ajustes registrados.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('[data-vx-open-low-stock]').forEach((element) => {
                element.addEventListener('keydown', (event) => {
                    if (event.key !== 'Enter' && event.key !== ' ') {
                        return;
                    }

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

            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));
            });

            const autoOpenModalId = @json($autoOpenModalId);
            if (typeof autoOpenModalId === 'string' && autoOpenModalId !== '') {
                const modalEl = document.getElementById(autoOpenModalId);
                if (modalEl && typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                    bootstrap.Modal.getOrCreateInstance(modalEl).show();
                }
            }
        });
    </script>
@endpush
