@extends('layouts.admin')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Inventory Management</h4>
                </div>
                
                <div class="card-body">
                
                        @if(session('success'))
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                {{ session('success') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        @endif
                    
                        @if(session('error'))
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                {{ session('error') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        @endif
                    
                        @if($errors->any())
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <ul class="mb-0">
                                    @foreach($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        @endif
                    
                      
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Category</th>
                                    <th>Current Stock</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($products as $product)
                                <tr data-product-id="{{ $product->id }}">
                                        <td>
                                            <div class="d-flex align-items-center">
                                                @if($product->images->first())
                                                    <img src="{{ asset('storage/' . $product->images->first()->path) }}" 
                                                         alt="{{ $product->name }}" 
                                                         style="width: 40px; height: 40px; object-fit: cover; margin-right: 10px;">
                                                @endif
                                                {{ $product->name }}
                                            </div>
                                        </td>
                                        <td>{{ $product->category->name }}</td>
                                        <td class="stock-quantity">{{ $product->stock_quantity }}</td>
                                        <td>
                                            <span class="status-badge badge 
                                                @if($product->stock_quantity > 5)
                                                    bg-success
                                                @elseif($product->stock_quantity > 0)
                                                    bg-warning
                                                @else
                                                    bg-danger
                                                @endif">
                                                @if($product->stock_quantity > 5)
                                                    In Stock
                                                @elseif($product->stock_quantity > 0)
                                                    Low Stock
                                                @else
                                                    Out of Stock
                                                @endif
                                            </span>
                                        </td>
                                        
                                        <td>
                                            <button type="button" 
                                            class="btn btn-sm btn-success" 
                                            data-bs-toggle="modal" 
                                            data-bs-target="#addStockModal{{ $product->id }}">
                                        Add Stock
                                    </button>
                                            <a href="{{ route('admin.products.edit', $product) }}" 
                                               class="btn btn-sm btn-info">Update Stock</a>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="5" class="text-center">No products found</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-4">
                        {{ $products->links('pagination::bootstrap-5') }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


@foreach($products as $product)
    <!-- Add Stock Modal -->
    <div class="modal fade" id="addStockModal{{ $product->id }}" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="{{ route('admin.products.add-stock', $product->id) }}" 
                    method="POST" 
                    class="add-stock-form">
                  @csrf
                    <div class="modal-header">
                        <h5 class="modal-title">Add Stock - {{ $product->name }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="quantity{{ $product->id }}" class="form-label">Quantity to Add</label>
                            <input type="number" 
                                   class="form-control" 
                                   id="quantity{{ $product->id }}" 
                                   name="quantity" 
                                   min="1" 
                                   required>
                        </div>
                        <div class="mb-3">
                            <label for="purchase_price{{ $product->id }}" class="form-label">Purchase Price (per unit)</label>
                            <input type="number" 
                                   class="form-control" 
                                   id="purchase_price{{ $product->id }}" 
                                   name="purchase_price" 
                                   step="0.01" 
                                   min="0" 
                                   required>
                        </div>
                        <div class="mb-3">
                            <label for="supplier{{ $product->id }}" class="form-label">Supplier (optional)</label>
                            <input type="text" 
                                   class="form-control" 
                                   id="supplier{{ $product->id }}" 
                                   name="supplier">
                        </div>
                        <div class="mb-3">
                            <label for="notes{{ $product->id }}" class="form-label">Notes</label>
                            <textarea class="form-control" 
                                      id="notes{{ $product->id }}" 
                                      name="notes" 
                                      rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Stock</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endforeach


<script>
    // Handle form submission
    document.querySelectorAll('.add-stock-form').forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            fetch(this.action, {
                method: 'POST',
                body: new FormData(this),
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Close modal
                    const modal = this.closest('.modal');
                    const bsModal = bootstrap.Modal.getInstance(modal);
                    bsModal.hide();

                    // Show success message
                    const alert = `
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            ${data.message}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    `;
                    document.querySelector('.card-body').insertAdjacentHTML('afterbegin', alert);

                    // Update stock quantity in the table
                    const productRow = document.querySelector(`tr[data-product-id="${data.product_id}"]`);
                    if (productRow) {
                        productRow.querySelector('.stock-quantity').textContent = data.new_stock;
                        // Update status badge
                        const statusBadge = productRow.querySelector('.status-badge');
                        if (data.new_stock > 5) {
                            statusBadge.className = 'badge bg-success';
                            statusBadge.textContent = 'In Stock';
                        } else if (data.new_stock > 0) {
                            statusBadge.className = 'badge bg-warning';
                            statusBadge.textContent = 'Low Stock';
                        } else {
                            statusBadge.className = 'badge bg-danger';
                            statusBadge.textContent = 'Out of Stock';
                        }
                    }

                    // Reset form
                    this.reset();
                } else {
                    throw new Error(data.message || 'Failed to update stock');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                const alert = `
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        ${error.message}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                `;
                document.querySelector('.card-body').insertAdjacentHTML('afterbegin', alert);
            });
        });
    });
</script>
@endsection