<div class="page-header">
    <div>
        <a href="<?= APP_URL ?>/stock-takings" class="btn btn-ghost btn-sm mb-4" style="padding-left:0;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Stock Taking
        </a>
        <h1>Count Stock</h1>
        <div class="page-subtitle">Reference: <?= e($stockTaking['reference']) ?> | Mode: <?= ucfirst($stockTaking['mode']) ?></div>
    </div>
    <div class="flex gap-2 flex-wrap items-center">
        <div class="search-box" style="position: relative;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999;"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
            <input type="text" id="product-search" class="form-control" placeholder="Search products..." autocomplete="off" oninput="filterProducts(this.value)" style="padding-left: 40px; width: 250px;">
        </div>
        <button onclick="printTable()" class="btn btn-outline" title="Print count sheet">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v-5a2 2 0 0 1-2 2h-2"></path><rect x="6" y="14" width="12" height="8"></rect></svg>
            Print Count Sheet
        </button>
        <button onclick="exportCSV()" class="btn btn-outline" title="Export to CSV">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
            Export to CSV
        </button>
    </div>
</div>

<div class="card mb-6">
    <div class="card-body p-4">
        <div class="grid-4 gap-4">
            <div>
                <div class="text-sm text-muted">Location</div>
                <div class="font-semibold"><?= e($stockTaking['location_name']) ?></div>
            </div>
            <div>
                <div class="text-sm text-muted">Total Products</div>
                <div class="font-semibold"><?= count($products) ?></div>
            </div>
            <div>
                <div class="text-sm text-muted">Counted Items</div>
                <div class="font-semibold"><?= count($countedMap) ?></div>
            </div>
            <div>
                <div class="text-sm text-muted">Status</div>
                <div class="badge badge-warning">Draft</div>
            </div>
        </div>
    </div>
</div>

<form action="<?= APP_URL ?>/stock-takings/save" method="POST" id="stockCountForm">
    <?= Security::csrfField() ?>
    <input type="hidden" name="stock_taking_id" value="<?= $stockTaking['id'] ?>">

    <?php
    // Group products by category for tab navigation
    $categories = [];
    foreach ($products as $product) {
        $catName = $product['category_name'] ?: 'Uncategorized';
        if (!isset($categories[$catName])) {
            $categories[$catName] = [];
        }
        $categories[$catName][] = $product;
    }

    if ($stockTaking['mode'] === 'category' && count($categories) > 0): ?>
        <!-- Tab Navigation -->
        <div class="tabs mb-6" style="display: flex; gap: 4px; border-bottom: 2px solid var(--border); padding-bottom: 0;">
            <?php $firstCategory = true; ?>
            <?php foreach ($categories as $catName => $catProducts): ?>
                <button type="button"
                        class="tab-btn <?= $firstCategory ? 'active' : '' ?>"
                        data-category="<?= e($catName) ?>"
                        onclick="switchTab(this)"
                        style="padding: 10px 20px; border: none; background: transparent; cursor: pointer; font-weight: 600; color: var(--text-muted); border-bottom: 2px solid transparent; margin-bottom: -2px; transition: all 0.2s;">
                    <?= e($catName) ?>
                </button>
                <?php $firstCategory = false; ?>
            <?php endforeach; ?>
        </div>

        <!-- Tab Content -->
        <?php $firstCategory = true; ?>
        <?php foreach ($categories as $catName => $catProducts): ?>
            <div class="tab-content <?= $firstCategory ? 'active' : '' ?>" data-category="<?= e($catName) ?>" style="display: <?= $firstCategory ? 'block' : 'none' ?>;">
                <div class="card mb-6">
                    <div class="table-wrapper">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>SKU</th>
                                    <?php if (Auth::can('stock.adjust')): ?>
                                    <th>Current Stock</th>
                                    <?php endif; ?>
                                    <th>Counted Qty</th>
                                    <th>Difference</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($catProducts as $product): ?>
                                    <?php
                                    $countedItem = $countedMap[$product['id']] ?? null;
                                    $countedQty = $countedItem ? (float)$countedItem['counted_qty'] : '';
                                    $currentStock = (float)$product['current_stock'];
                                    $difference = $countedQty !== '' ? (float)$countedQty - $currentStock : 0;

                                    if ($countedQty === '') {
                                        $status = 'pending';
                                        $statusClass = 'badge-muted';
                                        $diffClass = 'text-muted';
                                    } elseif ($difference < 0) {
                                        $status = 'shortage';
                                        $statusClass = 'badge-danger';
                                        $diffClass = 'text-red-600';
                                    } elseif ($difference > 0) {
                                        $status = 'over';
                                        $statusClass = 'badge-warning';
                                        $diffClass = 'text-orange-600';
                                    } else {
                                        $status = 'equal';
                                        $statusClass = 'badge-success';
                                        $diffClass = 'text-green-600';
                                    }
                                    ?>
                                    <tr data-product-id="<?= $product['id'] ?>" data-name="<?= e($product['name']) ?>" data-sku="<?= e($product['sku'] ?: '') ?>" data-category="<?= e($catName) ?>">
                                        <td>
                                            <strong><?= e($product['name']) ?></strong>
                                        </td>
                                        <td>
                                            <span class="text-sm text-muted"><?= e($product['sku'] ?: '-') ?></span>
                                        </td>
                                        <?php if (Auth::can('stock.adjust')): ?>
                                        <td>
                                            <span class="text-sm font-semibold"><?= number_format($currentStock, 2) ?></span>
                                        </td>
                                        <?php endif; ?>
                                        <td>
                                            <input type="number"
                                                   name="items[<?= $product['id'] ?>][counted_qty]"
                                                   class="form-control form-control-sm"
                                                   style="width: 100px;"
                                                   step="0.01"
                                                   min="0"
                                                   value="<?= $countedQty ?>"
                                                   data-current-stock="<?= $currentStock ?>"
                                                   onchange="updateDifference(<?= $product['id'] ?>)">
                                            <input type="hidden" name="items[<?= $product['id'] ?>][current_stock]" value="<?= $currentStock ?>">
                                            <input type="hidden" name="items[<?= $product['id'] ?>][category_id]" value="<?= $product['category_id'] ?>">
                                            <input type="hidden" name="items[<?= $product['id'] ?>][unit_cost]" value="<?= $product['unit_cost'] ?>">
                                        </td>
                                        <td>
                                            <span class="text-sm font-semibold <?= $diffClass ?>" id="diff-<?= $product['id'] ?>">
                                                <?= $difference != 0 ? ($difference > 0 ? '+' : '') . number_format($difference, 2) : '-' ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge <?= $statusClass ?>" id="status-<?= $product['id'] ?>">
                                                <?= ucfirst($status) ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php $firstCategory = false; ?>
        <?php endforeach; ?>
    <?php else: ?>
        <!-- Item mode (single table) -->
        <div class="card mb-6">
            <div class="card-header">
                <h3 class="card-title">Products</h3>
            </div>
            <div class="table-wrapper">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>SKU</th>
                            <th>Category</th>
                            <?php if (Auth::hasRole(['admin', 'owner'])): ?>
                            <th>Current Stock</th>
                            <?php endif; ?>
                            <th>Counted Qty</th>
                            <th>Difference</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        foreach ($products as $product):
            
            $countedItem = $countedMap[$product['id']] ?? null;
            $countedQty = $countedItem ? (float)$countedItem['counted_qty'] : '';
            $currentStock = (float)$product['current_stock'];
            $difference = $countedQty !== '' ? (float)$countedQty - $currentStock : 0;

            if ($countedQty === '') {
                $status = 'pending';
                $statusClass = 'badge-muted';
                $diffClass = 'text-muted';
            } elseif ($difference < 0) {
                $status = 'shortage';
                $statusClass = 'badge-danger';
                $diffClass = 'text-red-600';
            } elseif ($difference > 0) {
                $status = 'over';
                $statusClass = 'badge-warning';
                $diffClass = 'text-orange-600';
            } else {
                $status = 'equal';
                $statusClass = 'badge-success';
                $diffClass = 'text-green-600';
            }
            ?>
            <tr data-product-id="<?= $product['id'] ?>" data-name="<?= e($product['name']) ?>" data-sku="<?= e($product['sku'] ?: '') ?>" data-category="<?= e($product['category_name'] ?: '') ?>">
                <td>
                    <strong><?= e($product['name']) ?></strong>
                </td>
                <td>
                    <span class="text-sm text-muted"><?= e($product['sku'] ?: '-') ?></span>
                </td>
                <?php if ($stockTaking['mode'] === 'item'): ?>
                <td>
                    <span class="text-sm"><?= e($product['category_name'] ?: '-') ?></span>
                </td>
                <?php endif; ?>
                <?php if (Auth::hasRole(['admin', 'owner'])): ?>
                <td>
                    <span class="text-sm font-semibold"><?= number_format($currentStock, 2) ?></span>
                </td>
                <?php endif; ?>
                <td>
                    <input type="number" 
                           name="items[<?= $product['id'] ?>][counted_qty]" 
                           class="form-control form-control-sm" 
                           style="width: 100px;"
                           step="0.01"
                           min="0"
                           value="<?= $countedQty ?>"
                           data-current-stock="<?= $currentStock ?>"
                           onchange="updateDifference(<?= $product['id'] ?>)">
                    <input type="hidden" name="items[<?= $product['id'] ?>][current_stock]" value="<?= $currentStock ?>">
                    <input type="hidden" name="items[<?= $product['id'] ?>][category_id]" value="<?= $product['category_id'] ?>">
                    <input type="hidden" name="items[<?= $product['id'] ?>][unit_cost]" value="<?= $product['unit_cost'] ?>">
                </td>
                <td>
                    <span class="text-sm font-semibold <?= $diffClass ?>" id="diff-<?= $product['id'] ?>">
                        <?= $difference != 0 ? ($difference > 0 ? '+' : '') . number_format($difference, 2) : '-' ?>
                    </span>
                </td>
                <td>
                    <span class="badge <?= $statusClass ?>" id="status-<?= $product['id'] ?>">
                        <?= ucfirst($status) ?>
                    </span>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
    <?php endif; ?>

<div class="card">
    <div class="card-body">
        <div class="flex justify-between items-center gap-4">
            <div class="text-sm text-muted">
                <strong>Note:</strong> Enter the actual counted quantity for each product. The system will automatically calculate differences and indicate shortages or overstock.
            </div>
            <div class="flex gap-2">
                <button type="submit" name="action" value="save" class="btn btn-secondary">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                        <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                        <polyline points="17 21 17 13 7 13 7 21"></polyline>
                        <polyline points="7 3 7 8 15 8"></polyline>
                    </svg>
                    Save Draft
                </button>
                <button type="submit" name="action" value="save_complete" class="btn btn-primary" onclick="return confirm('Complete this stock taking? You will be able to view the report after.')">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                        <polyline points="20 6 9 17 4 12"></polyline>
                    </svg>
                    Complete & View Report
                </button>
                <button type="submit" name="action" value="save_update" class="btn btn-success" onclick="return confirmUpdateStock()">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                        <path d="M11 4H4a2 2 0 0 1-2h3a2 2 0 0 1-2z"></path>
                        <path d="M17 5v-2h3a2 2 0 0 1-2z"></path>
                        <polyline points="20 12 20 22 4 22 4 12"></polyline>
                    </svg>
                    Complete & Update Stock
                </button>
            </div>
        </div>
    </div>
</div>
</form>

<script>
function switchTab(tabBtn) {
    const category = tabBtn.dataset.category;

    // Update tab button styles
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
        btn.style.color = 'var(--text-muted)';
        btn.style.borderBottomColor = 'transparent';
    });
    tabBtn.classList.add('active');
    tabBtn.style.color = 'var(--primary)';
    tabBtn.style.borderBottomColor = 'var(--primary)';

    // Show/hide tab content
    document.querySelectorAll('.tab-content').forEach(content => {
        if (content.dataset.category === category) {
            content.style.display = 'block';
        } else {
            content.style.display = 'none';
        }
    });
}

function filterProducts(searchTerm) {
    const rows = document.querySelectorAll('tr[data-product-id]');
    const term = searchTerm.toLowerCase().trim();

    rows.forEach(row => {
        const name = row.dataset.name ? row.dataset.name.toLowerCase() : '';
        const sku = row.dataset.sku ? row.dataset.sku.toLowerCase() : '';
        const category = row.dataset.category ? row.dataset.category.toLowerCase() : '';

        const matches = term === '' || name.includes(term) || sku.includes(term) || category.includes(term);
        row.style.display = matches ? '' : 'none';
    });
}

function updateDifference(productId) {
    const input = document.querySelector(`input[name="items[${productId}][counted_qty]"]`);
    const currentStock = parseFloat(input.dataset.currentStock);
    const diffEl = document.getElementById(`diff-${productId}`);
    const statusEl = document.getElementById(`status-${productId}`);

    // Clear difference and status if input is empty
    if (input.value === '') {
        diffEl.textContent = '-';
        diffEl.className = 'text-sm font-semibold text-muted';
        statusEl.textContent = 'Pending';
        statusEl.className = 'badge badge-muted';
        return;
    }

    const countedQty = parseFloat(input.value) || 0;
    const difference = countedQty - currentStock;

    if (difference < 0) {
        diffEl.textContent = difference.toFixed(2);
        diffEl.className = 'text-sm font-semibold text-red-600';
        statusEl.textContent = 'Shortage';
        statusEl.className = 'badge badge-danger';
    } else if (difference > 0) {
        diffEl.textContent = '+' + difference.toFixed(2);
        diffEl.className = 'text-sm font-semibold text-orange-600';
        statusEl.textContent = 'Over';
        statusEl.className = 'badge badge-warning';
    } else {
        diffEl.textContent = '-';
        diffEl.className = 'text-sm font-semibold text-green-600';
        statusEl.textContent = 'Equal';
        statusEl.className = 'badge badge-success';
    }
}

function confirmUpdateStock() {
    const inputs = document.querySelectorAll('input[name*="[counted_qty]"]');
    let hasNegativesInSystem = false;
    let productsWithNegatives = [];

    inputs.forEach(input => {
        const current = parseFloat(input.dataset.currentStock) || 0;
        if (current < 0 && input.value !== '') {
            hasNegativesInSystem = true;
            const row = input.closest('tr');
            const name = row ? row.dataset.name : 'Unknown Product';
            productsWithNegatives.push(`${name} (Current: ${current})`);
        }
        
        // Final sanity check for negative input
        if (parseFloat(input.value) < 0) {
            alert('Error: Negative counts are not allowed.');
            input.focus();
            return false;
        }
    });

    let message = "Are you sure you want to complete this stock taking and update your actual inventory levels?\n\nThis will adjust stock to match your counted quantities.";

    if (hasNegativesInSystem) {
        message += "\n\n⚠️ IMPORTANT: Some products currently have NEGATIVE stock in the system which will be corrected to your new counted values:\n- " + productsWithNegatives.slice(0, 5).join("\n- ");
        if (productsWithNegatives.length > 5) message += "\n... and " + (productsWithNegatives.length - 5) + " more.";
    }

    message += "\n\nProceed with applying these changes? (Yes/No)";

    return confirm(message);
}
</script>
<script>
function printTable() {
    const form = document.getElementById('stockCountForm');
    if (!form) return;
    
    const container = document.createElement('div');
    const cards = form.querySelectorAll('.card');
    cards.forEach(card => {
        if (!card.querySelector('table')) return; 
        
        const clonedCard = card.cloneNode(true);
        const inputs = clonedCard.querySelectorAll('input[type="number"]');
        inputs.forEach(input => {
            const span = document.createElement('span');
            span.style.cssText = 'display:inline-block; border-bottom: 2px dashed #000; width: 60px; height: 14px;';
            input.parentNode.replaceChild(span, input);
        });
        
        const hiddens = clonedCard.querySelectorAll('input[type="hidden"]');
        hiddens.forEach(h => h.remove());
        
        container.appendChild(clonedCard);
    });
    
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Stock Count Sheet</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; font-size: 12px; }
                table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
                th, td { border: 1px solid #ccc; padding: 6px 8px; text-align: left; }
                th { background: #f5f5f5; font-weight: bold; }
                h3.card-title { margin: 15px 0 5px 0; font-size: 14px; font-weight: bold; }
                .text-muted { color: #666; }
                .text-sm { font-size: 11px; }
                .font-semibold { font-weight: bold; }
                .badge { padding: 3px 8px; border-radius: 3px; font-size: 10px; display: inline-block; background: #e2e3e5; color: #333; }
                .text-red-600 { color: #dc2626; }
                .text-orange-600 { color: #ea580c; }
                .text-green-600 { color: #16a34a; }
                @media print {
                    body { margin: 15mm; padding: 0; }
                    .card { page-break-inside: avoid; }
                }
            </style>
        </head>
        <body>
            <div style="margin-bottom: 20px; border-bottom: 2px solid #333; padding-bottom: 10px;">
                <h2 style="margin: 0 0 5px 0;">Stock Count Sheet: <?= e($stockTaking['reference']) ?></h2>
                <p style="margin: 0; color: #666;">Location: <?= e($stockTaking['location_name']) ?> | Date: ${new Date().toLocaleDateString()}</p>
            </div>
            ${container.innerHTML}
        </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.onload = function() {
        printWindow.print();
        printWindow.close();
    };
}

function exportCSV() {
    let csv = 'Product,SKU,Category,Current Stock\n';
    <?php foreach ($products as $product): ?>
    csv += '<?= e(str_replace(',', ' ', $product['name'])) ?>,<?= e($product['sku']) ?>,<?= e(str_replace(',', ' ', $product['category_name'] ?: '-')) ?>,<?= $product['current_stock'] ?>\n';
    <?php endforeach; ?>
    
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'stock_count_sheet_<?= e($stockTaking['reference']) ?>.csv';
    a.click();
    window.URL.revokeObjectURL(url);
}
</script>
