<?php 
include 'views/headin-dashboard.php';

// Get inventory statistics from database
try {
    // Total Products
    $total_products_query = $conn->query("SELECT COUNT(*) as count FROM products WHERE status = 'active'");
    $total_products = $total_products_query->fetch(PDO::FETCH_OBJ)->count;
    
    // Low Stock Products
    $low_stock_query = $conn->query("SELECT COUNT(*) as count FROM products WHERE stock_quantity <= low_stock_alert AND status = 'active' AND stock_quantity > 0");
    $low_stock = $low_stock_query->fetch(PDO::FETCH_OBJ)->count;
    
    // Out of Stock Products
    $out_of_stock_query = $conn->query("SELECT COUNT(*) as count FROM products WHERE stock_quantity = 0 AND status = 'active'");
    $out_of_stock = $out_of_stock_query->fetch(PDO::FETCH_OBJ)->count;
    
    // Total Stock Value
    $stock_value_query = $conn->query("SELECT SUM(COALESCE(cost_price, regular_price) * stock_quantity) as value FROM products WHERE status = 'active'");
    $stock_value = $stock_value_query->fetch(PDO::FETCH_OBJ)->value ?? 0;
    
    // Total Stock Quantity
    $total_stock_query = $conn->query("SELECT SUM(stock_quantity) as total FROM products WHERE status = 'active'");
    $total_stock = $total_stock_query->fetch(PDO::FETCH_OBJ)->total ?? 0;
    
    // Get inventory data with images
    $inventory_query = $conn->query("SELECT p.*, pi.image_url 
                                     FROM products p 
                                     LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1
                                     WHERE p.status = 'active'
                                     ORDER BY p.stock_quantity ASC, p.product_name ASC");
    $inventory_data = $inventory_query->fetchAll(PDO::FETCH_OBJ);
    
} catch(Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
        <!-- Inventory Page Content -->
        <main class="p-6">
            <!-- Header Section -->
            <div class="mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <h1 class="text-3xl font-bold text-licorice mb-2">Inventory Management 📦</h1>
                    <p class="text-gray-600">Track and manage your product stock levels</p>
                </div>
                <div class="flex gap-3">
                    <button id="bulkUpdateBtn" class="btn-secondary px-4 py-2 rounded-lg text-gray-700 font-semibold flex items-center gap-2 shadow-md hover:shadow-lg transition-all">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                        </svg>
                        Bulk Update
                    </button>
                    <button id="exportBtn" class="btn-secondary px-4 py-2 rounded-lg text-gray-700 font-semibold flex items-center gap-2 shadow-md hover:shadow-lg transition-all">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                        </svg>
                        Export
                    </button>
                </div>
            </div>

            <!-- Stats Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                <!-- Total Products -->
                <div class="bg-white rounded-xl shadow-md p-6 hover:shadow-xl transition-shadow duration-300">
                    <div class="flex items-center justify-between mb-4">
                        <div class="p-3 bg-gradient-to-br from-verdigris to-verdigris/80 rounded-lg">
                            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                            </svg>
                        </div>
                        <span class="text-verdigris text-sm font-semibold">Total</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Total Products</h3>
                    <p class="text-2xl font-bold text-licorice"><?php echo number_format($total_products); ?></p>
                </div>

                <!-- Low Stock Alert -->
                <div class="bg-white rounded-xl shadow-md p-6 hover:shadow-xl transition-shadow duration-300">
                    <div class="flex items-center justify-between mb-4">
                        <div class="p-3 bg-gradient-to-br from-hunyadi to-hunyadi/80 rounded-lg">
                            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                            </svg>
                        </div>
                        <span class="text-orange-500 text-sm font-semibold">Alert</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Low Stock</h3>
                    <p class="text-2xl font-bold text-licorice"><?php echo number_format($low_stock); ?></p>
                </div>

                <!-- Out of Stock -->
                <div class="bg-white rounded-xl shadow-md p-6 hover:shadow-xl transition-shadow duration-300">
                    <div class="flex items-center justify-between mb-4">
                        <div class="p-3 bg-gradient-to-br from-red-500 to-red-600 rounded-lg">
                            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </div>
                        <span class="text-red-500 text-sm font-semibold">Unavailable</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Out of Stock</h3>
                    <p class="text-2xl font-bold text-licorice"><?php echo number_format($out_of_stock); ?></p>
                </div>

                <!-- Stock Value -->
                <div class="bg-white rounded-xl shadow-md p-6 hover:shadow-xl transition-shadow duration-300">
                    <div class="flex items-center justify-between mb-4">
                        <div class="p-3 bg-gradient-to-br from-purple-500 to-purple-600 rounded-lg">
                            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                            </svg>
                        </div>
                        <span class="text-purple-500 text-sm font-semibold">Value</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Stock Value</h3>
                    <p class="text-2xl font-bold text-licorice">$<?php echo number_format($stock_value, 2); ?></p>
                </div>
            </div>

            <!-- Filters & Search -->
            <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
                    <!-- Search -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Search Products</label>
                        <div class="relative">
                            <input 
                                type="text" 
                                id="searchInput"
                                placeholder="Search by name, SKU, or category..." 
                                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                            <svg class="absolute left-3 top-2.5 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                            </svg>
                        </div>
                    </div>

                    <!-- Stock Status Filter -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Stock Status</label>
                        <select id="stockFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                            <option value="">All Stock</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>

                    <!-- Category Filter -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Category</label>
                        <select id="categoryFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                            <option value="">All Categories</option>
                            <option value="electronics">Electronics</option>
                            <option value="clothing">Clothing</option>
                            <option value="home">Home & Garden</option>
                            <option value="other">Other</option>
                        </select>
                    </div>

                    <!-- Sort By -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Sort By</label>
                        <select id="sortBy" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                            <option value="stock_asc">Stock (Low to High)</option>
                            <option value="stock_desc">Stock (High to Low)</option>
                            <option value="name_asc">Name (A to Z)</option>
                            <option value="name_desc">Name (Z to A)</option>
                            <option value="value_desc">Value (High to Low)</option>
                            <option value="value_asc">Value (Low to High)</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Inventory Table -->
            <div class="bg-white rounded-xl shadow-md overflow-hidden">
                <div class="p-6 border-b border-gray-200 flex items-center justify-between">
                    <h2 class="text-xl font-bold text-licorice">Inventory Overview</h2>
                    <div class="flex items-center gap-4">
                        <span class="text-sm text-gray-600">Total Stock: <span class="font-semibold text-licorice"><?php echo number_format($total_stock); ?></span> units</span>
                        <button id="refreshBtn" class="p-2 text-gray-600 hover:text-verdigris hover:bg-gray-100 rounded-lg transition-colors" title="Refresh">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                            </svg>
                        </button>
                    </div>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                    <input type="checkbox" id="selectAll" class="rounded border-gray-300 text-verdigris focus:ring-verdigris">
                                </th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Image</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Product Name</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">SKU</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Category</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Current Stock</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Low Stock Alert</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Stock Value</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="inventoryTableBody">
                            <?php if (empty($inventory_data)): ?>
                            <tr>
                                <td colspan="10" class="px-6 py-16 text-center">
                                    <div class="flex flex-col items-center justify-center">
                                        <svg class="w-24 h-24 text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                                        </svg>
                                        <h3 class="text-xl font-semibold text-gray-600 mb-2">No Products Found</h3>
                                        <p class="text-gray-500 mb-6">Get started by adding your first product</p>
                                        <a href="add-product" class="btn-primary px-6 py-3 rounded-xl text-white font-semibold inline-flex items-center gap-2 shadow-lg hover-lift">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
                                            </svg>
                                            Add First Product
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($inventory_data as $product): ?>
                            <?php 
                            $stock_value = ($product->cost_price ?? $product->regular_price) * $product->stock_quantity;
                            $is_low_stock = $product->stock_quantity <= $product->low_stock_alert && $product->stock_quantity > 0;
                            $is_out_of_stock = $product->stock_quantity == 0;
                            ?>
                            <tr class="hover:bg-gray-50 transition-colors" data-product-id="<?php echo $product->id; ?>">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="checkbox" class="product-checkbox rounded border-gray-300 text-verdigris focus:ring-verdigris" value="<?php echo $product->id; ?>">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <img src="<?php echo $product->image_url ?: 'https://via.placeholder.com/50'; ?>" alt="<?php echo htmlspecialchars($product->product_name); ?>" class="w-12 h-12 object-cover rounded-lg border border-gray-200">
                                </td>
                                <td class="px-6 py-4">
                                    <div class="font-semibold text-licorice"><?php echo htmlspecialchars($product->product_name); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($product->brand ?: 'No brand'); ?></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700"><?php echo htmlspecialchars($product->sku); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700 capitalize"><?php echo htmlspecialchars($product->category); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center gap-2">
                                        <input 
                                            type="number" 
                                            class="stock-input w-20 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi" 
                                            value="<?php echo $product->stock_quantity; ?>" 
                                            min="0"
                                            data-original-value="<?php echo $product->stock_quantity; ?>"
                                        >
                                        <button class="update-stock-btn p-1 text-verdigris hover:text-hunyadi transition-colors" title="Update Stock" style="display: none;">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                            </svg>
                                        </button>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input 
                                        type="number" 
                                        class="alert-input w-16 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi" 
                                        value="<?php echo $product->low_stock_alert; ?>" 
                                        min="0"
                                        data-original-value="<?php echo $product->low_stock_alert; ?>"
                                    >
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-licorice">
                                    $<?php echo number_format($stock_value, 2); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php if ($is_out_of_stock): ?>
                                        <span class="px-3 py-1 bg-red-100 text-red-700 rounded-full text-xs font-semibold">Out of Stock</span>
                                    <?php elseif ($is_low_stock): ?>
                                        <span class="px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-xs font-semibold">Low Stock</span>
                                    <?php else: ?>
                                        <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold">In Stock</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <div class="flex items-center gap-2">
                                        <button onclick="editProduct(<?php echo $product->id; ?>)" class="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors" title="Edit Product">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                                            </svg>
                                        </button>
                                        <button onclick="adjustStock(<?php echo $product->id; ?>, '<?php echo htmlspecialchars($product->product_name); ?>')" class="p-2 text-green-600 hover:bg-green-50 rounded-lg transition-colors" title="Adjust Stock">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                                            </svg>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex flex-col sm:flex-row items-center justify-between gap-4">
                    <div class="text-sm text-gray-600">
                        Showing <span class="font-semibold">1</span> to <span class="font-semibold"><?php echo count($inventory_data); ?></span> of <span class="font-semibold"><?php echo count($inventory_data); ?></span> results
                    </div>
                    <div class="flex items-center gap-2">
                        <button class="px-4 py-2 border border-gray-300 rounded-lg text-sm font-semibold text-gray-600 hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            Previous
                        </button>
                        <button class="px-4 py-2 bg-verdigris text-white rounded-lg text-sm font-semibold">1</button>
                        <button class="px-4 py-2 border border-gray-300 rounded-lg text-sm font-semibold text-gray-600 hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            Next
                        </button>
                    </div>
                </div>
            </div>
        </main>

        <!-- Stock Adjustment Modal -->
        <div id="stockModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
            <div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-md mx-4">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-bold text-licorice">Adjust Stock</h3>
                    <button id="closeStockModal" class="text-gray-400 hover:text-gray-600 transit