<?php
    $editableColumns = isset($editableColumns) && is_array($editableColumns) ? $editableColumns : [];
    $detailEntities = ['bienes', 'registros-stock'];
    $highlightColumnsByEntity = [
        'sitios' => ['responsable'],
        'embarcaciones' => ['responsable'],
        'tallas-uniformes' => ['cedula_usuario'],
        'registros-stock' => ['cedulaResponsable', 'codigo'],
    ];
    $resolvePhotoUrl = static function (string $directory, ?string $identifier): ?string {
        $identifier = trim((string) $identifier);
        if ($identifier === '') {
            return null;
        }

        foreach (['jpg', 'png', 'webp'] as $ext) {
            $relativePath = $directory . '/' . $identifier . '.' . $ext;
            if (is_file(public_path($relativePath))) {
                return asset($relativePath);
            }
        }

        return null;
    };
    $extractTooltipLabel = static function ($label): ?string {
        if (! is_string($label) || $label === '') {
            return null;
        }

        $parts = explode(' - ', $label, 2);

        return $parts[1] ?? $label;
    };
    $resolveOperationRoute = static function ($value): ?string {
        return match ((int) $value) {
            1 => 'alimentos',
            2 => 'dotacion',
            3 => 'transferencia',
            5 => 'devolucion-prestamo',
            6 => 'devolucion-transferencia',
            default => null,
        };
    };
    $entityKey = is_string($entity ?? null) ? $entity : '';
    $formatKg = static function ($value): string {
        $numericValue = is_numeric($value) ? (float) $value : 0.0;
        $formatted = number_format($numericValue, 3, '.', '');
        $formatted = rtrim(rtrim($formatted, '0'), '.');

        return ($formatted === '' ? '0' : $formatted) . ' kg';
    };
    $hasDetailAction = in_array($entityKey, $detailEntities, true);
    $hasReadOnlyActions = $hasDetailAction || $entityKey === 'operaciones';
    $showActionsColumn = ! ($isReadOnly ?? false) || $hasReadOnlyActions;
    $entityHighlightColumns = $highlightColumnsByEntity[$entityKey] ?? [];
?>

<div class="crud-card p-3" style="width: 100%; max-width: 100vw;">
    <?php if(method_exists($rows, 'links')): ?>
        <div class="mb-2">
            <?php echo e($rows->links()); ?>

        </div>
    <?php endif; ?>
    <div class="crud-table-wrap">
        <div>
            <table class="table table-sm align-middle mb-0" style="width:100%; table-layout:auto; overflow:visible;">
                <thead>
                    <tr>
                        <?php if(!empty($showRowNumber)): ?>
                            <th>#</th>
                        <?php endif; ?>
                        <?php $__currentLoopData = $columns; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $column): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <th class="<?php echo e($entity === 'embarcaciones' && $column === 'observacion' ? 'obs-col' : ''); ?>"><?php echo e($columnLabels[$column] ?? $column); ?></th>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        <?php if($showActionsColumn): ?>
                            <th>Acciones</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php $__empty_1 = true; $__currentLoopData = $rows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <?php
                            $usuarioPhotoUrl = $resolvePhotoUrl('foto_usuarios', data_get($row, 'cedula'));
                            $bienPhotoUrl = $entity === 'bienes'
                                ? $resolvePhotoUrl('foto_bienes', data_get($row, 'codigo'))
                                : null;
                            $rowRecord = collect($editableColumns)->mapWithKeys(fn ($col) => [$col => data_get($row, $col)]);
                            $tipoOperacionRoute = $entity === 'operaciones'
                                ? $resolveOperationRoute(data_get($row, 'tipo'))
                                : null;
                        ?>
                        <tr>
                            <?php if(!empty($showRowNumber)): ?>
                                <td><?php echo e(($rows->firstItem() ?? 1) + $loop->index); ?></td>
                            <?php endif; ?>
                            <?php $__currentLoopData = $columns; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $column): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php
                                    $cellValue = data_get($row, $column);
                                    $rawCellValue = $cellValue;
                                    $cellTooltip = null;
                                    $isEmbarcacionObservation = $entity === 'embarcaciones' && $column === 'observacion';

                                    if ($column === 'activo') {
                                        $cellValue = (string) $cellValue === '1' ? 'Activo' : 'Inactivo';
                                    }

                                    if ($entity === 'bienes' && $column === 'tipo') {
                                        $cellValue = data_get($row, 'tipo_nombre') ?? $cellValue;
                                    } elseif ($entity === 'bienes' && $column === 'pesoTotal') {
                                        $cellValue = data_get($row, 'pesoTotal');
                                    } elseif ($entity === 'registros-stock' && $column === 'objetivo') {
                                        $cellValue = match ((int) $cellValue) {
                                            1 => 'Almacenado',
                                            2 => 'En stock',
                                            default => $cellValue,
                                        };
                                    } elseif ($entity === 'operaciones' && $column === 'tipo') {
                                        $cellValue = $fieldOptions['tipo'][(int) $rawCellValue] ?? $rawCellValue;
                                    }

                                    if (($entity === 'sitios' || $entity === 'embarcaciones') && $column === 'responsable') {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions['responsable'][$cellValue] ?? null);
                                    } elseif ($entity === 'tallas-uniformes' && $column === 'cedula_usuario') {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions['cedula_usuario'][$cellValue] ?? null);
                                    } elseif (in_array($column, ['cedulaEditor', 'cedula_usuario'], true) && isset($fieldOptions[$column])) {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions[$column][$cellValue] ?? null);
                                        $cellValue = $fieldOptions[$column][$cellValue] ?? $cellValue;
                                    } elseif ($entity === 'registros-stock' && $column === 'cedulaResponsable') {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions['cedulaResponsable'][$cellValue] ?? null);
                                    } elseif ($entity === 'registros-stock' && $column === 'codigo') {
                                        $bienDescripcion = $bienLabels[$cellValue] ?? null;
                                        $cellTooltip = is_string($bienDescripcion) && trim($bienDescripcion) !== ''
                                            ? $bienDescripcion
                                            : null;
                                    }

                                    $isHighlightedCell = in_array($column, $entityHighlightColumns, true) && filled($cellValue);
                                ?>
                                <td class="<?php echo e($isEmbarcacionObservation ? 'obs-col' : ''); ?>">
                                    <?php if($isHighlightedCell): ?>
                                        <span
                                            class="responsable-highlight"
                                            <?php if($cellTooltip): ?>
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="<?php echo e($cellTooltip); ?>"
                                            <?php endif; ?>
                                        ><?php echo e($cellValue); ?></span>
                                    <?php elseif($isEmbarcacionObservation): ?>
                                        <div class="observation-cell">
                                            <button
                                                type="button"
                                                class="observation-indicator action-icon-btn <?php echo e(filled($cellValue) ? '' : 'd-none'); ?>"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="<?php echo e($cellValue ?? ''); ?>"
                                                aria-label="Ver observacion"
                                            >💬</button>
                                        </div>
                                    <?php elseif($entity === 'precios-por-bien' && in_array($column, ['precio', 'precio_final'], true)): ?>
                                        <?php echo e(number_format((float) ($cellValue ?? 0), 2, ',', '.')); ?>

                                    <?php elseif($entity === 'precios-por-bien' && $column === 'porcentaje_utilidad'): ?>
                                        <?php echo e(number_format((float) ($cellValue ?? 0), 2, ',', '.')); ?>%
                                    <?php elseif($entity === 'bienes' && $column === 'precioUnitario'): ?>
                                        <?php
                                            $ultimaFechaPrecio = data_get($row, 'ultimoPrecioPorBien.fecha_registro');
                                            $establecerPrecioUrl = route('administracion.crud.index', [
                                                'entity' => 'precios-por-bien',
                                                'bien_id' => data_get($row, 'id'),
                                                'open_modal' => 'create',
                                                'selected_bien_id' => data_get($row, 'id'),
                                            ]);
                                        ?>
                                        <?php if($cellValue === null): ?>
                                            <?php if(! ($isReadOnly ?? false)): ?>
                                                <a class="btn btn-sm btn-outline-primary" href="<?php echo e($establecerPrecioUrl); ?>">Establecer precio</a>
                                            <?php else: ?>
                                                -
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <div><?php echo e(number_format((float) $cellValue, 2, ',', '.')); ?></div>
                                            <?php if(filled($ultimaFechaPrecio)): ?>
                                                <div class="small text-muted">(<?php echo e($ultimaFechaPrecio); ?>)</div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    <?php elseif($entity === 'bienes' && in_array($column, ['peso', 'pesoTotal'], true)): ?>
                                        <?php echo e($formatKg($cellValue)); ?>

                                    <?php elseif($entity === 'bienes' && $column === 'relacionUnidades'): ?>
                                        <?php echo e((int) ($cellValue ?? 0)); ?>

                                    <?php else: ?>
                                        <?php echo e($cellValue); ?>

                                    <?php endif; ?>
                                </td>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php if($showActionsColumn): ?>
                                <td class="text-nowrap">
                                    <div class="actions-cell">
                                        <?php if($hasDetailAction): ?>
                                            <button
                                                class="btn btn-sm action-icon-btn detail-row-btn"
                                                type="button"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="Ver detalle"
                                                aria-label="Ver detalle"
                                                data-detail-record='<?php echo json_encode($rowRecord, 15, 512) ?>'
                                                <?php if($entity === 'bienes'): ?>
                                                    data-foto-bien-url="<?php echo e($bienPhotoUrl ?? ''); ?>"
                                                <?php endif; ?>
                                            >👁</button>
                                        <?php endif; ?>
                                        <?php if($entity === 'operaciones' && $tipoOperacionRoute !== null): ?>
                                            <a
                                                class="btn btn-sm btn-outline-primary"
                                                href="<?php echo e(route('administracion.comprobante.show', ['id' => data_get($row, $primaryKey)])); ?>"
                                                aria-label="Ver comprobante"
                                            >Ver comprobante</a>
                                            <a
                                                class="btn btn-sm btn-excel"
                                                href="<?php echo e(route('asignacion.operacion.export', ['tipo' => $tipoOperacionRoute, 'numero' => data_get($row, 'numero')])); ?>"
                                                aria-label="Exportar Excel"
                                            >Exportar Excel</a>
                                        <?php elseif($entity === 'operaciones'): ?>
                                            <span class="text-muted small">Sin comprobante</span>
                                        <?php endif; ?>
                                        <?php if(! ($isReadOnly ?? false)): ?>
                                            <button
                                                class="btn btn-sm action-icon-btn edit-row-btn"
                                                type="button"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="Editar"
                                                aria-label="Editar"
                                                data-update-url="<?php echo e(route('administracion.crud.update', ['entity' => $entity, 'id' => data_get($row, $primaryKey)])); ?>"
                                                data-record='<?php echo json_encode($rowRecord, 15, 512) ?>'
                                                data-foto-usuario-url="<?php echo e($usuarioPhotoUrl ?? ''); ?>"
                                                <?php if($entity === 'bienes'): ?>
                                                    data-foto-bien-url="<?php echo e($bienPhotoUrl ?? ''); ?>"
                                                <?php endif; ?>
                                            >✏️</button>
                                            <form method="POST" class="d-inline" action="<?php echo e(route('administracion.crud.destroy', ['entity' => $entity, 'id' => data_get($row, $primaryKey)])); ?>" onsubmit="return confirm('Eliminar registro?');">
                                                <?php echo csrf_field(); ?>
                                                <?php echo method_field('DELETE'); ?>
                                                <button class="btn btn-sm action-icon-btn" type="submit" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Eliminar" aria-label="Eliminar">🚫</button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td class="text-secondary" colspan="<?php echo e(count($columns) + ($showActionsColumn ? 1 : 0) + (!empty($showRowNumber) ? 1 : 0)); ?>">Sin registros.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if(method_exists($rows, 'links')): ?>
        <div class="mt-3">
            <?php echo e($rows->links()); ?>

        </div>
    <?php endif; ?>
</div>
<?php /**PATH C:\xampp\htdocs\almacen2\resources\views/administracion/crud/partials/table.blade.php ENDPATH**/ ?>