<?php
session_start();
include("layout.php");
include("db.php");

// Get stores list
$stores_query = "SELECT * FROM stores WHERE is_active = 1 ORDER BY store_name";
$stores_result = $conn->query($stores_query);

// Get items with stock for the quick add interface
$items_query = "
    SELECT i.id, i.name, i.item_code, i.item_role, c.name as category_name,
           COALESCE(
               (SELECT SUM(CASE WHEN im.movement_type = 'in' THEN im.quantity ELSE 0 END) -
                       SUM(CASE WHEN im.movement_type = 'out' THEN im.quantity ELSE 0 END) +
                       SUM(CASE WHEN im.movement_type = 'adjustment' THEN im.quantity ELSE 0 END)
                FROM inventory_movements im 
                WHERE im.item_id = i.id AND (im.store_id = 1 OR im.store_id IS NULL)
               ), 0
           ) as current_stock, i.cost_price
    FROM items i
    LEFT JOIN categories c ON i.category_id = c.id
    WHERE i.item_role IN ('stock', 'material')
    ORDER BY i.name
";
$items_result = $conn->query($items_query);

// Handle transfer request submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_transfer') {
    $from_store_id = $_POST['from_store_id'];
    $to_store_id = $_POST['to_store_id'];
    $notes = $_POST['notes'];
    $item_ids = $_POST['item_ids'];
    $quantities = $_POST['quantities'];
    $remarks = $_POST['remarks'];
    
    // Generate transfer number
    $transfer_number = 'TRF-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    // Calculate totals
    $total_items = count($item_ids);
    $total_quantity = 0;
    foreach ($quantities as $qty) {
        $total_quantity += floatval($qty);
    }
    
    // Insert transfer record
    $stmt = $conn->prepare("
        INSERT INTO stock_transfers (transfer_number, from_store_id, to_store_id, transfer_date, status, total_items, total_quantity, notes, requested_by)
        VALUES (?, ?, ?, NOW(), 'pending', ?, ?, ?, ?)
    ");
    $user_id = $_SESSION['user_id'] ?? 1; // Get from session
    $stmt->bind_param("siiidsi", $transfer_number, $from_store_id, $to_store_id, $total_items, $total_quantity, $notes, $user_id);
    $stmt->execute();
    $transfer_id = $conn->insert_id;
    $stmt->close();
    
    // Insert transfer items
    foreach ($item_ids as $index => $item_id) {
        if (floatval($quantities[$index]) > 0) {
            $item_name = $_POST['item_names'][$index];
            $quantity = floatval($quantities[$index]);
            $cost_price = floatval($_POST['cost_prices'][$index]);
            $item_remarks = $remarks[$index];
            
            $stmt = $conn->prepare("
                INSERT INTO stock_transfer_items (to_store_id, from_store_id, transfer_id, item_id, item_name, quantity, cost_price, remarks)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param("iiiisids", $to_store_id, $from_store_id, $transfer_id, $item_id, $item_name, $quantity, $cost_price, $item_remarks);
            $stmt->execute();
            $stmt->close();
        }
    }
    
    header("Location: stock_transfer_approval.php?success=1&transfer_id=" . $transfer_id);
    exit;
}
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>Stock Transfer Request</h4>
                <h6>Create a new stock transfer between stores</h6>
            </div>
            <div class="d-flex gap-2">
                <a href="stock_transfer_approval.php" class="btn btn-outline-primary">
                    <i class="fas fa-list"></i> View Transfers
                </a>
            </div>
        </div>

        <form method="POST" id="transferForm">
            <input type="hidden" name="action" value="create_transfer">
            
            <!-- Transfer Details -->
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">Transfer Details</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>From Store *</label>
                                <select name="from_store_id" class="form-control" id="fromStoreSelect" required>
                                    <option value="">Select Source Store</option>
                                    <?php 
                                    $stores_result->data_seek(0); // Reset result pointer
                                    while ($store = $stores_result->fetch_assoc()): 
                                    ?>
                                        <option value="<?= $store['id'] ?>"><?= htmlspecialchars($store['store_name']) ?> (<?= htmlspecialchars($store['store_code']) ?>)</option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>To Store *</label>
                                <select name="to_store_id" class="form-control" required>
                                    <option value="">Select Destination Store</option>
                                    <?php 
                                    $stores_result->data_seek(0);
                                    while ($store = $stores_result->fetch_assoc()): 
                                    ?>
                                        <option value="<?= $store['id'] ?>"><?= htmlspecialchars($store['store_name']) ?> (<?= htmlspecialchars($store['store_code']) ?>)</option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Notes</label>
                        <textarea name="notes" class="form-control" rows="2" placeholder="Enter transfer notes..."></textarea>
                    </div>
                </div>
            </div>

            <!-- Selected Items -->
            <div class="card" id="selectedItemsCard" style="display: none;">
                <div class="card-header">
                    <h5 class="card-title">Selected Items for Transfer</h5>
                </div>
                <div class="card-body">
                    <div id="selectedItemsList">
                        <!-- Selected items will be added here dynamically -->
                    </div>
                    
                    <div class="text-end mt-3">
                        <span class="text-muted">Total Items: <span id="selectedCount">0</span></span>
                    </div>
                </div>
            </div>

            <!-- Submit Button -->
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <span class="text-muted">Selected Items: <span id="selectedCount2">0</span></span>
                        </div>
                        <div>
                            <button type="button" class="btn btn-secondary me-2" onclick="history.back()">Cancel</button>
                            <button type="submit" class="btn btn-primary" id="submitBtn" disabled>
                                <i class="fas fa-paper-plane"></i> Submit Transfer Request
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Add Items Section -->
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">Add Items to Transfer</h5>
                </div>
                <div class="card-body">
                    <!-- Search and Filter -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Search Items</label>
                                <input type="text" id="itemSearch" class="form-control" placeholder="Type item name to search...">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>Category Filter</label>
                                <select id="categoryFilter" class="form-control">
                                    <option value="">All Categories</option>
                                    <?php
                                    $categories_query = "SELECT DISTINCT c.name FROM categories c 
                                                       INNER JOIN items i ON c.id = i.category_id 
                                                       WHERE i.item_role IN ('stock', 'material') 
                                                       ORDER BY c.name";
                                    $categories_result = $conn->query($categories_query);
                                    while ($category = $categories_result->fetch_assoc()):
                                    ?>
                                        <option value="<?= htmlspecialchars($category['name']) ?>"><?= htmlspecialchars($category['name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>Stock Filter</label>
                                <select id="stockFilter" class="form-control">
                                    <option value="">All Items</option>
                                    <option value="in_stock">In Stock</option>
                                    <option value="low_stock">Low Stock</option>
                                    <option value="out_of_stock">Out of Stock</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Items Grid -->
                    <div class="row" id="itemsGrid">
                        <?php while ($item = $items_result->fetch_assoc()): ?>
                            <div class="col-md-4 col-lg-3 mb-3 item-card" 
                                 data-name="<?= strtolower(htmlspecialchars($item['name'])) ?>"
                                 data-category="<?= htmlspecialchars($item['category_name']) ?>"
                                 data-stock="<?= $item['current_stock'] > 0 ? ($item['current_stock'] < 10 ? 'low_stock' : 'in_stock') : 'out_of_stock' ?>">
                                <div class="card h-100 item-card-inner">
                                    <div class="card-body text-center">
                                        <div class="item-icon mb-2">
                                            <i class="fas fa-box text-primary fa-2x"></i>
                                        </div>
                                        <h6 class="card-title"><?= htmlspecialchars($item['name']) ?></h6>
                                        <p class="text-muted small mb-2"><?= htmlspecialchars($item['item_code']) ?></p>
                                        <span class="badge bg-secondary mb-2"><?= htmlspecialchars($item['category_name']) ?></span>
                                        
                                        <div class="stock-info mb-3">
                                            <?php
                                            $stock_class = 'bg-success';
                                            $stock_text = 'In Stock';
                                            if ($item['current_stock'] <= 0) {
                                                $stock_class = 'bg-danger';
                                                $stock_text = 'Out of Stock';
                                            } elseif ($item['current_stock'] < 10) {
                                                $stock_class = 'bg-warning';
                                                $stock_text = 'Low Stock';
                                            }
                                            ?>
                                            <span class="badge <?= $stock_class ?>">
                                                <?= number_format($item['current_stock'], 2) ?>
                                            </span>
                                        </div>
                                        
                                        <button type="button" class="btn btn-primary btn-sm add-item-btn" 
                                                data-item-id="<?= $item['id'] ?>"
                                                data-item-name="<?= htmlspecialchars($item['name']) ?>"
                                                data-item-code="<?= htmlspecialchars($item['item_code']) ?>"
                                                data-current-stock="<?= $item['current_stock'] ?>"
                                                data-cost-price="<?= $item['cost_price'] ?>"
                                                <?= $item['current_stock'] <= 0 ? 'disabled' : '' ?>>
                                            <i class="fas fa-plus"></i> Add to Transfer
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const itemSearch = document.getElementById('itemSearch');
    const categoryFilter = document.getElementById('categoryFilter');
    const stockFilter = document.getElementById('stockFilter');
    const itemsGrid = document.getElementById('itemsGrid');
    const selectedItemsCard = document.getElementById('selectedItemsCard');
    const selectedItemsList = document.getElementById('selectedItemsList');
    const selectedCount = document.getElementById('selectedCount');
    const selectedCount2 = document.getElementById('selectedCount2');
    const submitBtn = document.getElementById('submitBtn');
    
    let selectedItems = [];
    
    // Update stock levels when store changes
    document.getElementById('fromStoreSelect').addEventListener('change', function() {
        const storeId = this.value;
        if (storeId) {
            updateStockLevels(storeId);
        }
    });
    
    // Function to update stock levels via AJAX
    function updateStockLevels(storeId) {
        fetch(`ajax/get_store_stock.php?store_id=${storeId}`)
            .then(response => response.json())
            .then(data => {
                data.forEach(item => {
                    const itemCard = document.querySelector(`[data-item-id="${item.id}"]`).closest('.item-card');
                    if (itemCard) {
                        const stockBadge = itemCard.querySelector('.badge');
                        const addButton = itemCard.querySelector('.add-item-btn');
                        
                        // Update stock display
                        let stockClass = 'bg-success';
                        let stockText = 'In Stock';
                        if (item.current_stock <= 0) {
                            stockClass = 'bg-danger';
                            stockText = 'Out of Stock';
                        } else if (item.current_stock < 10) {
                            stockClass = 'bg-warning';
                            stockText = 'Low Stock';
                        }
                        
                        stockBadge.className = `badge ${stockClass}`;
                        stockBadge.textContent = `${item.current_stock.toFixed(2)}`;
                        
                        // Update button state
                        addButton.disabled = item.current_stock <= 0;
                        addButton.dataset.currentStock = item.current_stock;
                        
                        // Update data attributes
                        itemCard.dataset.stock = item.current_stock;
                    }
                });
            })
            .catch(error => {
                console.error('Error updating stock levels:', error);
            });
    }
    
    // Search and filter functionality
    function filterItems() {
        const searchTerm = itemSearch.value.toLowerCase();
        const categoryFilterValue = categoryFilter.value;
        const stockFilterValue = stockFilter.value;
        
        const itemCards = document.querySelectorAll('.item-card');
        
        itemCards.forEach(card => {
            const name = card.dataset.name;
            const category = card.dataset.category;
            const stock = card.dataset.stock;
            
            let show = true;
            
            // Search filter
            if (searchTerm && !name.includes(searchTerm)) {
                show = false;
            }
            
            // Category filter
            if (categoryFilterValue && category !== categoryFilterValue) {
                show = false;
            }
            
            // Stock filter
            if (stockFilterValue && stock !== stockFilterValue) {
                show = false;
            }
            
            card.style.display = show ? 'block' : 'none';
        });
    }
    
    itemSearch.addEventListener('input', filterItems);
    categoryFilter.addEventListener('change', filterItems);
    stockFilter.addEventListener('change', filterItems);
    
    // Add item functionality
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('add-item-btn')) {
            const btn = e.target;
            const itemId = btn.dataset.itemId;
            const itemName = btn.dataset.itemName;
            const itemCode = btn.dataset.itemCode;
            const currentStock = parseFloat(btn.dataset.currentStock);
            const costPrice = parseFloat(btn.dataset.costPrice);
            
            // Check if item is already selected
            if (selectedItems.find(item => item.id === itemId)) {
                alert('This item is already in your transfer list!');
                return;
            }
            
            // Add to selected items
            selectedItems.push({
                id: itemId,
                name: itemName,
                code: itemCode,
                currentStock: currentStock,
                costPrice: costPrice,
                quantity: 0
            });
            
            updateSelectedItemsDisplay();
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-check"></i> Added';
            btn.classList.remove('btn-primary');
            btn.classList.add('btn-success');
        }
    });
    
    // Update selected items display
    function updateSelectedItemsDisplay() {
        if (selectedItems.length === 0) {
            selectedItemsCard.style.display = 'none';
        } else {
            selectedItemsCard.style.display = 'block';
            selectedItemsList.innerHTML = '';
            
                         selectedItems.forEach((item, index) => {
                 const itemHtml = `
                     <div class="row mb-3 align-items-center selected-item" data-index="${index}">
                         <div class="col-md-3">
                             <strong>${item.name}</strong>
                             <br><small class="text-muted">${item.code}</small>
                         </div>
                         <div class="col-md-2">
                             <span class="badge bg-info">${item.currentStock} units available</span>
                         </div>
                         <div class="col-md-2">
                             <label class="form-label small text-muted mb-1">Transfer Quantity</label>
                             <input type="number" class="form-control form-control-sm quantity-input" 
                                    placeholder="Enter quantity to transfer" min="0" max="${item.currentStock}" step="0.01"
                                    value="${item.quantity}" data-index="${index}">
                         </div>
                         <div class="col-md-2">
                             <label class="form-label small text-muted mb-1">Cost Price</label>
                             <input type="number" class="form-control form-control-sm cost-input" 
                                    placeholder="Enter cost price" min="0" step="0.01"
                                    value="${item.costPrice}" data-index="${index}">
                         </div>
                         <div class="col-md-2">
                             <label class="form-label small text-muted mb-1">Remarks</label>
                             <input type="text" class="form-control form-control-sm remarks-input" 
                                    placeholder="Enter any notes" data-index="${index}">
                         </div>
                         <div class="col-md-1">
                             <label class="form-label small text-muted mb-1">&nbsp;</label>
                             <button type="button" class="btn btn-danger btn-sm remove-item" data-index="${index}">
                                 <i class="fas fa-times"></i>
                             </button>
                         </div>
                     </div>
                 `;
                selectedItemsList.innerHTML += itemHtml;
            });
        }
        
        selectedCount.textContent = selectedItems.length;
        selectedCount2.textContent = selectedItems.length;
        submitBtn.disabled = selectedItems.length === 0;
    }
    
    // Handle quantity input changes
    selectedItemsList.addEventListener('input', function(e) {
        if (e.target.classList.contains('quantity-input')) {
            const index = parseInt(e.target.dataset.index);
            const quantity = parseFloat(e.target.value) || 0;
            selectedItems[index].quantity = quantity;
        } else if (e.target.classList.contains('cost-input')) {
            const index = parseInt(e.target.dataset.index);
            const cost = parseFloat(e.target.value) || 0;
            selectedItems[index].costPrice = cost;
        } else if (e.target.classList.contains('remarks-input')) {
            const index = parseInt(e.target.dataset.index);
            const remarks = e.target.value;
            selectedItems[index].remarks = remarks;
        }
    });
    
    // Remove item functionality
    selectedItemsList.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-item') || e.target.closest('.remove-item')) {
            const btn = e.target.classList.contains('remove-item') ? e.target : e.target.closest('.remove-item');
            const index = parseInt(btn.dataset.index);
            const itemId = selectedItems[index].id;
            
            // Remove from selected items
            selectedItems.splice(index, 1);
            
            // Re-enable the add button
            const addBtn = document.querySelector(`[data-item-id="${itemId}"]`);
            if (addBtn) {
                addBtn.disabled = false;
                addBtn.innerHTML = '<i class="fas fa-plus"></i> Add to Transfer';
                addBtn.classList.remove('btn-success');
                addBtn.classList.add('btn-primary');
            }
            
            updateSelectedItemsDisplay();
        }
    });
    
    // Form validation
    document.getElementById('transferForm').addEventListener('submit', function(e) {
        const fromStore = document.querySelector('select[name="from_store_id"]').value;
        const toStore = document.querySelector('select[name="to_store_id"]').value;
        
        if (fromStore === toStore) {
            e.preventDefault();
            alert('Source and destination stores cannot be the same!');
            return false;
        }
        
        if (selectedItems.length === 0) {
            e.preventDefault();
            alert('Please select at least one item to transfer!');
            return false;
        }
        
        // Check if quantities are entered for selected items
        let hasQuantity = false;
        selectedItems.forEach(item => {
            if (item.quantity > 0) {
                hasQuantity = true;
            }
        });
        
        if (!hasQuantity) {
            e.preventDefault();
            alert('Please enter transfer quantities for selected items!');
            return false;
        }
        
        // Prepare form data
        selectedItems.forEach((item, index) => {
            // Add hidden inputs for form submission
            const itemIdInput = document.createElement('input');
            itemIdInput.type = 'hidden';
            itemIdInput.name = 'item_ids[]';
            itemIdInput.value = item.id;
            this.appendChild(itemIdInput);
            
            const itemNameInput = document.createElement('input');
            itemNameInput.type = 'hidden';
            itemNameInput.name = 'item_names[]';
            itemNameInput.value = item.name;
            this.appendChild(itemNameInput);
            
            const quantityInput = document.createElement('input');
            quantityInput.type = 'hidden';
            quantityInput.name = 'quantities[]';
            quantityInput.value = item.quantity;
            this.appendChild(quantityInput);
            
            const costInput = document.createElement('input');
            costInput.type = 'hidden';
            costInput.name = 'cost_prices[]';
            costInput.value = item.costPrice;
            this.appendChild(costInput);
            
            const remarksInput = document.createElement('input');
            remarksInput.type = 'hidden';
            remarksInput.name = 'remarks[]';
            remarksInput.value = item.remarks || '';
            this.appendChild(remarksInput);
        });
    });
});
</script>

<style>
.item-card-inner {
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.item-card-inner:hover {
    border-color: #007bff;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.selected-item {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    border: 1px solid #dee2e6;
}

.quantity-input, .cost-input, .remarks-input {
    font-size: 0.875rem;
}

#itemSearch {
    border-radius: 20px;
}

.item-icon {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
