<div class="page-header responsive-header">
    <div>
        <a href="<?= APP_URL ?>/inventory" class="btn btn-ghost btn-sm mb-3" 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 Inventory
        </a>
        <h1>Add Stock Adjustment</h1>
        <div class="page-subtitle">Manage stock adjustments with multiple products</div>
    </div>
    <div class="flex gap-2 flex-wrap">
        <button type="button" onclick="window.print()" class="btn btn-secondary btn-sm">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="6 9 6 15 18 15"></polyline>
                <path d="M6 4h12v16H6z"></path>
            </svg>
            Print
        </button>
    </div>
</div>

<style>
/* Base Compact Styles */
.page-header {
    margin-bottom: 0.75rem;
}

.page-header h1 {
    font-size: 1.25rem;
    margin-bottom: 0.25rem;
}

.page-subtitle {
    font-size: 0.75rem;
}

.card {
    margin-bottom: 0.75rem;
    padding: 0.5rem;
}

.card-header {
    padding: 0.5rem 0.5rem 0.25rem 0.5rem;
}

.card-title {
    font-size: 0.875rem;
    font-weight: 600;
}

/* Responsive Grid Layout */
.responsive-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0.5rem;
}

.form-grid {
    grid-template-columns: repeat(2, 1fr);
}

/* Compact Forms */
.form-group {
    margin-bottom: 0.5rem;
}

.form-label {
    font-size: 0.7rem;
    margin-bottom: 0.25rem;
}

.form-control {
    padding: 0.4rem 0.5rem;
    font-size: 0.75rem;
}

/* Compact Buttons */
.btn-sm {
    padding: 0.35rem 0.6rem;
    font-size: 0.7rem;
}

/* Compact Table */
.adjustment-table {
    font-size: 0.7rem;
}

.adjustment-table thead th {
    padding: 0.3rem 0.4rem;
    font-size: 0.65rem;
    line-height: 1.1;
    white-space: nowrap;
    font-weight: 600;
}

.adjustment-table tbody td {
    padding: 0.3rem 0.4rem;
    font-size: 0.7rem;
    line-height: 1.3;
}

.adjustment-table .cell-value {
    white-space: nowrap;
}

.adjustment-table .cell-product {
    min-width: 150px;
}

/* Responsive Header */
.responsive-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
}
@media (min-width: 640px) {
    .responsive-header {
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        gap: 0;
    }
}

/* Tablet Responsive */
@media (max-width: 1024px) {
    .responsive-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    .form-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

/* Mobile Responsive */
@media (max-width: 640px) {
    .responsive-grid {
        grid-template-columns: 1fr;
    }
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .page-header h1 {
        font-size: 1rem;
    }
    
    .page-subtitle {
        font-size: 0.7rem;
    }
    
    .card {
        padding: 0.5rem;
    }
    
    .adjustment-table thead th {
        padding: 0.25rem 0.3rem;
        font-size: 0.6rem;
    }
    
    .adjustment-table tbody td {
        padding: 0.25rem 0.3rem;
        font-size: 0.65rem;
    }
    
    .btn-sm {
        padding: 0.3rem 0.5rem;
        font-size: 0.65rem;
    }
    
    .form-control {
        padding: 0.35rem 0.5rem;
        font-size: 0.7rem;
    }
    
    .card-title {
        font-size: 0.8rem;
    }
}

/* Card view on mobile for table */
@media (max-width: 768px) {
    .adjustment-table thead {
        display: none;
    }

    .adjustment-table,
    .adjustment-table tbody,
    .adjustment-table tr,
    .adjustment-table td {
        display: block;
        width: 100%;
    }

    .adjustment-table tbody tr {
        border-bottom: 1px solid #e5e7eb;
        padding: 0.35rem 0;
    }

    .adjustment-table tbody td {
        display: flex;
        justify-content: space-between;
        gap: 0.75rem;
        align-items: flex-start;
        border: 0;
        padding: 0.25rem 0;
        text-align: right;
        font-size: 0.65rem;
    }

    .adjustment-table tbody td::before {
        content: attr(data-label);
        font-weight: 600;
        color: #6b7280;
        text-align: left;
        font-size: 0.6rem;
        min-width: 80px;
    }
}
</style>

<!-- Header Form -->
<div class="card mb-3">
    <div class="card-header">
        <h3 class="card-title">Adjustment Details</h3>
    </div>
    <form action="<?= APP_URL ?>/inventory/adjust" method="POST" id="adjustmentForm">
        <?= Security::csrfField() ?>
        
        <div class="responsive-grid gap-2 form-grid p-2">
            <div class="form-group">
                <label class="form-label">Business Location <span class="required">*</span></label>
                <select name="location_id" class="form-control" required>
                    <option value="">Select Location...</option>
                    <?php foreach ($locations as $l): ?>
                        <option value="<?= $l['id'] ?>"><?= e($l['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label">Reference No</label>
                <input type="text" name="reference_no" class="form-control" value="ADJ-<?= date('Ymd-His') ?>" readonly>
            </div>
            
            <div class="form-group">
                <label class="form-label">Date <span class="required">*</span></label>
                <input type="date" name="adjustment_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
        </div>
    </form>
</div>

<!-- Product Search -->
<div class="card mb-3">
    <div class="card-header">
        <h3 class="card-title">Add Products</h3>
    </div>
    <div class="p-2">
        <div class="form-group">
            <label class="form-label">Search Product</label>
            <input type="text" id="productSearch" class="form-control" placeholder="Search by name or SKU..." autocomplete="off">
            <div id="searchResults" class="search-results" style="display: none; position: absolute; z-index: 1000; background: white; border: 1px solid #e5e7eb; border-radius: 4px; max-height: 200px; overflow-y: auto; width: 100%; box-shadow: 0 4px 6px rgba(0,0,0,0.1); margin-top: 0.25rem;"></div>
        </div>
    </div>
</div>

<!-- Products Table -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">Adjustment Items</h3>
    </div>
    <div class="overflow-x-auto">
        <table class="data-table adjustment-table">
            <thead>
                <tr>
                    <th class="text-left cell-product">Product</th>
                    <th class="text-left">SKU</th>
                    <th class="text-center">Type</th>
                    <th class="text-center">Quantity</th>
                    <th class="text-center cell-value">Unit Price</th>
                    <th class="text-center cell-value">Subtotal</th>
                    <th class="text-center">Action</th>
                </tr>
            </thead>
            <tbody id="productsTable">
                <tr>
                    <td colspan="7" class="text-center text-muted py-4">No products added yet</td>
                </tr>
            </tbody>
            <tfoot>
                <tr class="font-bold bg-gray-50">
                    <td colspan="5" class="text-right">Total Amount:</td>
                    <td class="text-center text-blue-600" id="totalAmount">0.00</td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
    
    <div class="p-2 flex justify-end gap-2 mt-2">
        <button type="button" onclick="clearAll()" class="btn btn-outline btn-sm">Clear All</button>
        <button type="button" onclick="submitAdjustment()" class="btn btn-primary btn-sm">Process Adjustment</button>
    </div>
</div>

<script>
let adjustmentItems = [];
let allProducts = <?= json_encode($products) ?>;

// Load saved items from localStorage on page load
function loadSavedItems() {
    const saved = localStorage.getItem('adjustmentItems');
    if (saved) {
        try {
            adjustmentItems = JSON.parse(saved);
            updateTable();
        } catch (e) {
            console.error('Error loading saved items:', e);
            localStorage.removeItem('adjustmentItems');
        }
    }
}

// Save items to localStorage
function saveItems() {
    localStorage.setItem('adjustmentItems', JSON.stringify(adjustmentItems));
}

// Load saved items when page loads
document.addEventListener('DOMContentLoaded', loadSavedItems);

function updateTable() {
    const tbody = document.getElementById('productsTable');
    const totalAmountEl = document.getElementById('totalAmount');
    
    if (adjustmentItems.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-4">No products added yet</td></tr>';
        totalAmountEl.textContent = '0.00';
        return;
    }
    
    let total = 0;
    tbody.innerHTML = adjustmentItems.map((item, index) => {
        const subtotal = item.quantity * item.price;
        total += subtotal;
        return `
            <tr>
                <td class="text-left cell-product" data-label="Product">${item.name}</td>
                <td class="text-left" data-label="SKU">${item.sku}</td>
                <td class="text-center" data-label="Type">
                    <select onchange="updateType(${index}, this.value)" class="form-control" style="padding: 0.25rem 0.5rem; font-size: 0.7rem;">
                        <option value="add" ${item.type === 'add' ? 'selected' : ''}>Add (+)</option>
                        <option value="subtract" ${item.type === 'subtract' ? 'selected' : ''}>Subtract (-)</option>
                        <option value="set" ${item.type === 'set' ? 'selected' : ''}>Set (=)</option>
                    </select>
                </td>
                <td class="text-center" data-label="Quantity">
                    <input type="number" step="0.01" min="0.01" value="${item.quantity}" 
                           onchange="updateQuantity(${index}, this.value)" 
                           class="form-control" style="width: 80px; padding: 0.25rem 0.5rem;">
                </td>
                <td class="text-center cell-value" data-label="Unit Price">${item.price.toFixed(2)}</td>
                <td class="text-center cell-value" data-label="Subtotal">${subtotal.toFixed(2)}</td>
                <td class="text-center" data-label="Action">
                    <button type="button" onclick="removeProduct(${index})" class="btn btn-outline btn-sm text-red-600">Remove</button>
                </td>
            </tr>
        `;
    }).join('');
    
    totalAmountEl.textContent = total.toFixed(2);
}

function updateQuantity(index, value) {
    adjustmentItems[index].quantity = parseFloat(value) || 1;
    saveItems();
    updateTable();
}

function removeProduct(index) {
    adjustmentItems.splice(index, 1);
    saveItems();
    updateTable();
}

function clearAll() {
    if (confirm('Are you sure you want to clear all products?')) {
        adjustmentItems = [];
        saveItems();
        updateTable();
    }
}

function submitAdjustment() {
    if (adjustmentItems.length === 0) {
        alert('Please add at least one product');
        return;
    }
    
    const form = document.getElementById('adjustmentForm');
    const locationId = form.querySelector('[name="location_id"]').value;
    
    if (!locationId || locationId === '') {
        alert('Please select a business location');
        return;
    }
    
    const formData = new FormData(form);
    
    // Add products as JSON
    formData.append('items', JSON.stringify(adjustmentItems));
    
    fetch(form.action, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            localStorage.removeItem('adjustmentItems');
            alert('Stock adjustment processed successfully');
            window.location.href = '<?= APP_URL ?>/inventory';
        } else {
            alert('Error: ' + (data.message || 'Failed to process adjustment'));
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
    });
}

// Product search autocomplete functionality
document.getElementById('productSearch').addEventListener('input', function(e) {
    const search = e.target.value.toLowerCase();
    const resultsDiv = document.getElementById('searchResults');
    
    if (search.length < 2) {
        resultsDiv.style.display = 'none';
        return;
    }
    
    const filteredProducts = allProducts.filter(p => 
        p.name.toLowerCase().includes(search) || 
        p.sku.toLowerCase().includes(search)
    );
    
    if (filteredProducts.length === 0) {
        resultsDiv.innerHTML = '<div class="p-2 text-muted text-sm">No products found</div>';
        resultsDiv.style.display = 'block';
        return;
    }
    
    resultsDiv.innerHTML = filteredProducts.map(p => `
        <div class="search-result-item cursor-pointer hover:bg-gray-100 border-b" 
             onclick="selectProduct(${p.id})" 
             style="font-size: 0.75rem; padding: 0.5rem 0.75rem; margin: 0;">
            <div class="font-semibold" style="margin-bottom: 0.25rem;">${p.name}</div>
            <div class="text-muted text-xs">SKU: ${p.sku} | Price: ${parseFloat(p.cost_price).toFixed(2)}</div>
        </div>
    `).join('');
    
    resultsDiv.style.display = 'block';
});

function selectProduct(productId) {
    const product = allProducts.find(p => p.id === productId);
    
    const adjustmentItem = {
        id: product.id,
        name: product.name,
        sku: product.sku,
        price: parseFloat(product.cost_price) || 0,
        quantity: 1,
        type: 'add'
    };
    
    // Check if product already exists
    const existingIndex = adjustmentItems.findIndex(item => item.id === product.id);
    if (existingIndex >= 0) {
        const item = adjustmentItems[existingIndex];
        item.quantity += 1;
        adjustmentItems.splice(existingIndex, 1);
        adjustmentItems.unshift(item);
    } else {
        adjustmentItems.unshift(adjustmentItem);
    }
    
    saveItems();
    updateTable();
    document.getElementById('productSearch').value = '';
    document.getElementById('searchResults').style.display = 'none';
}

function updateType(index, value) {
    adjustmentItems[index].type = value;
    saveItems();
}

// Hide search results when clicking outside
document.addEventListener('click', function(e) {
    const searchContainer = document.querySelector('.form-group');
    if (!searchContainer.contains(e.target)) {
        document.getElementById('searchResults').style.display = 'none';
    }
});
</script>
