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

// Get real 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;
    
    // Total Categories
    $total_categories_query = $conn->query("SELECT COUNT(*) as count FROM categories WHERE status = 'active' AND parent_id IS NULL");
    $total_categories = $total_categories_query->fetch(PDO::FETCH_OBJ)->count;
    
    // Total Sales (sum of sales_count)
    $total_sales_query = $conn->query("SELECT SUM(sales_count) as total FROM products");
    $total_sales = $total_sales_query->fetch(PDO::FETCH_OBJ)->total ?? 0;
    
    // Total Revenue (estimated based on sales)
    $total_revenue_query = $conn->query("SELECT SUM(COALESCE(sale_price, regular_price) * sales_count) as revenue FROM products");
    $total_revenue = $total_revenue_query->fetch(PDO::FETCH_OBJ)->revenue ?? 0;
    
    // Low Stock Products
    $low_stock_query = $conn->query("SELECT COUNT(*) as count FROM products WHERE stock_quantity < low_stock_alert AND status = 'active'");
    $low_stock = $low_stock_query->fetch(PDO::FETCH_OBJ)->count;
    
    // Total Stock Value
    $stock_value_query = $conn->query("SELECT SUM(regular_price * stock_quantity) as value FROM products WHERE status = 'active'");
    $stock_value = $stock_value_query->fetch(PDO::FETCH_OBJ)->value ?? 0;
    
    // Get top selling products
    $top_products_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.sales_count DESC 
                                        LIMIT 5");
    $top_products = $top_products_query->fetchAll(PDO::FETCH_OBJ);
    
    // Get recent products (as a substitute for recent orders)
    $recent_products_query = $conn->query("SELECT p.*, pi.image_url, c.name as category_name
                                           FROM products p 
                                           LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1
                                           LEFT JOIN categories c ON p.category = c.slug
                                           WHERE p.status = 'active'
                                           ORDER BY p.created_at DESC 
                                           LIMIT 5");
    $recent_products = $recent_products_query->fetchAll(PDO::FETCH_OBJ);
    
} catch(Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
        <!-- Dashboard Content -->
        <main class="p-6">
            <!-- Welcome Section -->
            <div class="mb-6">
                <h1 class="text-3xl font-bold text-licorice mb-2">Welcome! 👋</h1>
                <p class="text-gray-600">Overview of your store's performance</p>
            </div>

            <!-- Stats Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                <!-- Card 1: 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-blue-500 text-sm font-semibold">Products</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Total Active Products</h3>
                    <p class="text-2xl font-bold text-licorice"><?php echo number_format($total_products); ?></p>
                </div>

                <!-- Card 2: Categories -->
                <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="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/>
                            </svg>
                        </div>
                        <span class="text-orange-500 text-sm font-semibold">Categories</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Total Categories</h3>
                    <p class="text-2xl font-bold text-licorice"><?php echo number_format($total_categories); ?></p>
                </div>

                <!-- Card 3: Total Sales -->
                <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-seal-brown to-seal-brown/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="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/>
                            </svg>
                        </div>
                        <span class="text-green-500 text-sm font-semibold">Sales</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Total Sales Count</h3>
                    <p class="text-2xl font-bold text-licorice"><?php echo number_format($total_sales); ?></p>
                </div>

                <!-- Card 4: Total Revenue -->
                <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-vanilla to-hunyadi 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-green-500 text-sm font-semibold">Revenue</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Total Revenue (Estimated)</h3>
                    <p class="text-2xl font-bold text-licorice">$<?php echo number_format($total_revenue, 2); ?></p>
                </div>
            </div>

            <!-- Additional Stats Row -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6 mb-6">
                <!-- 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-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="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-red-500 text-sm font-semibold">Alert</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Low Stock Products</h3>
                    <p class="text-2xl font-bold text-licorice"><?php echo number_format($low_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="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
                            </svg>
                        </div>
                        <span class="text-purple-500 text-sm font-semibold">Value</span>
                    </div>
                    <h3 class="text-gray-500 text-sm mb-1">Total Stock Value</h3>
                    <p class="text-2xl font-bold text-licorice">$<?php echo number_format($stock_value, 2); ?></p>
                </div>
            </div>

            <!-- Charts & Tables Section -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
                <!-- Recent Products -->
                <div class="lg:col-span-2 bg-white rounded-xl shadow-md p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-xl font-bold text-licorice">Recent Products</h2>
                        <a href="products.php" class="text-verdigris hover:text-seal-brown transition-colors text-sm font-semibold">View All</a>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="border-b border-gray-200">
                                    <th class="text-left pb-3 text-sm font-semibold text-gray-600">Product Name</th>
                                    <th class="text-left pb-3 text-sm font-semibold text-gray-600">Category</th>
                                    <th class="text-left pb-3 text-sm font-semibold text-gray-600">Price</th>
                                    <th class="text-left pb-3 text-sm font-semibold text-gray-600">Stock</th>
                                    <th class="text-left pb-3 text-sm font-semibold text-gray-600">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($recent_products)): ?>
                                <tr>
                                    <td colspan="5" class="py-4 text-center text-gray-500">
                                        No products found
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($recent_products as $product): ?>
                                <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                                    <td class="py-4 text-sm">
                                        <a href="edit-product.php?id=<?php echo $product->id; ?>" class="text-verdigris hover:underline">
                                            <?php echo htmlspecialchars($product->product_name); ?>
                                        </a>
                                    </td>
                                    <td class="py-4 text-sm"><?php echo htmlspecialchars($product->category_name ?? $product->category); ?></td>
                                    <td class="py-4 text-sm">
                                        $<?php echo number_format($product->sale_price ?? $product->regular_price, 2); ?>
                                    </td>
                                    <td class="py-4 text-sm">
                                        <span class="<?php echo $product->stock_quantity < $product->low_stock_alert ? 'text-red-600 font-semibold' : ''; ?>">
                                            <?php echo $product->stock_quantity; ?>
                                        </span>
                                    </td>
                                    <td class="py-4">
                                        <?php 
                                        $status_colors = [
                                            'active' => 'bg-green-100 text-green-700',
                                            'inactive' => 'bg-red-100 text-red-700',
                                            'draft' => 'bg-yellow-100 text-yellow-700'
                                        ];
                                        $status_labels = [
                                            'active' => 'Active',
                                            'inactive' => 'Inactive',
                                            'draft' => 'Draft'
                                        ];
                                        ?>
                                        <span class="px-3 py-1 <?php echo $status_colors[$product->status]; ?> rounded-full text-xs font-semibold">
                                            <?php echo $status_labels[$product->status]; ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Top Products -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-xl font-bold text-licorice">Top Selling Products</h2>
                        <svg class="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="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z"/>
                        </svg>
                    </div>
                    <div class="space-y-4">
                        <?php if (empty($top_products)): ?>
                        <div class="text-center text-gray-500 py-8">
                            No products found
                        </div>
                        <?php else: ?>
                        <?php 
                        $gradient_colors = [
                            'from-verdigris to-hunyadi',
                            'from-hunyadi to-seal-brown',
                            'from-seal-brown to-licorice',
                            'from-vanilla to-hunyadi',
                            'from-verdigris to-seal-brown'
                        ];
                        $rank = 1;
                        foreach ($top_products as $product): 
                        ?>
                        <!-- Product <?php echo $rank; ?> -->
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                            <div class="flex items-center flex-1">
                                <div class="w-12 h-12 bg-gradient-to-br <?php echo $gradient_colors[$rank - 1]; ?> rounded-lg flex items-center justify-center text-white font-bold flex-shrink-0">
                                    <?php echo $rank; ?>
                                </div>
                                <div class="ml-3 flex-1 min-w-0">
                                    <p class="font-semibold text-sm truncate" title="<?php echo htmlspecialchars($product->product_name); ?>">
                                        <?php echo htmlspecialchars($product->product_name); ?>
                                    </p>
                                    <p class="text-xs text-gray-500">
                                        <?php echo number_format($product->sales_count); ?> sales
                                    </p>
                                </div>
                            </div>
                            <span class="text-verdigris font-bold text-sm ml-2">
                                $<?php echo number_format($product->sale_price ?? $product->regular_price, 2); ?>
                            </span>
                        </div>
                        <?php 
                        $rank++;
                        endforeach; 
                        ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <a href="add-product.php" class="bg-gradient-to-br from-verdigris to-verdigris/80 text-white p-6 rounded-xl shadow-md hover:shadow-xl transform hover:-translate-y-1 transition-all duration-300 block text-center">
                    <svg class="w-8 h-8 mb-3 mx-auto" 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>
                    <h3 class="font-bold mb-1">New Product</h3>
                    <p class="text-sm opacity-90">Add Product</p>
                </a>

                <a href="products.php" class="bg-gradient-to-br from-hunyadi to-hunyadi/80 text-white p-6 rounded-xl shadow-md hover:shadow-xl transform hover:-translate-y-1 transition-all duration-300 block text-center">
                    <svg class="w-8 h-8 mb-3 mx-auto" 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>
                    <h3 class="font-bold mb-1">Products</h3>
                    <p class="text-sm opacity-90">Manage Products</p>
                </a>

                <a href="categories.php" class="bg-gradient-to-br from-seal-brown to-seal-brown/80 text-white p-6 rounded-xl shadow-md hover:shadow-xl transform hover:-translate-y-1 transition-all duration-300 block text-center">
                    <svg class="w-8 h-8 mb-3 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/>
                    </svg>
                    <h3 class="font-bold mb-1">Categories</h3>
                    <p class="text-sm opacity-90">Manage Categories</p>
                </a>

                <a href="dashboard.php" class="bg-gradient-to-br from-licorice to-seal-brown text-white p-6 rounded-xl shadow-md hover:shadow-xl transform hover:-translate-y-1 transition-all duration-300 block text-center">
                    <svg class="w-8 h-8 mb-3 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
                    </svg>
                    <h3 class="font-bold mb-1">Reports</h3>
                    <p class="text-sm opacity-90">Analytics & Stats</p>
                </a>
            </div>
        </main>
    <script>
        // Mobile offcanvas menu
        const menuToggle = document.getElementById('menuToggle');
        const closeSidebar = document.getElementById('closeSidebar');
        const sidebar = document.getElementById('sidebar');
        const sidebarBackdrop = document.getElementById('sidebarBackdrop');
        const mainContent = document.getElementById('mainContent');

        // Function to open sidebar
        function openSidebar() {
            sidebar.classList.add('active');
            sidebarBackdrop.classList.add('active');
            document.body.style.overflow = 'hidden'; // Prevent body scroll when sidebar is open
        }

        // Function to close sidebar
        function closeSidebarFunc() {
            sidebar.classList.remove('active');
            sidebarBackdrop.classList.remove('active');
            document.body.style.overflow = ''; // Restore body scroll
        }

        // Toggle sidebar on menu button click
        menuToggle.addEventListener('click', function() {
            if (sidebar.classList.contains('active')) {
                closeSidebarFunc();
            } else {
                openSidebar();
            }
        });

        // Close sidebar on close button click
        closeSidebar.addEventListener('click', closeSidebarFunc);

        // Close sidebar when clicking on backdrop
        sidebarBackdrop.addEventListener('click', closeSidebarFunc);

        // Close sidebar on window resize if screen is large
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 1024) {
                closeSidebarFunc();
            }
        });

        // Close sidebar when pressing Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && sidebar.classList.contains('active')) {
                closeSidebarFunc();
            }
        });

        // Add animation to stats cards on scroll
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -100px 0px'
        };

        const observer = new IntersectionObserver(function(entries) {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, observerOptions);

        // Initially hide elements for animation
        document.querySelectorAll('.grid > div').forEach(el => {
            el.style.opacity = '0';
            el.style.transform = 'translateY(20px)';
            el.style.transition = 'all 0.5s ease-out';
            observer.observe(el);
        });

        // Smooth scroll behavior
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    </script>
<?php require_once 'views/fotter-dashboard.php'; ?>