<div class="page-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>Transfer Stock</h1>
        <div class="page-subtitle">Move products between warehouses or stores</div>
    </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 */
.transfer-table {
    font-size: 0.7rem;
}

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

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

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

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

/* Search Results */
.search-results {
    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;
}

.search-result-item {
    cursor: pointer;
    padding: 0.5rem 0.75rem;
    margin: 0;
}

.search-result-item:hover {
    background-color: #f3f4f6;
}

/* 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;
    }
    
    .transfer-table thead th {
        padding: 0.25rem 0.3rem;
        font-size: 0.6rem;
    }
    
    .transfer-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) {
    .transfer-table thead {
        display: none;
    }

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

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

    .transfer-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;
    }

    .transfer-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">Transfer Details</h3>
    </div>
    <form action="<?= APP_URL ?>/inventory/transfer" method="POST" id="transferForm">
        <?= Security::csrfField() ?>
        
        <div class="responsive-grid gap-2 form-grid p-2">
            <div class="form-group">
                <label class="form-label">Source Location <span class="required">*</span></label>
                <select name="source_id" id="sourceId" class="form-control" required>
                    <option value="">Select Source...</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">Destination Location <span class="required">*</span></label>
                <select name="destination_id" id="destId" class="form-control" required>
                    <option value="">Select Destination...</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="TRF-<?= date('Ymd-His') ?>" readonly>
            </div>
            
            <div class="form-group">
                <label class="form-label">Date <span class="required">*</span></label>
                <input type="date" name="transfer_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;"></div>
        </div>
    </div>
</div>

<!-- Products Table -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">Transfer Items</h3>
    </div>
    <div class="overflow-x-auto">
        <table class="data-table transfer-table">
            <thead>
                <tr>
                    <th class="text-left cell-product">Product</th>
                    <th class="text-left">SKU</th>
                    <th class="text-center">Available</th>
                    <th class="text-center">Quantity</th>
                    <th class="text-center">Action</th>
                </tr>
            </thead>
            <tbody id="productsTable">
                <tr>
                    <td colspan="5" class="text-center text-muted py-4">No products added yet</td>
                </tr>
            </tbody>
            <tfoot>
                <tr class="font-bold bg-gray-50">
                    <td colspan="3" class="text-right">Total Items:</td>
                    <td class="text-center text-blue-600" id="totalItems">0</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="submitTransfer()" class="btn btn-primary btn-sm">Process Transfer</button>
    </div>
</div>

<script>
const allProducts = <?= json_encode($products, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
let transferItems = [];
const STOCK_INFO_URL = '<?= APP_URL ?>/api/stock-info';

// Load saved items from localStorage
function loadSavedItems() {
    const saved = localStorage.getItem('transferItems');
    if (saved) {
        transferItems = JSON.parse(saved);
        updateTable();
    }
}

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

// Product search autocomplete
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 sourceId = document.getElementById('sourceId').value;
    if (!sourceId) {
        alert('Please select a source location first');
        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="search-result-item 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}</div>
        </div>
    `).join('');
    
    resultsDiv.style.display = 'block';
});

async function selectProduct(productId) {
    const product = allProducts.find(p => p.id === productId);
    const sourceId = document.getElementById('sourceId').value;
    
    if (!sourceId) {
        alert('Please select a source location first');
        return;
    }
    
    // Get available stock
    try {
        const url = STOCK_INFO_URL + '?product_id=' + productId + '&location_id=' + sourceId;
        console.log('Requesting URL:', url);
        console.log('STOCK_INFO_URL:', STOCK_INFO_URL);
        
        const response = await fetch(url);
        console.log('Response status:', response.status);
        console.log('Response ok:', response.ok);
        
        const data = await response.json();
        console.log('Stock info response:', data);
        
        if (data.error) {
            alert('Error: ' + data.error);
            return;
        }
        
        const availableStock = data.stock !== undefined ? parseFloat(data.stock) : 0;
        
        console.log('Product:', product.name, 'Available stock:', availableStock);
        
        if (availableStock <= 0) {
            alert('No stock available at source location. Available: ' + availableStock);
            return;
        }
        
        const transferItem = {
            id: product.id,
            name: product.name,
            sku: product.sku,
            available: availableStock,
            quantity: 1
        };
        
        // Check if product already exists
        const existingIndex = transferItems.findIndex(item => item.id === product.id);
        if (existingIndex >= 0) {
            const item = transferItems[existingIndex];
            item.quantity += 1;
            transferItems.splice(existingIndex, 1);
            transferItems.unshift(item);
        } else {
            transferItems.unshift(transferItem);
        }
        
        saveItems();
        updateTable();
        document.getElementById('productSearch').value = '';
        document.getElementById('searchResults').style.display = 'none';
    } catch (error) {
        console.error('Error loading stock info:', error);
        alert('Error loading stock information: ' + error.message);
    }
}

function updateTable() {
    const tbody = document.getElementById('productsTable');
    const totalItemsEl = document.getElementById('totalItems');
    
    if (transferItems.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted py-4">No products added yet</td></tr>';
        totalItemsEl.textContent = '0';
        return;
    }
    
    tbody.innerHTML = transferItems.map((item, index) => {
        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="Available">${item.available.toFixed(2)}</td>
                <td class="text-center" data-label="Quantity">
                    <input type="number" step="0.01" min="0.01" max="${item.available}" value="${item.quantity}" 
                           onchange="updateQuantity(${index}, this.value)" 
                           class="form-control" style="width: 80px; padding: 0.25rem 0.5rem;">
                </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('');
    
    totalItemsEl.textContent = transferItems.length;
}

function updateQuantity(index, value) {
    const qty = parseFloat(value) || 1;
    const available = transferItems[index].available;
    
    if (qty > available) {
        alert(`Cannot transfer more than available stock (${available})`);
        document.querySelector(`#productsTable tr:nth-child(${index + 1}) input`).value = transferItems[index].quantity;
        return;
    }
    
    transferItems[index].quantity = qty;
    saveItems();
    updateTable();
}

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

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

async function submitTransfer() {
    const sourceId = document.getElementById('sourceId').value;
    const destId = document.getElementById('destId').value;
    
    if (!sourceId || !destId) {
        alert('Please select both source and destination locations');
        return;
    }
    
    if (sourceId === destId) {
        alert('Source and destination must be different');
        return;
    }
    
    if (transferItems.length === 0) {
        alert('Please add at least one product');
        return;
    }
    
    const form = document.getElementById('transferForm');
    const formData = new FormData(form);
    
    // Add products as JSON
    formData.append('items', JSON.stringify(transferItems));
    
    fetch(form.action, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            localStorage.removeItem('transferItems');
            alert('Stock transferred successfully');
            window.location.href = '<?= APP_URL ?>/inventory';
        } else {
            alert('Error: ' + (data.message || 'Failed to process transfer'));
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
    });
}

// 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';
    }
});

// Load saved items on page load
document.addEventListener('DOMContentLoaded', loadSavedItems);
</script>
