<!DOCTYPE html>
<?php
include("layout.php");
include("db.php");
include 'functions/video_help.php';

// Rights checking removed - will be implemented later

// Get selected store filter
$selected_store = isset($_GET['store_id']) ? intval($_GET['store_id']) : ($_SESSION['current_store_id'] ?? 1);

// Get all stores for the filter dropdown
$stores_query = "SELECT id, store_name, store_code FROM stores WHERE is_active = 1 ORDER BY store_name";
$stores_result = $conn->query($stores_query);

// Items will be loaded dynamically via search
?>

<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 Adjustment</h4>
                <h6>Adjust stock quantities and track cost impact</h6>
            </div>
            <div class="d-flex gap-2">
                <?= display_video_help_button('stock_adjustment', $conn, '<i class="fa fa-play-circle"></i> Watch Video', 'btn-outline-primary') ?>
                <a href="stock_adjustment_list.php" class="btn btn-info">
                    <i class="fa fa-history"></i> Adjustment History
                </a>
            </div>
        </div>

        <!-- Store Filter -->
        <div class="card mb-3">
            <div class="card-body">
                <form method="GET" action="" class="row align-items-end">
                    <div class="col-md-4">
                        <label for="store_filter" class="form-label">Select Store</label>
                        <select name="store_id" id="store_filter" class="form-control" onchange="this.form.submit()">
                            <?php while ($store = $stores_result->fetch_assoc()) : ?>
                                <option value="<?= $store['id'] ?>" <?= ($store['id'] == $selected_store) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($store['store_name']) ?> (<?= htmlspecialchars($store['store_code']) ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fa fa-filter"></i> Apply Filter
                        </button>
                    </div>
                    <div class="col-md-6 text-end">
                        <small class="text-muted">
                            <i class="fa fa-info-circle"></i> 
                            Adjusting stock for: 
                            <strong>
                                <?php 
                                $stores_result->data_seek(0);
                                while ($store = $stores_result->fetch_assoc()) {
                                    if ($store['id'] == $selected_store) {
                                        echo htmlspecialchars($store['store_name']);
                                        break;
                                    }
                                }
                                ?>
                            </strong>
                        </small>
                    </div>
                </form>
            </div>
        </div>

        <!-- Stock Adjustment Form -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-edit"></i> Create Stock Adjustment
                </h5>
            </div>
            <div class="card-body">
                <form id="stockAdjustmentForm" method="POST" action="handlers/stock_adjustment_handler.php">
                    <input type="hidden" name="store_id" value="<?= $selected_store ?>">
                    
                    <!-- General Remarks -->
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <label for="remarks" class="form-label">General Remarks</label>
                            <textarea name="remarks" id="remarks" class="form-control" rows="2" placeholder="Enter any general remarks for this adjustment..."></textarea>
                        </div>
                    </div>

                    <!-- Items Selection -->
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <label class="form-label">Search Items to Adjust</label>
                            <div class="position-relative">
                                <input type="text" id="itemSearchInput" class="form-control" placeholder="Type item name or code to search...">
                                <div id="searchDropdown" class="position-absolute w-100 bg-white border rounded shadow-sm" style="top: 100%; left: 0; z-index: 1050; max-height: 300px; overflow-y: auto; display: none;">
                                    <!-- Search results will be populated here -->
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label>&nbsp;</label>
                            <div>
                                <!-- Browse feature removed to simplify interface -->
                            </div>
                        </div>
                    </div>

                    <!-- Items Table -->
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="itemsTable">
                                                         <thead class="table-light">
                                 <tr>
                                     <th width="5%">Action</th>
                                     <th width="25%">Item Name</th>
                                     <th width="8%">Type</th>
                                     <th width="10%">Current Stock</th>
                                     <th width="10%">Cost Price</th>
                                     <th width="10%">Current Value</th>
                                     <th width="12%">Actual Quantity</th>
                                     <th width="10%">Adjustment</th>
                                     <th width="10%">Adjustment Value</th>
                                     <th width="10%">New Value</th>
                                 </tr>
                             </thead>
                            <tbody id="adjustmentItemsTable">
                                <!-- Items will be added here dynamically -->
                            </tbody>
                        </table>
                    </div>

                    <!-- Summary Section -->
                    <div class="row mt-4">
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title">Adjustment Summary</h6>
                                    <div class="row">
                                        <div class="col-6">
                                            <strong>Total Items:</strong>
                                        </div>
                                        <div class="col-6 text-end">
                                            <span id="totalItems">0</span>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-6">
                                            <strong>Total Adjustment Value:</strong>
                                        </div>
                                        <div class="col-6 text-end">
                                            <span id="totalAdjustmentValue" class="text-primary">0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title">Stock Value Impact</h6>
                                    <div class="row">
                                        <div class="col-6">
                                            <strong>Current Stock Value:</strong>
                                        </div>
                                        <div class="col-6 text-end">
                                            <span id="totalCurrentValue">0.00</span>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-6">
                                            <strong>New Stock Value:</strong>
                                        </div>
                                        <div class="col-6 text-end">
                                            <span id="totalNewValue">0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div class="row mt-4">
                        <div class="col-12 text-end">
                            <button type="button" class="btn btn-secondary me-2" onclick="resetForm()">
                                <i class="fa fa-refresh"></i> Reset
                            </button>
                            <button type="submit" class="btn btn-primary" id="submitBtn" disabled>
                                <i class="fa fa-save"></i> Process Adjustment
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>



<script>
let allItems = [];
let searchTimeout;
let selectedIndex = -1;
let searchResults = [];

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    updateSummary();
});

// Enhanced search functionality
$('#itemSearchInput').on('input', function() {
    const searchTerm = $(this).val().trim();
    
    clearTimeout(searchTimeout);
    
    if (searchTerm.length < 2) {
        hideDropdown();
        return;
    }
    
    // Show loading state
    showDropdown();
    $('#searchDropdown').html('<div class="p-3 text-center text-muted"><i class="fas fa-spinner fa-spin"></i> Searching...</div>');
    
    searchTimeout = setTimeout(() => {
        searchItems(searchTerm);
    }, 300);
});

// Keyboard navigation
$('#itemSearchInput').on('keydown', function(e) {
    const dropdown = $('#searchDropdown');
    const items = dropdown.find('.search-item');
    
    switch(e.keyCode) {
        case 40: // Down arrow
            e.preventDefault();
            selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
            updateSelection();
            break;
        case 38: // Up arrow
            e.preventDefault();
            selectedIndex = Math.max(selectedIndex - 1, -1);
            updateSelection();
            break;
        case 13: // Enter
            e.preventDefault();
            if (selectedIndex >= 0 && searchResults[selectedIndex]) {
                selectItem(searchResults[selectedIndex]);
            }
            break;
        case 27: // Escape
            hideDropdown();
            break;
    }
});

// Click outside to hide dropdown
$(document).on('click', function(e) {
    if (!$(e.target).closest('#itemSearchInput, #searchDropdown').length) {
        hideDropdown();
    }
});

function searchItems(searchTerm) {
    console.log('Searching for:', searchTerm);
    $.getJSON('search_items_enhanced.php', { q: searchTerm }, function(data) {
        console.log('Search results:', data);
        searchResults = data;
        displaySearchResults(data);
    }).fail(function(xhr, status, error) {
        console.error('Search failed:', error);
        $('#searchDropdown').html('<div class="p-3 text-center text-danger">Error loading results: ' + error + '</div>');
    });
}

function displaySearchResults(results) {
    const dropdown = $('#searchDropdown');
    
    if (results.length === 0) {
        dropdown.html('<div class="p-3 text-center text-muted">No items found</div>');
        return;
    }
    
    let html = '';
    results.forEach((item, index) => {
        html += `
            <div class="search-item p-3 border-bottom" data-index="${index}" style="cursor: pointer;">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <strong>${item.name}</strong>
                        <br><small class="text-muted">${item.item_code}</small>
                    </div>
                    <div class="text-end">
                        <div class="text-primary">${item.cost_price}</div>
                        <small class="text-muted">Stock: ${item.current_stock}</small>
                    </div>
                </div>
            </div>
        `;
    });
    
    dropdown.html(html);
    selectedIndex = -1;
    
    // Add click event to search items
    dropdown.find('.search-item').on('click', function() {
        const index = $(this).data('index');
        if (searchResults[index]) {
            selectItem(searchResults[index]);
        }
    });
}

function updateSelection() {
    $('#searchDropdown .search-item').removeClass('bg-primary text-white');
    if (selectedIndex >= 0) {
        $('#searchDropdown .search-item').eq(selectedIndex).addClass('bg-primary text-white');
    }
}

function selectItem(item) {
    if (!item || !item.id) return;
    
    // Check if item is already in the table
    const existingRow = $(`input[name="item_id[]"][value="${item.id}"]`).closest('tr');
    if (existingRow.length > 0) {
        alert('This item is already in your adjustment list!');
        return;
    }
    
    // Use stock data directly from search results
    const currentStock = parseFloat(item.current_stock) || 0;
    const costPrice = parseFloat(item.cost_price.replace(/,/g, '')) || 0;
    const currentValue = currentStock * costPrice;
    
    let row = $(`
        <tr class="item-row" data-item-id="${item.id}">
            <td>
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">
                    <i class="fas fa-times"></i>
                </button>
                <input type="hidden" name="selected_items[]" value="${item.id}">
                <input type="hidden" name="item_names[${item.id}]" value="${item.name}">
                <input type="hidden" name="item_id[]" value="${item.id}">
            </td>
            <td>
                <strong>${item.name}</strong>
            </td>
            <td>
                <span class="badge ${item.item_type === 'stock' ? 'bg-primary' : 'bg-success'}">
                    ${item.item_type ? item.item_type.charAt(0).toUpperCase() + item.item_type.slice(1) : 'Stock'}
                </span>
            </td>
            <td class="text-end">
                <span class="current-qty">${currentStock.toFixed(2)}</span>
                <input type="hidden" name="current_quantities[${item.id}]" value="${currentStock}">
            </td>
            <td class="text-end">
                <span class="cost-price">${costPrice.toFixed(2)}</span>
                <input type="hidden" name="cost_prices[${item.id}]" value="${costPrice}">
            </td>
            <td class="text-end">
                <span class="current-value">${currentValue.toFixed(2)}</span>
                <input type="hidden" name="current_values[${item.id}]" value="${currentValue}">
            </td>
                         <td>
                 <input type="number" name="desired_quantities[${item.id}]" 
                        class="form-control desired-qty" 
                        step="0.01" 
                        placeholder="Enter quantity"
                        value=""
                        onchange="updateRowCalculations(this)">
             </td>
             <td class="text-end">
                 <span class="adjustment-qty">0.00</span>
                 <input type="hidden" name="adjustment_quantities[${item.id}]" value="0">
             </td>
             <td class="text-end">
                 <span class="adjustment-value">0.00</span>
                 <input type="hidden" name="adjustment_values[${item.id}]" value="0">
             </td>
             <td class="text-end">
                 <span class="new-value">${currentValue.toFixed(2)}</span>
                 <input type="hidden" name="new_values[${item.id}]" value="${currentValue}">
                 <input type="hidden" name="new_quantities[${item.id}]" value="${currentStock}">
             </td>
        </tr>
    `);

    $('#adjustmentItemsTable').append(row);
    
    // Store item data for calculations
    allItems[item.id] = {
        currentQty: currentStock,
        costPrice: costPrice,
        currentValue: currentValue
    };
    
    // Clear search and hide dropdown
    $('#itemSearchInput').val('');
    hideDropdown();
    
    updateSummary();
}

function removeRow(button) {
    const row = $(button).closest('tr');
    const itemId = row.data('item-id');
    
    // Remove from allItems
    delete allItems[itemId];
    
    // Remove row
    row.remove();
    
    updateSummary();
}

function showDropdown() {
    $('#searchDropdown').show();
}

function hideDropdown() {
    $('#searchDropdown').hide();
    selectedIndex = -1;
}



// Update calculations for a specific row
function updateRowCalculations(element) {
    const row = element.closest('.item-row');
    const itemId = row.dataset.itemId;
    const desiredQtyInput = row.querySelector('.desired-qty');
    
    if (desiredQtyInput.value !== '') {
        const desiredQty = parseFloat(desiredQtyInput.value) || 0;
        const currentQty = allItems[itemId].currentQty;
        const adjustmentQty = desiredQty - currentQty;
        const adjustmentValue = adjustmentQty * allItems[itemId].costPrice;
        const newValue = desiredQty * allItems[itemId].costPrice;
        
        // Update row values
        row.querySelector('.adjustment-qty').textContent = adjustmentQty.toFixed(2);
        row.querySelector('.adjustment-value').textContent = adjustmentValue.toFixed(2);
        row.querySelector('.new-value').textContent = newValue.toFixed(2);
        
        // Update hidden inputs
        row.querySelector('input[name="adjustment_quantities[' + itemId + ']"]').value = adjustmentQty;
        row.querySelector('input[name="adjustment_values[' + itemId + ']"]').value = adjustmentValue;
        row.querySelector('input[name="new_values[' + itemId + ']"]').value = newValue;
        row.querySelector('input[name="new_quantities[' + itemId + ']"]').value = desiredQty;
        
        // Add visual styling for adjustment
        const adjustmentSpan = row.querySelector('.adjustment-qty');
        if (adjustmentQty > 0) {
            adjustmentSpan.className = 'adjustment-qty text-success';
        } else if (adjustmentQty < 0) {
            adjustmentSpan.className = 'adjustment-qty text-danger';
        } else {
            adjustmentSpan.className = 'adjustment-qty text-muted';
        }
    }
    
    updateSummary();
}

// Update summary calculations
function updateSummary() {
    let totalItems = 0;
    let totalAdjustmentValue = 0;
    let totalCurrentValue = 0;
    let totalNewValue = 0;
    
    const rows = document.querySelectorAll('.item-row');
    
    rows.forEach(row => {
        const itemId = row.dataset.itemId;
        const desiredQtyInput = row.querySelector('.desired-qty');
        
        if (desiredQtyInput.value !== '') {
            const desiredQty = parseFloat(desiredQtyInput.value) || 0;
            const currentQty = allItems[itemId].currentQty;
            const adjustmentQty = desiredQty - currentQty;
            
            if (adjustmentQty !== 0) {
                totalItems++;
                
                const adjustmentValue = adjustmentQty * allItems[itemId].costPrice;
                const newValue = desiredQty * allItems[itemId].costPrice;
                
                totalAdjustmentValue += adjustmentValue;
                totalNewValue += newValue;
            } else {
                totalNewValue += allItems[itemId].currentValue;
            }
        }
        
        totalCurrentValue += allItems[itemId].currentValue;
    });
    
    // Update summary display
    document.getElementById('totalItems').textContent = totalItems;
    document.getElementById('totalAdjustmentValue').textContent = totalAdjustmentValue.toFixed(2);
    document.getElementById('totalCurrentValue').textContent = totalCurrentValue.toFixed(2);
    document.getElementById('totalNewValue').textContent = totalNewValue.toFixed(2);
    
    // Enable/disable submit button
    const submitBtn = document.getElementById('submitBtn');
    submitBtn.disabled = totalItems === 0;
}

// Reset form
function resetForm() {
    document.getElementById('stockAdjustmentForm').reset();
    
    // Clear all items from the table
    $('#adjustmentItemsTable').empty();
    
    // Clear allItems object
    allItems = {};
    
    updateSummary();
}

// Form validation and AJAX submission
document.getElementById('stockAdjustmentForm').addEventListener('submit', function(e) {
    e.preventDefault(); // Prevent default form submission
    
    const rows = document.querySelectorAll('.item-row');
    let hasValidAdjustments = false;
    
    rows.forEach(row => {
        const desiredQtyInput = row.querySelector('.desired-qty');
        
        if (desiredQtyInput.value !== '') {
            const desiredQty = parseFloat(desiredQtyInput.value) || 0;
            const currentQty = parseFloat(row.querySelector('.current-qty').textContent) || 0;
            const adjustmentQty = desiredQty - currentQty;
            
            if (adjustmentQty !== 0) {
                hasValidAdjustments = true;
            }
        }
    });
    
    if (!hasValidAdjustments) {
        Swal.fire({
            title: 'Validation Error',
            text: 'Please add at least one item and modify the desired final quantities.',
            icon: 'warning',
            confirmButtonText: 'OK'
        });
        return false;
    }
    
    // Show confirmation
    Swal.fire({
        title: 'Confirm Stock Adjustment',
        text: 'Are you sure you want to process this stock adjustment? This action cannot be undone.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Process',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#007bff'
    }).then((result) => {
        if (result.isConfirmed) {
            // Process the form via AJAX
            processStockAdjustment();
        }
    });
});

// Function to process stock adjustment via AJAX
function processStockAdjustment() {
    // Show loading state
    const submitBtn = document.getElementById('submitBtn');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    submitBtn.disabled = true;
    
    // Collect form data
    const formData = new FormData(document.getElementById('stockAdjustmentForm'));
    
    // The form data is already collected by FormData, no need to manually append
    // FormData automatically collects all form inputs including the hidden ones
    
    $.ajax({
        url: 'handlers/stock_adjustment_handler.php',
        type: 'POST',
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                // Show success popup with details
                Swal.fire({
                    title: 'Success!',
                    html: `
                        <div class="text-center">
                            <i class="fas fa-check-circle text-success fa-3x mb-3"></i>
                            <h5>Stock Adjustment Processed Successfully!</h5>
                            <div class="text-muted">
                                <p><strong>Adjustment #:</strong> ${response.adjustment_number}</p>
                                <p><strong>Items:</strong> ${response.total_items}</p>
                                <p><strong>Total Value:</strong> $${parseFloat(response.total_adjustment_value).toFixed(2)}</p>
                            </div>
                        </div>
                    `,
                    icon: 'success',
                    confirmButtonText: 'View All Adjustments',
                    confirmButtonColor: '#007bff'
                }).then((result) => {
                    // Redirect to stock adjustment list
                    window.location.href = 'stock_adjustment_list.php';
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: response.message,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        },
        error: function(xhr, status, error) {
            Swal.fire({
                title: 'Error!',
                text: 'Error processing stock adjustment: ' + error,
                icon: 'error',
                confirmButtonText: 'OK'
            });
        },
        complete: function() {
            // Reset button state
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    });
}
</script>

<style>
.item-row:hover {
    background-color: #f8f9fa;
}

.table th {
    background-color: #f8f9fa;
    border-color: #dee2e6;
}

.badge {
    font-size: 0.75em;
}

.text-end {
    text-align: right;
}

.card.bg-light {
    border: 1px solid #dee2e6;
}

.form-control:focus {
    border-color: #80bdff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

#searchDropdown {
    z-index: 1050;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

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

.search-item.bg-primary {
    background-color: #007bff !important;
}

/* Visual styling for adjustment quantities */
.adjustment-qty.text-success {
    font-weight: bold;
}

.adjustment-qty.text-danger {
    font-weight: bold;
}

.adjustment-qty.text-muted {
    font-style: italic;
}

/* Highlight desired quantity input when changed */
.desired-qty:focus {
    border-color: #28a745;
    box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
}

/* Tooltip for better understanding */
.desired-qty {
    position: relative;
}

 .desired-qty:hover::after {
     content: "Enter the actual quantity you want";
     position: absolute;
     bottom: 100%;
     left: 50%;
     transform: translateX(-50%);
     background: #333;
     color: white;
     padding: 5px 10px;
     border-radius: 4px;
     font-size: 12px;
     white-space: nowrap;
     z-index: 1000;
 }
</style>
