@extends('layouts.yellow')

@section('title', 'Detalles del Ítem de Inventario')

@section('content_header')
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1><i class="fas fa-box"></i> {{ $inventory->name }}</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('inventory.index') }}">Inventario</a></li>
                    <li class="breadcrumb-item active">Detalles</li>
                </ol>
            </div>
        </div>
    </div>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="row mb-3">
            <div class="col-md-12">
                <a href="{{ route('inventory.edit', $inventory) }}" class="btn btn-warning">
                    <i class="fas fa-edit"></i> Editar
                </a>
                <a href="{{ route('inventory.transactions.for-inventory', $inventory) }}" class="btn btn-info">
                    <i class="fas fa-exchange-alt"></i> Ver transacciones
                </a>
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#adjustModal">
                    <i class="fas fa-balance-scale"></i> Ajustar cantidad
                </button>
                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">
                    <i class="fas fa-trash"></i> Eliminar
                </button>
                <a href="{{ route('inventory.index') }}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Volver
                </a>
            </div>
        </div>

        <div class="row">
            <!-- Información general -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Información General</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-bordered">
                                    <tr>
                                        <th style="width: 40%">ID</th>
                                        <td>{{ $inventory->id }}</td>
                                    </tr>
                                    <tr>
                                        <th>Nombre</th>
                                        <td>{{ $inventory->name }}</td>
                                    </tr>
                                    <tr>
                                        <th>Categoría</th>
                                        <td>
                                            @if($inventory->category)
                                                <a href="{{ route('inventory.by-category', $inventory->category) }}">
                                                    {{ $inventory->category->name }}
                                                </a>
                                            @else
                                                <span class="text-muted">No asignada</span>
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Estado</th>
                                        <td>
                                            @if ($inventory->status == 'active')
                                                <span class="badge badge-success">Activo</span>
                                            @elseif ($inventory->status == 'inactive')
                                                <span class="badge badge-secondary">Inactivo</span>
                                            @elseif ($inventory->status == 'maintenance')
                                                <span class="badge badge-warning">Mantenimiento</span>
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Stock Actual</th>
                                        <td>
                                            @if ($inventory->isLowStock())
                                                <span class="badge badge-danger">{{ $inventory->quantity }} (Bajo)</span>
                                            @elseif ($inventory->isOutOfStock())
                                                <span class="badge badge-danger">Agotado</span>
                                            @else
                                                <span class="badge badge-success">{{ $inventory->quantity }}</span>
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Stock Mínimo</th>
                                        <td>{{ $inventory->min_stock ?? 'No establecido' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Ubicación</th>
                                        <td>{{ $inventory->location ?? 'No especificada' }}</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-bordered">
                                    <tr>
                                        <th style="width: 40%">Marca</th>
                                        <td>{{ $inventory->brand ?? 'No especificada' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Modelo</th>
                                        <td>{{ $inventory->model ?? 'No especificado' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Número de Serie</th>
                                        <td>{{ $inventory->serial_number ?? 'No especificado' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Precio Unitario</th>
                                        <td>{{ $inventory->unit_price ? '$' . number_format($inventory->unit_price, 2) : 'No establecido' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Fecha de Vencimiento</th>
                                        <td>
                                            @if ($inventory->expiration_date)
                                                @if ($inventory->isExpired())
                                                    <span class="text-danger">{{ $inventory->expiration_date->format('d/m/Y') }} (Vencido)</span>
                                                @elseif ($inventory->isAboutToExpire())
                                                    <span class="text-warning">{{ $inventory->expiration_date->format('d/m/Y') }} (Próximo a vencer)</span>
                                                @else
                                                    {{ $inventory->expiration_date->format('d/m/Y') }}
                                                @endif
                                            @else
                                                <span class="text-muted">No aplica</span>
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Creado</th>
                                        <td>{{ $inventory->created_at->format('d/m/Y H:i') }}</td>
                                    </tr>
                                    <tr>
                                        <th>Actualizado</th>
                                        <td>{{ $inventory->updated_at->format('d/m/Y H:i') }}</td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        @if ($inventory->description)
                            <div class="row mt-3">
                                <div class="col-md-12">
                                    <div class="card">
                                        <div class="card-header">
                                            <h3 class="card-title">Descripción</h3>
                                        </div>
                                        <div class="card-body">
                                            {{ $inventory->description }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endif

                        @if ($inventory->notes)
                            <div class="row mt-3">
                                <div class="col-md-12">
                                    <div class="card">
                                        <div class="card-header">
                                            <h3 class="card-title">Notas</h3>
                                        </div>
                                        <div class="card-body">
                                            {{ $inventory->notes }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>

                <!-- Historial de transacciones recientes -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h3 class="card-title">Transacciones Recientes</h3>
                        <div class="card-tools">
                            <a href="{{ route('inventory.transactions.for-inventory', $inventory) }}" class="btn btn-tool">
                                <i class="fas fa-arrow-right"></i> Ver todas
                            </a>
                        </div>
                    </div>
                    <div class="card-body table-responsive p-0">
                        <table class="table table-hover text-nowrap">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Tipo</th>
                                    <th>Cantidad</th>
                                    <th>Stock Anterior</th>
                                    <th>Stock Nuevo</th>
                                    <th>Usuario</th>
                                    <th>Notas</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($transactions as $transaction)
                                    <tr>
                                        <td>{{ $transaction->created_at->format('d/m/Y H:i') }}</td>
                                        <td>
                                            @if ($transaction->transaction_type == 'entry')
                                                <span class="badge badge-success">Entrada</span>
                                            @elseif ($transaction->transaction_type == 'exit')
                                                <span class="badge badge-danger">Salida</span>
                                            @elseif ($transaction->transaction_type == 'adjustment')
                                                <span class="badge badge-warning">Ajuste</span>
                                            @elseif ($transaction->transaction_type == 'transfer')
                                                <span class="badge badge-info">Transferencia</span>
                                            @endif
                                        </td>
                                        <td>{{ $transaction->quantity }}</td>
                                        <td>{{ $transaction->previous_quantity }}</td>
                                        <td>{{ $transaction->new_quantity }}</td>
                                        <td>{{ $transaction->user->name ?? 'N/A' }}</td>
                                        <td>{{ $transaction->notes ?? 'N/A' }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="7" class="text-center">No hay transacciones registradas.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Información lateral -->
            <div class="col-md-4">
                <!-- Imagen -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Imagen</h3>
                    </div>
                    <div class="card-body text-center">
                        @if ($inventory->image_path)
                            <img src="{{ asset('storage/inventory/' . $inventory->image_path) }}" alt="{{ $inventory->name }}" class="img-fluid">
                        @else
                            <div class="alert alert-secondary">
                                <i class="fas fa-image fa-3x mb-3"></i>
                                <p>No hay imagen disponible para este ítem.</p>
                            </div>
                        @endif
                    </div>
                </div>

                <!-- Información del Proveedor -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h3 class="card-title">Información del Proveedor</h3>
                    </div>
                    <div class="card-body">
                        @if ($inventory->supplier)
                            <h5>{{ $inventory->supplier->name }}</h5>
                            <p>
                                @if ($inventory->supplier->phone)
                                    <i class="fas fa-phone"></i> {{ $inventory->supplier->phone }}<br>
                                @endif
                                @if ($inventory->supplier->email)
                                    <i class="fas fa-envelope"></i> {{ $inventory->supplier->email }}<br>
                                @endif
                                @if ($inventory->supplier->contact_person)
                                    <i class="fas fa-user"></i> {{ $inventory->supplier->contact_person }}<br>
                                @endif
                            </p>
                            <a href="{{ route('inventory.suppliers.show', $inventory->supplier) }}" class="btn btn-sm btn-info">
                                <i class="fas fa-external-link-alt"></i> Ver proveedor
                            </a>
                        @else
                            <div class="alert alert-secondary">
                                <p>No hay proveedor asignado para este ítem.</p>
                            </div>
                        @endif
                    </div>
                </div>

                <!-- Información de Mantenimiento -->
                @if ($inventory->last_maintenance || $inventory->next_maintenance)
                    <div class="card mt-4">
                        <div class="card-header">
                            <h3 class="card-title">Información de Mantenimiento</h3>
                        </div>
                        <div class="card-body">
                            <table class="table table-bordered">
                                @if ($inventory->last_maintenance)
                                    <tr>
                                        <th>Último Mantenimiento</th>
                                        <td>{{ $inventory->last_maintenance->format('d/m/Y') }}</td>
                                    </tr>
                                @endif
                                @if ($inventory->next_maintenance)
                                    <tr>
                                        <th>Próximo Mantenimiento</th>
                                        <td>
                                            @if ($inventory->next_maintenance->isPast())
                                                <span class="text-danger">{{ $inventory->next_maintenance->format('d/m/Y') }} (Atrasado)</span>
                                            @elseif ($inventory->next_maintenance->diffInDays(now()) <= 30)
                                                <span class="text-warning">{{ $inventory->next_maintenance->format('d/m/Y') }} (Próximo)</span>
                                            @else
                                                {{ $inventory->next_maintenance->format('d/m/Y') }}
                                            @endif
                                        </td>
                                    </tr>
                                @endif
                            </table>
                        </div>
                    </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Modal de eliminación -->
    <div class="modal fade inventory-modal" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">Confirmar eliminación</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    ¿Estás seguro de que deseas eliminar <strong>{{ $inventory->name }}</strong>?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <form action="{{ route('inventory.destroy', $inventory) }}" method="POST">
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger">Eliminar</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal de ajuste de cantidad -->
    <div class="modal fade" id="adjustModal" tabindex="-1" role="dialog" aria-labelledby="adjustModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="adjustModalLabel">Ajustar cantidad</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form action="{{ route('inventory.adjust', $inventory) }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="transaction_type">Tipo de transacción</label>
                            <select class="form-control" id="transaction_type" name="transaction_type" required>
                                <option value="entry">Entrada</option>
                                <option value="exit">Salida</option>
                                <option value="adjustment">Ajuste directo</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="quantity">Cantidad</label>
                            <input type="number" class="form-control" id="quantity" name="quantity" min="0" step="0.01" required>
                            <small class="form-text text-muted">
                                Para entradas: cantidad a agregar. Para salidas: cantidad a restar. Para ajustes: cantidad total nueva.
                            </small>
                        </div>
                        <div class="form-group">
                            <label for="notes">Notas</label>
                            <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    $(document).ready(function() {
        // Mover todos los modales al contenedor global
        $('.inventory-modal').each(function() {
            $(this).appendTo('#inventory-modals-container');
        });
        
        // Asegurar que todos los botones de bootstrap dentro del modal usen nuestros estilos
        $('#deleteModal').find('.btn-secondary').addClass('btn-inventory-secondary').removeClass('btn-secondary');
        $('#deleteModal').find('.btn-danger').addClass('btn-inventory-danger').removeClass('btn-danger');
        $('#adjustModal').find('.btn-secondary').addClass('btn-inventory-secondary').removeClass('btn-secondary');
        $('#adjustModal').find('.btn-primary').addClass('btn-inventory-primary').removeClass('btn-primary');
        
        // Estabilizar modales con control manual
        $('[data-toggle="modal"]').on('click', function(e) {
            e.preventDefault();
            
            var targetModal = $(this).data('target');
            var $modal = $(targetModal);
            
            // Asegurar que el backdrop existe
            if ($('.modal-backdrop').length === 0) {
                $('body').append('<div class="modal-backdrop show"></div>');
            }
            
            // Mostrar el modal sin animaciones
            $modal.removeClass('fade').addClass('show d-block');
            $('body').addClass('modal-open');
            
            // Configurar cierre
            $modal.find('.close, .btn-inventory-secondary').off('click').on('click', function() {
                closeModal($modal);
            });
        });
        
        // Función para cerrar modal manualmente
        function closeModal($modal) {
            $modal.removeClass('show d-block').addClass('fade');
            $('.modal-backdrop').remove();
            $('body').removeClass('modal-open');
        }
    });
</script>
@endpush 