@extends('layouts.main')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4>Products</h4>
        <small class="text-muted">Total: {{ $totalProducts }} products</small>
    </div>
    <div>
        @if(Auth::user()->hasPermission('products.delete'))
        <button type="button" class="btn btn-danger me-2" id="deleteSelectedBtn" style="display: none;" onclick="deleteSelected()">
            <i class="bi bi-trash"></i> Delete Selected (<span id="selectedCount">0</span>)
        </button>
        @endif
        @if(Auth::user()->hasPermission('products.create'))
        <a href="{{ route('products.create') }}" class="btn btn-primary">
            <i class="bi bi-plus-circle"></i> Add Product
        </a>
        @endif
    </div>
</div>

<div class="card">
    <div class="card-header">
        <form method="GET" action="{{ route('products.index') }}" class="row g-3">
            <div class="col-md-3">
                <input type="text" name="search" class="form-control" placeholder="Search products..." value="{{ request('search') }}">
            </div>
            <div class="col-md-3">
                <select name="category_id" class="form-select">
                    <option value="">All Categories</option>
                    @foreach($categories as $category)
                        <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                            {{ $category->name }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-2">
                <div class="form-check">
                    <input type="checkbox" name="low_stock" value="1" id="low_stock" class="form-check-input" {{ request('low_stock') ? 'checked' : '' }}>
                    <label class="form-check-label" for="low_stock">Low Stock</label>
                </div>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
            <div class="col-md-2">
                <a href="{{ route('products.index') }}" class="btn btn-secondary w-100">Reset</a>
            </div>
        </form>
    </div>
    <div class="card-body table-responsive">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="checkAll" onchange="toggleAll(this)">
                    </th>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Barcode</th>
                    <th>Category</th>
                    <th>Unit</th>
                    @if(Auth::user()->hasPermission('products.edit'))
                    <th>Cost</th>
                    @endif
                    <th>Price</th>
                    <th>Price 2</th>
                    <th>Price 3</th>
                    <th>Stock</th>
                    <th>Expiry</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                @forelse($products as $product)
                    <tr>
                        <td>
                            <input type="checkbox" class="product-checkbox" value="{{ $product->id }}" onchange="updateDeleteButton()">
                        </td>
                        <td>
                            @if($product->image)
                                <img src="{{ asset('storage/products/'.$product->image) }}" alt="" width="50" height="50" class="rounded object-fit-cover">
                            @else
                                <div class="bg-light rounded d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                                    <i class="bi bi-image text-muted"></i>
                                </div>
                            @endif
                        </td>
                        <td>{{ $product->name }}</td>
                        <td>{{ $product->barcode }}</td>
                        <td>{{ $product->category->name }}</td>
                        <td>{{ $product->unitOfMeasure->abbreviation ?? '-' }}</td>
                        @if(Auth::user()->hasPermission('products.edit'))
                        <td>{{ number_format($product->cost_price, 2) }}</td>
                        @endif
                        <td>{{ number_format($product->selling_price, 2) }}</td>
                        <td>
                            @if($product->price_2_name)
                                <span class="text-muted">{{ $product->price_2_name }}:</span> {{ number_format($product->price_2, 2) }}
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            @if($product->price_3_name)
                                <span class="text-muted">{{ $product->price_3_name }}:</span> {{ number_format($product->price_3, 2) }}
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            <span class="badge {{ $product->stock_quantity <= $product->low_stock_threshold ? 'bg-danger' : 'bg-success' }}">
                                {{ $product->stock_quantity }} {{ $product->unitOfMeasure->abbreviation ?? '' }}
                            </span>
                        </td>
                        <td>
                            @if($product->expiry_date)
                                @php
                                    $isExpired = $product->expiry_date->isPast();
                                    $daysLeft = floor($product->expiry_date->diffInDays(now()));
                                @endphp
                                @if($isExpired)
                                    <span class="badge bg-danger" title="Expired">Expired</span>
                                @elseif($daysLeft <= 7)
                                    <span class="badge bg-danger" title="{{ $daysLeft }} days left">{{ $daysLeft }}d</span>
                                @elseif($daysLeft <= 30)
                                    <span class="badge bg-warning" title="{{ $daysLeft }} days left">{{ $daysLeft }}d</span>
                                @else
                                    <span class="badge bg-success" title="{{ $product->expiry_date->format('d M Y') }}">{{ $product->expiry_date->format('d M y') }}</span>
                                @endif
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            <span class="badge {{ $product->is_active ? 'bg-success' : 'bg-secondary' }}">
                                {{ $product->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </td>
                        <td>
                            <a href="{{ route('products.show', $product->id) }}" class="btn btn-sm btn-info">
                                <i class="bi bi-eye"></i>
                            </a>
                            @if(Auth::user()->hasPermission('products.edit'))
                            <a href="{{ route('products.edit', $product->id) }}" class="btn btn-sm btn-primary">
                                <i class="bi bi-pencil"></i>
                            </a>
                            @endif
                            @if(Auth::user()->hasPermission('products.delete'))
                            <form action="{{ route('products.destroy', $product->id) }}" method="POST" class="d-inline">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                            @endif
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="14" class="text-center">No products found.</td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        {{ $products->withQueryString()->links('pagination::bootstrap-5') }}
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('input[name="search"]');
    
    if (searchInput.value) {
        searchInput.focus();
        searchInput.setSelectionRange(searchInput.value.length, searchInput.value.length);
    }
    
    searchInput.addEventListener('input', function() {
        const form = this.closest('form');
        const url = new URL(form.action);
        if (this.value === '') {
            url.searchParams.delete('search');
        } else {
            url.searchParams.set('search', this.value);
        }
        url.searchParams.delete('page');
        window.location.href = url.toString();
    });
});

function toggleAll(source) {
    const checkboxes = document.querySelectorAll('.product-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = source.checked;
    });
    updateDeleteButton();
}

function updateDeleteButton() {
    const checked = document.querySelectorAll('.product-checkbox:checked');
    const btn = document.getElementById('deleteSelectedBtn');
    const countSpan = document.getElementById('selectedCount');
    countSpan.textContent = checked.length;
    btn.style.display = checked.length > 0 ? 'inline-block' : 'none';
}

function deleteSelected() {
    const checked = document.querySelectorAll('.product-checkbox:checked');
    if (checked.length === 0) return;
    
    if (!confirm('Are you sure you want to delete ' + checked.length + ' product(s)? This action cannot be undone.')) {
        return;
    }
    
    const ids = Array.from(checked).map(cb => cb.value);
    
    $.ajax({
        url: '{{ route("products.bulkDestroy") }}',
        method: 'POST',
        data: { ids: ids },
        success: function(data) {
            console.log('Response:', data);
            if (data.success) {
                location.reload();
            } else {
                alert(data.message || 'Error deleting products');
            }
        },
        error: function(xhr) {
            console.error('Error:', xhr);
            alert('An error occurred while deleting products: ' + (xhr.responseJSON?.message || xhr.statusText));
        }
    });
}
</script>
@endsection
