<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

// Get summary statistics
$totalStockQuery = "SELECT 
    COUNT(*) as TotalItems,
    COALESCE(SUM(CurrentStock), 0) as TotalStock,
    COALESCE(SUM(StockInBags), 0) as TotalBags,
    COUNT(CASE WHEN CurrentStock <= 10 THEN 1 END) as LowStockItems,
    COUNT(CASE WHEN CurrentStock = 0 THEN 1 END) as OutOfStockItems
    FROM tblricebags 
    WHERE IsActive = 1";

$totalStockResult = mysqli_query($con, $totalStockQuery);
$stockSummary = mysqli_fetch_assoc($totalStockResult);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Mariyappa Nadar Ricemill | Stock Report</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    
    <style>
        /* Full-height layout and compact paddings */
        html, body, #wrapper, #content-wrapper, #content { height: 100%; }
        .container-fluid { padding: 8px 10px; }
        
        .stock-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 15px;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        
        .stock-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
            border-color: #4e73df;
        }
        
        .stock-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 10px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .stock-name {
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .stock-level {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            background: rgba(255, 255, 255, 0.2);
        }
        
        .stock-normal .stock-header {
            background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        }
        
        .stock-low .stock-header {
            background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);
        }
        
        .stock-out .stock-header {
            background: linear-gradient(135deg, #e74a3b 0%, #c0392b 100%);
        }
        
        .stock-body {
            padding: 12px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        
        .stock-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            margin-bottom: 10px;
        }
        
        .info-item {
            padding: 8px;
            background: #f8f9fc;
            border-radius: 6px;
            text-align: center;
        }
        
        .info-label {
            font-size: 0.7rem;
            color: #858796;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-weight: 600;
            color: #5a5c69;
            font-size: 0.85rem;
        }
        
        .product-info {
            background: #e3f2fd;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 10px;
        }
        
        .product-name {
            font-weight: 600;
            color: #1976d2;
            font-size: 0.9rem;
        }
        
        .product-details {
            font-size: 0.75rem;
            color: #666;
        }
        
        .stock-actions {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
            margin-top: auto;
            border-top: 1px solid #f8f9fc;
            padding-top: 10px;
        }
        
        .btn-action {
            flex: 1;
            min-width: 70px;
            padding: 6px 8px;
            border: none;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.15s ease-in-out;
            text-align: center;
        }
        
        .btn-adjust {
            background: #1cc88a;
            color: white;
        }
        
        .btn-adjust:hover {
            background: #17a673;
            transform: translateY(-1px);
        }
        
        .btn-history {
            background: #36b9cc;
            color: white;
        }
        
        .btn-history:hover {
            background: #2c9faf;
            transform: translateY(-1px);
        }
        
        .btn-reorder {
            background: #f6c23e;
            color: white;
        }
        
        .btn-reorder:hover {
            background: #dda20a;
            transform: translateY(-1px);
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px;
            color: white;
            padding: 14px;
            margin-bottom: 14px;
        }
        
        .stat-item {
            text-align: center;
            padding: 10px;
            background: rgba(255,255,255,0.1);
            border-radius: 8px;
            margin-bottom: 6px;
            transition: all 0.2s ease;
        }
        
        .stat-number {
            font-size: 1.4rem;
            font-weight: bold;
            margin-bottom: 4px;
        }
        
        .stat-label {
            font-size: 0.75rem;
            opacity: 0.9;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 6px 10px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            margin-bottom: 12px;
            font-size: 0.85rem;
        }
        
        .back-btn:hover {
            background: #545b62;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .filter-tabs {
            display: flex;
            background: white;
            border-radius: 8px;
            padding: 4px;
            margin-bottom: 12px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .filter-tab {
            flex: 1;
            padding: 8px 12px;
            background: none;
            border: none;
            border-radius: 6px;
            color: #858796;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.15s ease-in-out;
            font-size: 0.85rem;
            text-align: center;
        }
        
        .filter-tab.active {
            background: #4e73df;
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 2rem 1rem;
            color: #858796;
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #dddfeb;
        }
        
        /* Search and Filter Controls */
        .controls-section {
            background: white;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 12px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .search-box {
            position: relative;
        }
        
        .search-box input {
            padding-left: 35px;
        }
        
        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #858796;
        }
        
        /* Tighter grid gutters */
        .row > [class^="col-"] { padding-left: 6px; padding-right: 6px; }

        @media (max-width: 768px) {
            .stock-info {
                grid-template-columns: 1fr;
                gap: 6px;
            }
            
            .stock-actions {
                gap: 4px;
            }
            
            .btn-action {
                font-size: 0.7rem;
                padding: 5px 6px;
            }
            
            .page-header {
                padding: 10px 12px;
            }
            
            .filter-tab {
                padding: 6px 8px;
                font-size: 0.8rem;
            }
            
            .stats-card {
                padding: 12px;
            }
            
            .stat-number {
                font-size: 1.2rem;
            }
        }
    </style>
</head>

<body id="page-top">
    <!-- Page Wrapper -->
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include_once('includes/sidebar.php'); ?>
        
        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">
            <!-- Main Content -->
            <div id="content">
                <!-- Topbar -->
                <?php include_once('includes/topbar.php'); ?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Back Button -->
                    <a href="dashboard.php" class="back-btn">
                        <i class="fas fa-arrow-left"></i>
                        Back to Dashboard
                    </a>
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h1 class="h5 mb-1">
                                    <i class="fas fa-boxes mr-2"></i>
                                    Stock Report
                                </h1>
                                <p class="mb-0" style="font-size: 0.85rem; opacity: 0.9;">Current inventory levels and stock management</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-sm" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);" onclick="exportStockReport()">
                                    <i class="fas fa-download mr-1"></i>Export
                                </button>
                                <a href="stock-adjustment.php" class="btn btn-sm" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                                    <i class="fas fa-plus mr-1"></i>Adjust Stock
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Stock Summary Statistics -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="stats-card">
                                <h6 class="mb-3">
                                    <i class="fas fa-chart-pie mr-2"></i>
                                    Stock Overview
                                </h6>
                                <div class="row">
                                    <div class="col-6 col-md-2">
                                        <div class="stat-item">
                                            <div class="stat-number"><?php echo number_format($stockSummary['TotalItems']); ?></div>
                                            <div class="stat-label">Total Items</div>
                                        </div>
                                    </div>
                                    <div class="col-6 col-md-2">
                                        <div class="stat-item">
                                            <div class="stat-number"><?php echo number_format($stockSummary['TotalStock']); ?></div>
                                            <div class="stat-label">Total Stock (Kg)</div>
                                        </div>
                                    </div>
                                    <div class="col-6 col-md-2">
                                        <div class="stat-item">
                                            <div class="stat-number"><?php echo number_format($stockSummary['TotalBags']); ?></div>
                                            <div class="stat-label">Total Bags</div>
                                        </div>
                                    </div>
                                    <div class="col-6 col-md-2">
                                        <div class="stat-item">
                                            <div class="stat-number" style="color: #ffc107;"><?php echo number_format($stockSummary['LowStockItems']); ?></div>
                                            <div class="stat-label">Low Stock Items</div>
                                        </div>
                                    </div>
                                    <div class="col-6 col-md-2">
                                        <div class="stat-item">
                                            <div class="stat-number" style="color: #dc3545;"><?php echo number_format($stockSummary['OutOfStockItems']); ?></div>
                                            <div class="stat-label">Out of Stock</div>
                                        </div>
                                    </div>
                                    <div class="col-6 col-md-2">
                                        <div class="stat-item">
                                            <div class="stat-number" style="color: #28a745;">
                                                <?php echo number_format($stockSummary['TotalItems'] - $stockSummary['LowStockItems'] - $stockSummary['OutOfStockItems']); ?>
                                            </div>
                                            <div class="stat-label">Normal Stock</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filter Controls -->
                    <div class="controls-section">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <div class="search-box">
                                    <i class="fas fa-search"></i>
                                    <input type="text" class="form-control" id="searchInput" placeholder="Search rice bags by name, brand, or type...">
                                </div>
                            </div>
                            <div class="col-md-6 mt-2 mt-md-0">
                                <div class="d-flex gap-2">
                                    <select class="form-control" id="brandFilter">
                                        <option value="">All Brands</option>
                                    </select>
                                    <select class="form-control" id="typeFilter">
                                        <option value="">All Types</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Filter Tabs -->
                    <div class="filter-tabs">
                        <button class="filter-tab active" onclick="filterStock('all')" id="tab-all">
                            <i class="fas fa-boxes mr-1"></i>All Stock
                        </button>
                        <button class="filter-tab" onclick="filterStock('normal')" id="tab-normal">
                            <i class="fas fa-check mr-1"></i>Normal Stock
                        </button>
                        <button class="filter-tab" onclick="filterStock('low')" id="tab-low">
                            <i class="fas fa-exclamation-triangle mr-1"></i>Low Stock
                        </button>
                        <button class="filter-tab" onclick="filterStock('out')" id="tab-out">
                            <i class="fas fa-times mr-1"></i>Out of Stock
                        </button>
                    </div>
                    
                    <!-- Stock Items Container -->
                    <div class="row" id="stock-container">
                        <div class="col-12">
                            <div class="empty-state">
                                <i class="fas fa-spinner fa-spin"></i>
                                <h5>Loading stock data...</h5>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
            <!-- End of Main Content -->
            
            <!-- Footer -->
            <?php include_once('includes/footer.php'); ?>
        </div>
        <!-- End of Content Wrapper -->
    </div>
    <!-- End of Page Wrapper -->
    
    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Stock History Modal -->
    <div class="modal fade" id="stockHistoryModal" tabindex="-1" role="dialog" aria-labelledby="stockHistoryModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title" id="stockHistoryModalLabel">
                        <i class="fas fa-history mr-2"></i>Stock History
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="stockHistoryContent">
                    <div class="text-center">
                        <i class="fas fa-spinner fa-spin fa-2x"></i>
                        <p class="mt-2">Loading stock history...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <!-- Core plugin JavaScript-->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    
    <!-- Custom scripts for all pages-->
    <script src="js/sb-admin-2.min.js"></script>
    
    <script>
        let currentFilter = 'all';
        let allStockData = [];
        let filteredStockData = [];
        
        $(document).ready(function() {
            // Hide sidebar on load for compact, content-focused layout
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            
            loadStockData();
            
            // Setup search functionality
            $('#searchInput').on('input', handleSearch);
            $('#brandFilter').on('change', handleFilters);
            $('#typeFilter').on('change', handleFilters);
        });
        
        // Filter stock by level
        function filterStock(level) {
            currentFilter = level;
            
            // Update active tab
            $('.filter-tab').removeClass('active');
            $('#tab-' + level).addClass('active');
            
            // Apply filter and render
            applyFiltersAndRender();
        }
        
        // Load stock data from API
        function loadStockData() {
            $('#stock-container').html(`
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-spinner fa-spin"></i>
                        <h4>Loading stock data...</h4>
                    </div>
                </div>
            `);
            
            $.ajax({
                url: 'api/get-stock-data.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (Array.isArray(response)) {
                        allStockData = response;
                        populateFilterDropdowns();
                        applyFiltersAndRender();
                    } else {
                        showError('Invalid response format');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading stock data:', error);
                    showError('Error loading stock data. Please try again.');
                }
            });
        }
        
        // Populate filter dropdowns
        function populateFilterDropdowns() {
            const brands = [...new Set(allStockData.map(item => item.Brand).filter(Boolean))];
            const types = [...new Set(allStockData.map(item => item.ManufactureType).filter(Boolean))];
            
            const brandSelect = $('#brandFilter');
            const typeSelect = $('#typeFilter');
            
            brandSelect.empty().append('<option value="">All Brands</option>');
            typeSelect.empty().append('<option value="">All Types</option>');
            
            brands.forEach(brand => {
                brandSelect.append(`<option value="${brand}">${brand}</option>`);
            });
            
            types.forEach(type => {
                typeSelect.append(`<option value="${type}">${type}</option>`);
            });
        }
        
        // Handle search input
        function handleSearch() {
            applyFiltersAndRender();
        }
        
        // Handle filter changes
        function handleFilters() {
            applyFiltersAndRender();
        }
        
        // Apply all filters and render results
        function applyFiltersAndRender() {
            const searchTerm = $('#searchInput').val().toLowerCase();
            const selectedBrand = $('#brandFilter').val();
            const selectedType = $('#typeFilter').val();
            
            // Start with all data
            filteredStockData = allStockData.filter(item => {
                // Apply search filter
                const matchesSearch = !searchTerm || 
                    item.RiceBagName.toLowerCase().includes(searchTerm) ||
                    (item.Brand && item.Brand.toLowerCase().includes(searchTerm)) ||
                    (item.ManufactureType && item.ManufactureType.toLowerCase().includes(searchTerm));
                
                // Apply brand filter
                const matchesBrand = !selectedBrand || item.Brand === selectedBrand;
                
                // Apply type filter
                const matchesType = !selectedType || item.ManufactureType === selectedType;
                
                // Apply stock level filter
                let matchesStockLevel = true;
                if (currentFilter === 'low') {
                    matchesStockLevel = item.CurrentStock > 0 && item.CurrentStock <= 10;
                } else if (currentFilter === 'out') {
                    matchesStockLevel = item.CurrentStock == 0;
                } else if (currentFilter === 'normal') {
                    matchesStockLevel = item.CurrentStock > 10;
                }
                
                return matchesSearch && matchesBrand && matchesType && matchesStockLevel;
            });
            
            renderStockItems(filteredStockData);
        }
        
        // Render stock items
        function renderStockItems(stockData) {
            const container = $('#stock-container');
            
            if (stockData.length === 0) {
                container.html(`
                    <div class="col-12">
                        <div class="empty-state">
                            <i class="fas fa-boxes"></i>
                            <h5>No stock items found</h5>
                            <p>No items match your current filters.</p>
                            <button class="btn btn-primary btn-sm" onclick="clearFilters()">
                                <i class="fas fa-undo mr-1"></i>Clear Filters
                            </button>
                        </div>
                    </div>
                `);
                return;
            }
            
            let html = '';
            stockData.forEach(item => {
                html += renderStockCard(item);
            });
            
            container.html(html);
        }
        
        // Render individual stock card
        function renderStockCard(item) {
            const currentStock = parseFloat(item.CurrentStock) || 0;
            const stockInBags = parseInt(item.StockInBags) || 0;
            
            let stockClass = 'stock-normal';
            let stockLevel = 'Normal';
            
            if (currentStock === 0) {
                stockClass = 'stock-out';
                stockLevel = 'Out of Stock';
            } else if (currentStock <= 10) {
                stockClass = 'stock-low';
                stockLevel = 'Low Stock';
            }
            
            return `
                <div class="col-lg-3 col-md-4 col-sm-6 col-12">
                    <div class="stock-card ${stockClass}">
                        <div class="stock-header">
                            <div class="stock-name">${item.RiceBagName}</div>
                            <div class="stock-level">${stockLevel}</div>
                        </div>
                        <div class="stock-body">
                            <div class="product-info">
                                <div class="product-name">
                                    <i class="fas fa-seedling mr-1"></i>${item.Brand || 'N/A'} - ${item.BagKg}kg
                                </div>
                                <div class="product-details">
                                    <i class="fas fa-industry mr-1"></i>Type: ${item.ManufactureType || 'N/A'}
                                    ${item.Location ? `<br><i class="fas fa-map-marker-alt mr-1"></i>Location: ${item.Location}` : ''}
                                </div>
                            </div>
                            
                            <div class="stock-info">
                                <div class="info-item">
                                    <div class="info-label">Stock (Kg)</div>
                                    <div class="info-value">${currentStock.toFixed(1)}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Bags</div>
                                    <div class="info-value">${stockInBags}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Per Bag</div>
                                    <div class="info-value">${item.BagKg}kg</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Status</div>
                                    <div class="info-value" style="color: ${currentStock === 0 ? '#dc3545' : currentStock <= 10 ? '#ffc107' : '#28a745'};">
                                        ${stockLevel}
                                    </div>
                                </div>
                            </div>
                            
                            <div class="stock-actions">
                                <a href="stock-adjustment.php?rice_bag_id=${item.ID}" class="btn-action btn-adjust">
                                    <i class="fas fa-plus"></i> Adjust
                                </a>
                                <button class="btn-action btn-history" onclick="viewStockHistory('${item.ID}', '${item.RiceBagName}')">
                                    <i class="fas fa-history"></i> History
                                </button>
                                ${currentStock <= 10 ? `
                                <button class="btn-action btn-reorder" onclick="reorderItem('${item.ID}', '${item.RiceBagName}')">
                                    <i class="fas fa-shopping-cart"></i> Reorder
                                </button>
                                ` : `
                                <button class="btn-action btn-history" onclick="viewDetails('${item.ID}')">
                                    <i class="fas fa-info"></i> Details
                                </button>
                                `}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // View stock history
        function viewStockHistory(itemId, itemName) {
            $('#stockHistoryModalLabel').html(`<i class="fas fa-history mr-2"></i>Stock History - ${itemName}`);
            $('#stockHistoryContent').html(`
                <div class="text-center">
                    <i class="fas fa-spinner fa-spin fa-2x"></i>
                    <p class="mt-2">Loading stock history...</p>
                </div>
            `);
            $('#stockHistoryModal').modal('show');
            
            // Load detailed stock info including history
            $.ajax({
                url: `api/get-stock-data.php?id=${itemId}`,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response && response.recentAdjustments) {
                        renderStockHistory(response);
                    } else {
                        $('#stockHistoryContent').html(`
                            <div class="text-center text-muted">
                                <i class="fas fa-info-circle fa-2x mb-3"></i>
                                <p>No stock adjustment history found for this item.</p>
                            </div>
                        `);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading stock history:', error);
                    $('#stockHistoryContent').html(`
                        <div class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle fa-2x mb-3"></i>
                            <p>Error loading stock history. Please try again.</p>
                        </div>
                    `);
                }
            });
        }
        
        // Render stock history in modal
        function renderStockHistory(data) {
            let html = `
                <div class="mb-3">
                    <h6><i class="fas fa-boxes mr-2"></i>Current Stock Information</h6>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h4 class="text-primary">${parseFloat(data.CurrentStock || 0).toFixed(1)} kg</h4>
                                    <small class="text-muted">Current Stock</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h4 class="text-info">${data.StockInBags || 0}</h4>
                                    <small class="text-muted">Bags in Stock</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h4 class="text-secondary">${data.BagKg} kg</h4>
                                    <small class="text-muted">Per Bag</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <hr>
            `;
            
            if (data.recentAdjustments && data.recentAdjustments.length > 0) {
                html += `
                    <h6><i class="fas fa-history mr-2"></i>Recent Stock Adjustments</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Quantity</th>
                                    <th>Reason</th>
                                    <th>By</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                data.recentAdjustments.forEach(adj => {
                    const adjustmentDate = new Date(adj.CreatedDate).toLocaleDateString();
                    const adjustmentType = adj.AdjustmentType === 'Add' ? 'success' : 'danger';
                    const adjustmentIcon = adj.AdjustmentType === 'Add' ? 'plus' : 'minus';
                    
                    html += `
                        <tr>
                            <td>${adjustmentDate}</td>
                            <td>
                                <span class="badge badge-${adjustmentType}">
                                    <i class="fas fa-${adjustmentIcon} mr-1"></i>${adj.AdjustmentType}
                                </span>
                            </td>
                            <td>${adj.Quantity} kg</td>
                            <td>${adj.Reason || 'N/A'}</td>
                            <td>${adj.CreatedByName || 'N/A'}</td>
                        </tr>
                    `;
                });
                
                html += `
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                html += `
                    <div class="text-center text-muted">
                        <i class="fas fa-info-circle fa-2x mb-3"></i>
                        <p>No recent stock adjustments found.</p>
                    </div>
                `;
            }
            
            $('#stockHistoryContent').html(html);
        }
        
        // Reorder item (placeholder)
        function reorderItem(itemId, itemName) {
            alert(`Reorder functionality for "${itemName}" will be implemented soon!`);
        }
        
        // View item details (placeholder)
        function viewDetails(itemId) {
            alert('View detailed item information coming soon!');
        }
        
        // Clear all filters
        function clearFilters() {
            $('#searchInput').val('');
            $('#brandFilter').val('');
            $('#typeFilter').val('');
            currentFilter = 'all';
            $('.filter-tab').removeClass('active');
            $('#tab-all').addClass('active');
            applyFiltersAndRender();
        }
        
        // Export stock report (placeholder)
        function exportStockReport() {
            // Create CSV content
            let csvContent = "Rice Bag Name,Brand,Type,Bag Weight,Current Stock (Kg),Stock in Bags,Stock Level,Location\n";
            
            filteredStockData.forEach(item => {
                const currentStock = parseFloat(item.CurrentStock) || 0;
                let stockLevel = 'Normal';
                if (currentStock === 0) stockLevel = 'Out of Stock';
                else if (currentStock <= 10) stockLevel = 'Low Stock';
                
                csvContent += `"${item.RiceBagName}","${item.Brand || ''}","${item.ManufactureType || ''}","${item.BagKg}","${currentStock}","${item.StockInBags || 0}","${stockLevel}","${item.Location || ''}"\n`;
            });
            
            // Download CSV
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement("a");
            const url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", `stock_report_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // Show error message
        function showError(message) {
            $('#stock-container').html(`
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-exclamation-triangle" style="color: #e74a3b;"></i>
                        <h5>Error</h5>
                        <p>${message}</p>
                        <button class="btn btn-primary btn-sm" onclick="loadStockData()">Try Again</button>
                    </div>
                </div>
            `);
        }
    </script>
</body>
</html>