@extends('layouts.yellow')

@section('title', 'Editar Producto de Inventario')

@section('content')
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1><i class="fas fa-edit"></i> Editar Producto</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">Editar {{ $inventory->name }}</li>
                </ol>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Información del Producto</h3>
            </div>
            <form action="{{ route('inventory.update', $inventory) }}" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="card-body">
                    <!-- Información básica -->
                    <div class="row">
                        <div class="col-md-12">
                            <h4 class="mb-3">Información Básica</h4>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="name">Nombre <span class="text-danger">*</span></label>
                                <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{ old('name', $inventory->name) }}" required>
                                @error('name')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="category_id">Categoría <span class="text-danger">*</span></label>
                                <select class="form-control select2 @error('category_id') is-invalid @enderror" id="category_id" name="category_id" required>
                                    <option value="">Seleccionar categoría</option>
                                    @foreach($categories ?? [] as $category)
                                        <option value="{{ $category->id }}" {{ old('category_id', $inventory->category_id) == $category->id ? 'selected' : '' }}>
                                            {{ $category->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('category_id')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="supplier_id">Proveedor</label>
                                <select class="form-control select2 @error('supplier_id') is-invalid @enderror" id="supplier_id" name="supplier_id">
                                    <option value="">Seleccionar proveedor</option>
                                    @foreach($suppliers ?? [] as $supplier)
                                        <option value="{{ $supplier->id }}" {{ old('supplier_id', $inventory->supplier_id) == $supplier->id ? 'selected' : '' }}>
                                            {{ $supplier->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('supplier_id')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="status">Estado <span class="text-danger">*</span></label>
                                <select class="form-control @error('status') is-invalid @enderror" id="status" name="status" required>
                                    <option value="active" {{ old('status', $inventory->status) == 'active' ? 'selected' : '' }}>Activo</option>
                                    <option value="inactive" {{ old('status', $inventory->status) == 'inactive' ? 'selected' : '' }}>Inactivo</option>
                                    <option value="maintenance" {{ old('status', $inventory->status) == 'maintenance' ? 'selected' : '' }}>Mantenimiento</option>
                                </select>
                                @error('status')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="location">Ubicación</label>
                                <input type="text" class="form-control @error('location') is-invalid @enderror" id="location" name="location" value="{{ old('location', $inventory->location) }}">
                                @error('location')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="description">Descripción</label>
                                <textarea class="form-control @error('description') is-invalid @enderror" id="description" name="description" rows="3">{{ old('description', $inventory->description) }}</textarea>
                                @error('description')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="brand">Marca</label>
                                <input type="text" class="form-control @error('brand') is-invalid @enderror" id="brand" name="brand" value="{{ old('brand', $inventory->brand) }}">
                                @error('brand')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="model">Modelo</label>
                                <input type="text" class="form-control @error('model') is-invalid @enderror" id="model" name="model" value="{{ old('model', $inventory->model) }}">
                                @error('model')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="serial_number">Número de Serie</label>
                                <input type="text" class="form-control @error('serial_number') is-invalid @enderror" id="serial_number" name="serial_number" value="{{ old('serial_number', $inventory->serial_number) }}">
                                @error('serial_number')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                    </div>
                    
                    <!-- Inventario y precio -->
                    <div class="row mt-4">
                        <div class="col-md-12">
                            <h4 class="mb-3">Inventario y Precio</h4>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="quantity">Cantidad Actual</label>
                                <div class="input-group">
                                    <input type="number" class="form-control @error('quantity') is-invalid @enderror" id="quantity" name="quantity" step="0.01" min="0" value="{{ old('quantity', $inventory->quantity) }}">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-outline-info" data-toggle="modal" data-target="#adjustStockModal">
                                            <i class="fas fa-wrench"></i> Ajustar
                                        </button>
                                    </div>
                                </div>
                                <small class="form-text text-muted">Editar este campo registrará una transacción automáticamente.</small>
                                @error('quantity')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="min_stock">Stock Mínimo</label>
                                <input type="number" class="form-control @error('min_stock') is-invalid @enderror" id="min_stock" name="min_stock" step="0.01" min="0" value="{{ old('min_stock', $inventory->min_stock) }}">
                                <small class="form-text text-muted">Punto en el que se alerta de stock bajo.</small>
                                @error('min_stock')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="unit_price">Precio Unitario</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">$</span>
                                    </div>
                                    <input type="number" class="form-control @error('unit_price') is-invalid @enderror" id="unit_price" name="unit_price" step="0.01" min="0" value="{{ old('unit_price', $inventory->unit_price) }}">
                                </div>
                                @error('unit_price')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                    </div>
                    
                    <!-- Fechas -->
                    <div class="row mt-4">
                        <div class="col-md-12">
                            <h4 class="mb-3">Fechas Importantes</h4>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="expiration_date">Fecha de Vencimiento</label>
                                <input type="date" class="form-control @error('expiration_date') is-invalid @enderror" id="expiration_date" name="expiration_date" value="{{ old('expiration_date', $inventory->expiration_date ? $inventory->expiration_date->format('Y-m-d') : '') }}">
                                @error('expiration_date')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="last_maintenance">Último Mantenimiento</label>
                                <input type="date" class="form-control @error('last_maintenance') is-invalid @enderror" id="last_maintenance" name="last_maintenance" value="{{ old('last_maintenance', $inventory->last_maintenance ? $inventory->last_maintenance->format('Y-m-d') : '') }}">
                                @error('last_maintenance')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="next_maintenance">Próximo Mantenimiento</label>
                                <input type="date" class="form-control @error('next_maintenance') is-invalid @enderror" id="next_maintenance" name="next_maintenance" value="{{ old('next_maintenance', $inventory->next_maintenance ? $inventory->next_maintenance->format('Y-m-d') : '') }}">
                                @error('next_maintenance')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                    </div>
                    
                    <!-- Imagen y notas -->
                    <div class="row mt-4">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="image">Imagen del Producto</label>
                                <div class="input-group">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input @error('image') is-invalid @enderror" id="image" name="image" accept="image/*">
                                        <label class="custom-file-label" for="image">Seleccionar archivo</label>
                                    </div>
                                </div>
                                @error('image')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                                
                                @if($inventory->image_path)
                                    <div class="mt-2">
                                        <label>Imagen Actual:</label>
                                        <div>
                                            <img src="{{ asset('storage/inventory/' . $inventory->image_path) }}" alt="{{ $inventory->name }}" style="max-height: 150px; max-width: 100%;" class="img-thumbnail">
                                        </div>
                                        <div class="form-check mt-1">
                                            <input class="form-check-input" type="checkbox" name="remove_image" id="remove_image" value="1">
                                            <label class="form-check-label" for="remove_image">
                                                Eliminar imagen actual
                                            </label>
                                        </div>
                                    </div>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="notes">Notas</label>
                                <textarea class="form-control @error('notes') is-invalid @enderror" id="notes" name="notes" rows="4">{{ old('notes', $inventory->notes) }}</textarea>
                                @error('notes')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Guardar Cambios
                    </button>
                    <a href="{{ route('inventory.show', $inventory) }}" class="btn btn-secondary">
                        <i class="fas fa-times"></i> Cancelar
                    </a>
                </div>
            </form>
        </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-sm btn-info">
                        <i class="fas fa-history"></i> Ver Historial Completo
                    </a>
                </div>
            </div>
            <div class="card-body">
                @if(isset($transactions) && count($transactions) > 0)
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Tipo</th>
                                    <th>Cantidad</th>
                                    <th>Fecha</th>
                                    <th>Usuario</th>
                                    <th>Referencia</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($transactions as $transaction)
                                    <tr>
                                        <td>{{ $transaction->id }}</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->created_at->format('d/m/Y H:i') }}</td>
                                        <td>{{ $transaction->user->name ?? 'N/A' }}</td>
                                        <td>{{ $transaction->reference ?? 'Sin referencia' }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @else
                    <div class="alert alert-info mb-0">
                        <i class="fas fa-info-circle"></i> No hay transacciones registradas para este producto.
                    </div>
                @endif
            </div>
        </div>
    </div>
    
    <!-- Modal para ajustar stock -->
    <div class="modal fade" id="adjustStockModal" tabindex="-1" role="dialog" aria-labelledby="adjustStockModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="adjustStockModalLabel">Ajustar Stock</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">
                        <p>Cantidad actual: <strong>{{ $inventory->quantity }}</strong></p>
                        
                        <div class="form-group">
                            <label for="transaction_type">Tipo de Ajuste</label>
                            <select class="form-control" id="transaction_type" name="transaction_type" required>
                                <option value="entry">Entrada (Añadir)</option>
                                <option value="exit">Salida (Restar)</option>
                                <option value="adjustment">Ajuste (Establecer valor específico)</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="quantity_adjust">Cantidad</label>
                            <input type="number" class="form-control" id="quantity_adjust" name="quantity" min="0.01" step="0.01" value="1" required>
                            <small class="form-text text-muted quantity-help">
                                Esta cantidad se añadirá al stock actual.
                            </small>
                        </div>
                        
                        <div class="form-group">
                            <label for="notes_adjust">Notas</label>
                            <textarea class="form-control" id="notes_adjust" name="notes" rows="2" placeholder="Razón del ajuste..."></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 Ajuste</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@section('javascript')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Actualizar texto de ayuda según el tipo de transacción
        const transactionType = document.getElementById('transaction_type');
        const quantityHelp = document.querySelector('.quantity-help');
        
        transactionType.addEventListener('change', function() {
            switch (this.value) {
                case 'entry':
                    quantityHelp.textContent = 'Esta cantidad se añadirá al stock actual.';
                    break;
                case 'exit':
                    quantityHelp.textContent = 'Esta cantidad se restará del stock actual.';
                    break;
                case 'adjustment':
                    quantityHelp.textContent = 'El stock se establecerá exactamente a este valor.';
                    break;
            }
        });
        
        // Mostrar nombre del archivo seleccionado en el input file
        document.getElementById('image').addEventListener('change', function(e) {
            const fileName = e.target.files[0] ? e.target.files[0].name : 'Seleccionar archivo';
            const label = document.querySelector('.custom-file-label');
            label.textContent = fileName;
        });
    });
</script>
@endsection 