@extends('layouts.yellow')

@section('title', 'Crear Transacción de Inventario')

@section('content')
    <div class="container-fluid inventory-container">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1><i class="fas fa-exchange-alt"></i> Crear Nueva Transacción</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"><a href="{{ route('inventory.transactions.index') }}">Transacciones</a></li>
                    <li class="breadcrumb-item active">Crear</li>
                </ol>
            </div>
        </div>

        <div class="inventory-card">
            <div class="card-header">
                <h3 class="card-title">Información de la Transacción</h3>
            </div>
            <form action="{{ route('inventory.transactions.store') }}" method="POST" class="form-inventory">
                @csrf
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="inventory_id">Producto <span class="text-danger">*</span></label>
                                <select class="form-control select2 @error('inventory_id') is-invalid @enderror" id="inventory_id" name="inventory_id" required>
                                    <option value="">Seleccionar producto</option>
                                    @foreach($inventoryItems ?? [] as $item)
                                        <option value="{{ $item->id }}" data-stock="{{ $item->quantity }}" {{ old('inventory_id') == $item->id ? 'selected' : '' }}>
                                            {{ $item->name }} - Stock actual: {{ $item->quantity }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('inventory_id')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="transaction_type">Tipo de Transacción <span class="text-danger">*</span></label>
                                <select class="form-control @error('transaction_type') is-invalid @enderror" id="transaction_type" name="transaction_type" required>
                                    <option value="entry" {{ old('transaction_type') == 'entry' ? 'selected' : '' }}>Entrada</option>
                                    <option value="exit" {{ old('transaction_type') == 'exit' ? 'selected' : '' }}>Salida</option>
                                    <option value="adjustment" {{ old('transaction_type') == 'adjustment' ? 'selected' : '' }}>Ajuste</option>
                                    <option value="transfer" {{ old('transaction_type') == 'transfer' ? 'selected' : '' }}>Transferencia</option>
                                </select>
                                @error('transaction_type')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="quantity">Cantidad <span class="text-danger">*</span></label>
                                <input type="number" class="form-control @error('quantity') is-invalid @enderror" id="quantity" name="quantity" min="0.01" step="0.01" value="{{ old('quantity', 1) }}" required>
                                <small id="stock-info" class="form-text text-muted">Cantidad actual en stock: <span id="current-stock">0</span></small>
                                @error('quantity')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="reference">Referencia</label>
                                <input type="text" class="form-control @error('reference') is-invalid @enderror" id="reference" name="reference" value="{{ old('reference') }}" placeholder="Ej: Pedido #123, Factura B-456">
                                @error('reference')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="reference_id">ID de Referencia</label>
                                <input type="text" class="form-control @error('reference_id') is-invalid @enderror" id="reference_id" name="reference_id" value="{{ old('reference_id') }}" placeholder="Ej: 123">
                                <small class="form-text text-muted">Identificador numérico opcional que puede vincularse a otro sistema</small>
                                @error('reference_id')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                            
                            <div class="form-group">
                                <label for="notes">Notas</label>
                                <textarea class="form-control @error('notes') is-invalid @enderror" id="notes" name="notes" rows="3">{{ old('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-inventory btn-inventory-primary" id="submit-btn">
                        <i class="fas fa-save"></i> Guardar
                    </button>
                    <a href="{{ route('inventory.transactions.index') }}" class="btn-inventory btn-inventory-secondary">
                        <i class="fas fa-times"></i> Cancelar
                    </a>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('javascript')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Actualizar stock actual cuando se selecciona un producto
        const inventorySelect = document.getElementById('inventory_id');
        const stockInfo = document.getElementById('current-stock');
        const transactionType = document.getElementById('transaction_type');
        const quantityInput = document.getElementById('quantity');
        const submitBtn = document.getElementById('submit-btn');
        
        function updateStockInfo() {
            if (inventorySelect.selectedIndex > 0) {
                const selectedOption = inventorySelect.options[inventorySelect.selectedIndex];
                const currentStock = selectedOption.getAttribute('data-stock');
                stockInfo.textContent = currentStock;
                
                // Validar si hay suficiente stock
                validateStock();
            } else {
                stockInfo.textContent = '0';
            }
        }
        
        function validateStock() {
            if (transactionType.value === 'exit') {
                const currentStock = parseFloat(stockInfo.textContent);
                const quantity = parseFloat(quantityInput.value);
                
                if (quantity > currentStock) {
                    quantityInput.classList.add('is-invalid');
                    submitBtn.disabled = true;
                    
                    // Añadir mensaje de error si no existe
                    if (!document.getElementById('stock-error')) {
                        const errorMessage = document.createElement('div');
                        errorMessage.id = 'stock-error';
                        errorMessage.classList.add('invalid-feedback');
                        errorMessage.innerHTML = '<strong>No hay suficiente stock para esta salida</strong>';
                        quantityInput.parentNode.appendChild(errorMessage);
                    }
                } else {
                    quantityInput.classList.remove('is-invalid');
                    submitBtn.disabled = false;
                    
                    // Eliminar mensaje de error si existe
                    const errorMessage = document.getElementById('stock-error');
                    if (errorMessage) {
                        errorMessage.remove();
                    }
                }
            } else {
                quantityInput.classList.remove('is-invalid');
                submitBtn.disabled = false;
                
                // Eliminar mensaje de error si existe
                const errorMessage = document.getElementById('stock-error');
                if (errorMessage) {
                    errorMessage.remove();
                }
            }
        }
        
        inventorySelect.addEventListener('change', updateStockInfo);
        transactionType.addEventListener('change', validateStock);
        quantityInput.addEventListener('input', validateStock);
        
        // Inicialización
        updateStockInfo();
    });
</script>
@endsection 