@extends('layouts.main')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <h4>Products Reconciliation</h4>
    <div>
        <a href="{{ route('reports.reconciliation') }}" class="btn btn-info me-2">
            <i class="bi bi-file-earmark-text"></i> View Report
        </a>
        <a href="{{ route('inventory.index') }}" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> Back to Inventory
        </a>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-4">
        <div class="card stat-card blue">
            <div class="card-body">
                <h6 class="card-title">Total Products</h6>
                <h2 class="mb-0">{{ $products->count() }}</h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card stat-card green">
            <div class="card-body">
                <h6 class="card-title">Total Stock Value (Cost)</h6>
                <h2 class="mb-0">Kes {{ number_format($totalStockValue, 2) }}</h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card stat-card purple">
            <div class="card-body">
                <h6 class="card-title">Total Retail Value</h6>
                <h2 class="mb-0">Kes {{ number_format($totalRetailValue, 2) }}</h2>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <form method="GET" action="{{ route('inventory.reconciliation') }}" class="mb-4">
            <div class="row">
                <div class="col-md-3">
                    <label class="form-label">Search</label>
                    <input type="text" name="search" class="form-control" placeholder="Name, SKU, Barcode..." value="{{ $search ?? '' }}">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Category</label>
                    <select name="category_id" class="form-select">
                        <option value="">All Categories</option>
                        @foreach($categories as $category)
                            <option value="{{ $category->id }}" {{ $categoryId == $category->id ? 'selected' : '' }}>
                                {{ $category->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Stock Filter</label>
                    <select name="stock_filter" class="form-select">
                        <option value="">All Products</option>
                        <option value="positive" {{ $stockFilter === 'positive' ? 'selected' : '' }}>With Stock</option>
                        <option value="low" {{ $stockFilter === 'low' ? 'selected' : '' }}>Low Stock</option>
                        <option value="out" {{ $stockFilter === 'out' ? 'selected' : '' }}>Out of Stock</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="bi bi-filter"></i> Filter
                    </button>
                    <a href="{{ route('inventory.reconciliation') }}" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-counterclockwise"></i> Reset
                    </a>
                </div>
            </div>
        </form>

        <form method="POST" action="{{ route('inventory.reconciliation.save') }}">
            @csrf
            <div class="table-responsive">
                <table class="table table-hover" id="reconciliationTable">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>SKU</th>
                            <th>Barcode</th>
                            <th>Category</th>
                            <th class="text-end">Cost Price</th>
                            <th class="text-end">Old Qty</th>
                            <th class="text-end">New Qty</th>
                            <th class="text-end">Difference</th>
                            <th class="text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($products as $product)
                            @php
                                $oldQty = $product->stock_quantity;
                                $newQty = isset($itemQuantities[$product->id]) ? $itemQuantities[$product->id] : $oldQty;
                                $difference = $newQty - $oldQty;
                            @endphp
                            <tr data-product-id="{{ $product->id }}">
                                <td>{{ $product->name }}</td>
                                <td>{{ $product->sku }}</td>
                                <td>{{ $product->barcode ?? '-' }}</td>
                                <td>{{ $product->category->name ?? '-' }}</td>
                                <td class="text-end">Kes {{ number_format($product->cost_price, 2) }}</td>
                                <td class="text-end old-qty">{{ number_format($oldQty, 2) }} {{ $product->unitOfMeasure->name ?? '' }}</td>
                                <td class="text-end">
                                    <input type="hidden" name="items[{{ $loop->index }}][product_id]" value="{{ $product->id }}">
                                    <input type="hidden" name="items[{{ $loop->index }}][old_quantity]" value="{{ $oldQty }}">
                                    <input type="number" 
                                           name="items[{{ $loop->index }}][new_quantity]" 
                                           class="form-control text-end new-qty-input" 
                                           value="{{ number_format($newQty, 2, '.', '') }}" 
                                           step="0.01"
                                           style="width: 100px; display: inline-block;"
                                           data-old-qty="{{ $oldQty }}">
                                </td>
                                <td class="text-end difference">{{ $difference > 0 ? '+' : '' }}{{ number_format($difference, 2) }}</td>
                                <td class="text-center">
                                    @if($product->stock_quantity <= 0)
                                        <span class="badge bg-danger">Out of Stock</span>
                                    @elseif($product->isLowStock())
                                        <span class="badge bg-warning">Low Stock</span>
                                    @else
                                        <span class="badge bg-success">In Stock</span>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="9" class="text-center py-4">No products found.</td>
                            </tr>
                        @endforelse
                    </tbody>
                    <tfoot>
                        <tr class="fw-bold">
                            <td colspan="4">Total</td>
                            <td class="text-end"></td>
                            <td class="text-end">{{ number_format($products->sum('stock_quantity'), 2) }}</td>
                            <td class="text-end" id="totalNewQty">{{ number_format($products->sum('stock_quantity'), 2) }}</td>
                            <td class="text-end" id="totalDifference">0.00</td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            @if($products->count() > 0)
            <div class="mt-3 text-end">
                <button type="submit" class="btn btn-success">
                    <i class="bi bi-save"></i> Save Reconciliation
                </button>
            </div>
            @endif
        </form>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const table = document.getElementById('reconciliationTable');
    if (!table) return;

    const inputs = table.querySelectorAll('.new-qty-input');
    
    function updateRow(row) {
        const input = row.querySelector('.new-qty-input');
        const oldQty = parseFloat(input.dataset.oldQty) || 0;
        const newQty = parseFloat(input.value) || 0;
        const diff = newQty - oldQty;
        const diffCell = row.querySelector('.difference');
        
        diffCell.textContent = (diff > 0 ? '+' : '') + diff.toFixed(2);
        diffCell.className = 'text-end difference ' + (diff > 0 ? 'text-success' : (diff < 0 ? 'text-danger' : ''));
    }

    function updateTotals() {
        let totalNew = 0;
        let totalDiff = 0;
        
        inputs.forEach(input => {
            const row = input.closest('tr');
            const oldQty = parseFloat(input.dataset.oldQty) || 0;
            const newQty = parseFloat(input.value) || 0;
            totalNew += newQty;
            totalDiff += (newQty - oldQty);
        });

        document.getElementById('totalNewQty').textContent = totalNew.toFixed(2);
        const totalDiffEl = document.getElementById('totalDifference');
        totalDiffEl.textContent = (totalDiff > 0 ? '+' : '') + totalDiff.toFixed(2);
        totalDiffEl.className = 'text-end ' + (totalDiff > 0 ? 'text-success' : (totalDiff < 0 ? 'text-danger' : ''));
    }

    inputs.forEach(input => {
        input.addEventListener('input', function() {
            updateRow(this.closest('tr'));
            updateTotals();
        });
    });
});
</script>
@endpush
@endsection
