@extends('layouts.admin')

@section('title', 'Products Missing Purchase Price')

@section('content')
<x-admin.report-page title="Products Missing Purchase Price" subtitle="Fix cost price gaps so profit reports stay accurate.">
    <x-slot:actions>
        <a href="{{ route('admin.products.purchase-prices.import') }}" class="ci-btn ci-btn--ghost">
            <i class="bi bi-upload"></i> Bulk Import
        </a>
        <a href="{{ route('admin.reports.profit') }}" class="ci-btn ci-btn--ghost">
            <i class="bi bi-arrow-left"></i> Back to Profit Report
        </a>
    </x-slot:actions>

    <div class="ci-stats">
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Products Missing Purchase Price</p>
                <p class="ci-stat__value ci-stat__value--warning">{{ $missingCount }}</p>
            </div>
            <span class="ci-stat__icon"><i class="bi bi-exclamation-triangle"></i></span>
        </div>
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Products with Purchase Price</p>
                <p class="ci-stat__value ci-stat__value--success">{{ $totalProducts - $missingCount }}</p>
            </div>
            <span class="ci-stat__icon"><i class="bi bi-check-circle"></i></span>
        </div>
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Purchase Price Coverage</p>
                <p class="ci-stat__value">{{ number_format($coveragePercent, 1) }}%</p>
            </div>
            <span class="ci-stat__icon"><i class="bi bi-percent"></i></span>
        </div>
    </div>

    @if($coveragePercent < 100)
    <div class="ci-section">
        <div class="ci-section__body">
            <p class="mb-0">
                <i class="bi bi-exclamation-triangle text-warning"></i>
                <strong>Action Required:</strong> {{ $missingCount }} products are missing purchase prices, which affects profit calculations.
                Add purchase prices to get accurate profit reports.
            </p>
        </div>
    </div>
    @endif

    <div class="ci-table-card">
        <div class="ci-table-wrap">
            <table class="ci-table">
                <thead>
                    <tr>
                        <th>Product Name</th>
                        <th>Category</th>
                        <th>Barcode</th>
                        <th class="ci-end">Current Price</th>
                        <th class="ci-end">MRP</th>
                        <th class="ci-end">Stock</th>
                        <th class="ci-end">Status</th>
                        <th class="ci-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($products as $product)
                    <tr>
                        <td>
                            <strong>{{ $product->name }}</strong>
                            @if(!$product->is_active)
                                <span class="ci-pill ci-pill--inactive" style="margin-left:0.35rem;">Inactive</span>
                            @endif
                        </td>
                        <td>
                            @if($product->category)
                                <span class="ci-pill ci-pill--chip">{{ $product->category->name }}</span>
                            @else
                                <span class="ci-money--muted">No category</span>
                            @endif
                        </td>
                        <td>
                            @if($product->barcode)
                                <code class="ci-code">{{ $product->barcode }}</code>
                            @else
                                <span class="ci-money--muted">{{ $product->slug }}</span>
                            @endif
                        </td>
                        <td class="ci-end ci-money">
                            ₹{{ number_format($product->price, 2) }}
                        </td>
                        <td class="ci-end ci-money">
                            @if($product->mrp)
                                ₹{{ number_format($product->mrp, 2) }}
                            @else
                                <span class="ci-money--muted">-</span>
                            @endif
                        </td>
                        <td class="ci-end">
                            <span class="ci-pill {{ $product->current_stock > 0 ? 'ci-pill--success' : 'ci-pill--danger' }}">
                                {{ $product->current_stock }}
                            </span>
                        </td>
                        <td class="ci-end">
                            @if($product->is_active)
                                <span class="ci-pill ci-pill--active">Active</span>
                            @else
                                <span class="ci-pill ci-pill--inactive">Inactive</span>
                            @endif
                        </td>
                        <td class="ci-end">
                            <div style="display:inline-flex;gap:0.35rem;">
                                <a href="{{ route('admin.products.edit', $product->id) }}"
                                   class="ci-btn ci-btn--ghost ci-btn--icon"
                                   title="Edit Product">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <button type="button"
                                        class="ci-btn ci-btn--ghost ci-btn--icon"
                                        onclick="quickAddPurchasePrice({{ $product->id }}, '{{ addslashes($product->name) }}')"
                                        title="Quick Add Purchase Price">
                                    <i class="bi bi-plus"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="8">
                            <div class="ci-empty">
                                <i class="bi bi-check-circle" style="color:var(--ci-success);"></i>
                                <h3>All Products Have Purchase Prices!</h3>
                                <p>Great! All your active products have purchase prices set.</p>
                                <a href="{{ route('admin.reports.profit') }}" class="ci-btn ci-btn--primary">
                                    <i class="bi bi-graph-up"></i> View Profit Reports
                                </a>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        @if($products->total() > 0)
        <div class="ci-pagination">
            <div class="ci-pagination__info">
                Showing <strong>{{ $products->firstItem() ?? 0 }}</strong>–<strong>{{ $products->lastItem() ?? 0 }}</strong>
                of <strong>{{ $products->total() }}</strong>
            </div>
            @if($products->hasPages())
            <div>
                {{ $products->links('vendor.pagination.collection') }}
            </div>
            @endif
        </div>
        @endif
    </div>

    <!-- Quick Add Purchase Price Modal -->
    <div class="modal fade mt-5" id="quickAddModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Purchase Price</h5>
                    <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal"><i class="bi-x-lg"></i></button>
                </div>
                <form id="quickAddForm">
                    @csrf
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Product</label>
                            <input type="text" class="form-control" id="productName" readonly>
                            <input type="hidden" id="productId">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Purchase Price (₹) *</label>
                            <input type="number" step="0.01" class="form-control" id="purchasePrice" required placeholder="Enter cost price">
                            <div class="form-text">Enter the cost price for this product</div>
                        </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-success">Save Purchase Price</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</x-admin.report-page>
@endsection

@section('scripts')
<script>
function quickAddPurchasePrice(productId, productName) {
    document.getElementById('productId').value = productId;
    document.getElementById('productName').value = productName;
    document.getElementById('purchasePrice').value = '';

    const modal = new bootstrap.Modal(document.getElementById('quickAddModal'));
    modal.show();
}

document.getElementById('quickAddForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const productId = document.getElementById('productId').value;
    const purchasePrice = document.getElementById('purchasePrice').value;

    if (!purchasePrice || purchasePrice <= 0) {
        alert('Please enter a valid purchase price');
        return;
    }

    // Send AJAX request to update purchase price
    fetch(`/admin/products/${productId}/purchase-price`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({
            purchase_price: purchasePrice
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Close modal and reload page
            bootstrap.Modal.getInstance(document.getElementById('quickAddModal')).hide();
            location.reload();
        } else {
            alert('Error updating purchase price: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating purchase price');
    });
});
</script>
@endsection
