<?php 
// Include session handling
try {
    include_once 'services/session.php';
} catch (Exception $e) {
    die("Error including session.php: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
try {
    require_once 'layouts/dbconn.php';
} catch (Exception $e) {
    die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// Function to safely execute queries
if (!function_exists('safeQuery')) {
    function safeQuery($conn, $query, $params = []) {
        try {
            $stmt = $conn->prepare($query);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            if (!empty($params)) {
                $types = str_repeat('s', count($params));
                $stmt->bind_param($types, ...$params);
            }
            
            $stmt->execute();
            $result = $stmt->get_result();
            $data = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            return $data;
        } catch (Exception $e) {
            error_log("Query error: " . $e->getMessage());
            return [];
        }
    }
}

// Get pagination parameters
$page = $_GET['page'] ?? 1;
$per_page = 12;
$offset = ($page - 1) * $per_page;

// Get filter parameters
$category_filter = $_GET['category'] ?? 'all';
$price_filter = $_GET['price'] ?? 'all';
$search = $_GET['search'] ?? '';
$sort = $_GET['sort'] ?? 'featured';

// Build WHERE clause
$where_conditions = ["p.is_active = 1"];
$params = [];

if ($category_filter !== 'all') {
    $where_conditions[] = "p.category_id = ?";
    $params[] = $category_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(p.name LIKE ? OR p.short_description LIKE ? OR p.long_description LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$where_clause = implode(" AND ", $where_conditions);

// Build ORDER BY clause
$order_clause = "p.is_featured DESC, p.created_at DESC";
switch ($sort) {
    case 'name_asc':
        $order_clause = "p.name ASC";
        break;
    case 'name_desc':
        $order_clause = "p.name DESC";
        break;
    case 'price_asc':
        $order_clause = "MIN(pp.price_usd) ASC";
        break;
    case 'price_desc':
        $order_clause = "MIN(pp.price_usd) DESC";
        break;
    case 'newest':
        $order_clause = "p.created_at DESC";
        break;
    case 'popular':
        $order_clause = "p.download_count DESC";
        break;
    default: // featured
        $order_clause = "p.is_featured DESC, p.created_at DESC";
}

// Get products with pricing
$products = safeQuery($conn, "
    SELECT 
        p.product_id,
        p.name,
        p.short_description,
        p.long_description,
        p.features,
        p.supported_providers,
        p.requirements,
        p.documentation_url,
        p.demo_url,
        p.is_featured,
        p.download_count,
        p.rating_average,
        p.rating_count,
        p.created_at,
        pc.name as category_name,
        pc.icon as category_icon,
        MIN(pp.price_usd) as min_price,
        MAX(pp.price_usd) as max_price,
        COUNT(pp.pricing_id) as pricing_tiers,
        GROUP_CONCAT(DISTINCT pp.tier_name ORDER BY pp.price_usd) as tier_names
    FROM products p
    JOIN product_categories pc ON p.category_id = pc.category_id
    LEFT JOIN product_pricing pp ON p.product_id = pp.product_id AND pp.is_active = 1
    WHERE $where_clause
    GROUP BY p.product_id
    ORDER BY $order_clause
    LIMIT ? OFFSET ?
", array_merge($params, [$per_page, $offset]));

// Apply price filter after getting results
if ($price_filter !== 'all') {
    $products = array_filter($products, function($product) use ($price_filter) {
        $price = $product['min_price'];
        switch ($price_filter) {
            case 'under_25': return $price < 25;
            case '25_50': return $price >= 25 && $price <= 50;
            case '50_100': return $price >= 50 && $price <= 100;
            case 'over_100': return $price > 100;
            default: return true;
        }
    });
}

// Get total count for pagination
$total_result = safeQuery($conn, "
    SELECT COUNT(DISTINCT p.product_id) as total
    FROM products p
    JOIN product_categories pc ON p.category_id = pc.category_id
    WHERE $where_clause
", $params);
$total_products = $total_result[0]['total'] ?? 0;
$total_pages = ceil($total_products / $per_page);

// Get categories for filter
$categories = safeQuery($conn, "
    SELECT pc.category_id, pc.name, pc.icon, COUNT(p.product_id) as product_count
    FROM product_categories pc
    LEFT JOIN products p ON pc.category_id = p.category_id AND p.is_active = 1
    GROUP BY pc.category_id
    ORDER BY pc.name
");

// Check user's existing licenses to show purchase status
$user_licenses = [];
if ($user_id) {
    $licenses = safeQuery($conn, "
        SELECT product_id, status, COUNT(*) as license_count
        FROM licenses 
        WHERE user_id = ?
        GROUP BY product_id, status
    ", [$user_id]);
    
    foreach ($licenses as $license) {
        $user_licenses[$license['product_id']][$license['status']] = $license['license_count'];
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php 
    $title = "Browse Plugins";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>Browse Plugins - ConnectPay</title>\n";
        }
    } else {
        echo "<title>Browse Plugins - ConnectPay</title>\n";
    }
    ?>
    
    <?php 
    if (file_exists('partials/head-css.php')) {
        try {
            include_once 'partials/head-css.php';
        } catch (Exception $e) {
            echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
            echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
        echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        body {
            background-color: #f8f9fa;
        }
        
        .plugin-card {
            border: 1px solid #e9ecef;
            border-radius: 15px;
            transition: all 0.3s ease;
            height: 100%;
            background: white;
            overflow: hidden;
        }
        
        .plugin-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border-color: #007bff;
        }
        
        .plugin-featured {
            border: 2px solid #ffc107;
            position: relative;
        }
        
        .featured-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: linear-gradient(45deg, #ffc107, #ff8c00);
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            z-index: 10;
        }
        
        .plugin-image {
            height: 200px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
        }
        
        .plugin-content {
            padding: 1.5rem;
        }
        
        .plugin-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            height: 3rem;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        
        .plugin-description {
            color: #6c757d;
            font-size: 0.9rem;
            height: 3rem;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            margin-bottom: 1rem;
        }
        
        .plugin-features {
            margin-bottom: 1rem;
        }
        
        .feature-tag {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            padding: 0.25rem 0.5rem;
            border-radius: 15px;
            font-size: 0.75rem;
            margin-right: 0.5rem;
            margin-bottom: 0.25rem;
            display: inline-block;
        }
        
        .plugin-price {
            font-size: 1.5rem;
            font-weight: 700;
            color: #28a745;
            margin-bottom: 0.5rem;
        }
        
        .plugin-rating {
            color: #ffc107;
            margin-bottom: 1rem;
        }
        
        .plugin-footer {
            padding: 1rem 1.5rem;
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }
        
        .filter-sidebar {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }
        
        .category-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            border-radius: 8px;
            text-decoration: none;
            color: #495057;
            transition: all 0.3s ease;
            margin-bottom: 0.5rem;
        }
        
        .category-item:hover, .category-item.active {
            background: #007bff;
            color: white;
            text-decoration: none;
        }
        
        .search-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .sort-dropdown {
            min-width: 200px;
        }
        
        .owned-badge {
            background: #28a745;
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .provider-icons {
            margin-top: 0.5rem;
        }
        
        .provider-icon {
            width: 24px;
            height: 24px;
            background: #e9ecef;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-right: 0.5rem;
            font-size: 0.75rem;
            color: #6c757d;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "Browse Plugins"; 
    if (file_exists('partials/menu.php')) {
        try {
            include_once 'partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <div class="container">
                        <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                        <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                    </div>
                  </nav>';
        }
    } else {
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                    <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                </div>
              </nav>';
    }
    ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Search Header -->
                <div class="row">
                    <div class="col-12">
                        <div class="search-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h2 class="mb-3">
                                        <i class="fas fa-puzzle-piece me-2"></i>
                                        Plugin Marketplace
                                    </h2>
                                    <p class="mb-0 opacity-75">
                                        Discover powerful mobile money payment plugins for your WordPress site
                                    </p>
                                </div>
                                <div class="col-md-4">
                                    <form method="GET" class="d-flex">
                                        <input type="text" class="form-control me-2" name="search" 
                                               value="<?php echo htmlspecialchars($search); ?>" 
                                               placeholder="Search plugins...">
                                        <button class="btn btn-light" type="submit">
                                            <i class="fas fa-search"></i>
                                        </button>
                                        
                                        <!-- Preserve other filters -->
                                        <input type="hidden" name="category" value="<?php echo $category_filter; ?>">
                                        <input type="hidden" name="price" value="<?php echo $price_filter; ?>">
                                        <input type="hidden" name="sort" value="<?php echo $sort; ?>">
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- Filters Sidebar -->
                    <div class="col-xl-3 col-lg-4">
                        <div class="filter-sidebar">
                            <h5 class="mb-3">
                                <i class="fas fa-filter me-2"></i>
                                Filters
                            </h5>
                            
                            <!-- Categories -->
                            <div class="mb-4">
                                <h6 class="text-muted mb-3">Categories</h6>
                                <a href="?category=all&price=<?php echo $price_filter; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>" 
                                   class="category-item <?php echo $category_filter === 'all' ? 'active' : ''; ?>">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-th-large me-2"></i>
                                        <span>All Categories</span>
                                    </div>
                                    <span class="badge bg-secondary"><?php echo $total_products; ?></span>
                                </a>
                                
                                <?php foreach ($categories as $category): ?>
                                <a href="?category=<?php echo $category['category_id']; ?>&price=<?php echo $price_filter; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>" 
                                   class="category-item <?php echo $category_filter == $category['category_id'] ? 'active' : ''; ?>">
                                    <div class="d-flex align-items-center">
                                        <i class="<?php echo $category['icon'] ?? 'fas fa-folder'; ?> me-2"></i>
                                        <span><?php echo htmlspecialchars($category['name']); ?></span>
                                    </div>
                                    <span class="badge bg-secondary"><?php echo $category['product_count']; ?></span>
                                </a>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- Price Range -->
                            <div class="mb-4">
                                <h6 class="text-muted mb-3">Price Range</h6>
                                <div class="list-group list-group-flush">
                                    <a href="?category=<?php echo $category_filter; ?>&price=all&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>" 
                                       class="list-group-item list-group-item-action border-0 ps-0 <?php echo $price_filter === 'all' ? 'active' : ''; ?>">
                                        All Prices
                                    </a>
                                    <a href="?category=<?php echo $category_filter; ?>&price=under_25&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>" 
                                       class="list-group-item list-group-item-action border-0 ps-0 <?php echo $price_filter === 'under_25' ? 'active' : ''; ?>">
                                        Under $25
                                    </a>
                                    <a href="?category=<?php echo $category_filter; ?>&price=25_50&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>" 
                                       class="list-group-item list-group-item-action border-0 ps-0 <?php echo $price_filter === '25_50' ? 'active' : ''; ?>">
                                        $25 - $50
                                    </a>
                                    <a href="?category=<?php echo $category_filter; ?>&price=50_100&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>" 
                                       class="list-group-item list-group-item-action border-0 ps-0 <?php echo $price_filter === '50_100' ? 'active' : ''; ?>">
                                        $50 - $100
                                    </a>
                                    <a href="?category=<?php echo $category_filter; ?>&price=over_100&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>" 
                                       class="list-group-item list-group-item-action border-0 ps-0 <?php echo $price_filter === 'over_100' ? 'active' : ''; ?>">
                                        Over $100
                                    </a>
                                </div>
                            </div>
                            
                            <!-- Clear Filters -->
                            <div class="d-grid">
                                <a href="browse-plugins.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-times me-1"></i>
                                    Clear All Filters
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Products Grid -->
                    <div class="col-xl-9 col-lg-8">
                        <!-- Sort and Results Info -->
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <div>
                                <h5 class="mb-1">
                                    <?php echo count($products); ?> Plugin<?php echo count($products) !== 1 ? 's' : ''; ?> Found
                                </h5>
                                <?php if (!empty($search)): ?>
                                <small class="text-muted">Search results for "<?php echo htmlspecialchars($search); ?>"</small>
                                <?php endif; ?>
                            </div>
                            
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary dropdown-toggle sort-dropdown" type="button" 
                                        data-bs-toggle="dropdown">
                                    <i class="fas fa-sort me-1"></i>
                                    Sort by: 
                                    <?php
                                    $sort_labels = [
                                        'featured' => 'Featured',
                                        'name_asc' => 'Name (A-Z)',
                                        'name_desc' => 'Name (Z-A)',
                                        'price_asc' => 'Price (Low to High)',
                                        'price_desc' => 'Price (High to Low)',
                                        'newest' => 'Newest',
                                        'popular' => 'Most Popular'
                                    ];
                                    echo $sort_labels[$sort] ?? 'Featured';
                                    ?>
                                </button>
                                <ul class="dropdown-menu">
                                    <?php foreach ($sort_labels as $sort_key => $sort_label): ?>
                                    <li>
                                        <a class="dropdown-item <?php echo $sort === $sort_key ? 'active' : ''; ?>" 
                                           href="?category=<?php echo $category_filter; ?>&price=<?php echo $price_filter; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort_key; ?>">
                                            <?php echo $sort_label; ?>
                                        </a>
                                    </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>

                        <!-- Products Grid -->
                        <?php if (empty($products)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-search fa-4x mb-3 text-muted"></i>
                            <h4>No plugins found</h4>
                            <p class="text-muted mb-4">
                                Try adjusting your search criteria or browse different categories.
                            </p>
                            <a href="browse-plugins.php" class="btn btn-primary">
                                <i class="fas fa-refresh me-2"></i>
                                Reset Filters
                            </a>
                        </div>
                        <?php else: ?>
                        <div class="row">
                            <?php foreach ($products as $product): ?>
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="plugin-card <?php echo $product['is_featured'] ? 'plugin-featured' : ''; ?>">
                                    <?php if ($product['is_featured']): ?>
                                    <div class="featured-badge">
                                        <i class="fas fa-star me-1"></i>
                                        Featured
                                    </div>
                                    <?php endif; ?>
                                    
                                    <!-- Plugin Image/Icon -->
                                    <div class="plugin-image">
                                        <i class="<?php echo $product['category_icon'] ?? 'fas fa-puzzle-piece'; ?>"></i>
                                    </div>
                                    
                                    <div class="plugin-content">
                                        <!-- Plugin Title -->
                                        <h5 class="plugin-title">
                                            <?php echo htmlspecialchars($product['name']); ?>
                                        </h5>
                                        
                                        <!-- Category Badge -->
                                        <div class="mb-2">
                                            <span class="badge bg-light text-dark">
                                                <i class="<?php echo $product['category_icon'] ?? 'fas fa-folder'; ?> me-1"></i>
                                                <?php echo $product['category_name']; ?>
                                            </span>
                                            
                                            <!-- Ownership Status -->
                                            <?php if (isset($user_licenses[$product['product_id']])): ?>
                                            <span class="owned-badge ms-1">
                                                <i class="fas fa-check me-1"></i>
                                                Owned
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- Description -->
                                        <p class="plugin-description">
                                            <?php echo htmlspecialchars($product['short_description']); ?>
                                        </p>
                                        
                                        <!-- Features -->
                                        <?php if ($product['features']): ?>
                                        <div class="plugin-features">
                                            <?php 
                                            $features = json_decode($product['features'], true);
                                            if (is_array($features)):
                                                foreach (array_slice($features, 0, 3) as $feature): 
                                            ?>
                                            <span class="feature-tag">
                                                <i class="fas fa-check me-1"></i>
                                                <?php echo htmlspecialchars($feature); ?>
                                            </span>
                                            <?php 
                                                endforeach;
                                                if (count($features) > 3):
                                            ?>
                                            <span class="feature-tag">
                                                +<?php echo count($features) - 3; ?> more
                                            </span>
                                            <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Supported Providers -->
                                        <?php if ($product['supported_providers']): ?>
                                        <div class="provider-icons">
                                            <?php 
                                            $providers = json_decode($product['supported_providers'], true);
                                            if (is_array($providers)):
                                                foreach (array_slice($providers, 0, 4) as $provider): 
                                            ?>
                                            <span class="provider-icon" title="<?php echo htmlspecialchars($provider); ?>">
                                                <?php echo strtoupper(substr($provider, 0, 2)); ?>
                                            </span>
                                            <?php endforeach; ?>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Rating -->
                                        <?php if ($product['rating_count'] > 0): ?>
                                        <div class="plugin-rating">
                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star<?php echo $i <= $product['rating_average'] ? '' : '-o'; ?>"></i>
                                            <?php endfor; ?>
                                            <small class="text-muted ms-1">
                                                (<?php echo $product['rating_count']; ?> review<?php echo $product['rating_count'] !== 1 ? 's' : ''; ?>)
                                            </small>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Price -->
                                        <div class="plugin-price">
                                            <?php if ($product['min_price'] == $product['max_price']): ?>
                                            $<?php echo number_format($product['min_price'], 2); ?>
                                            <?php else: ?>
                                            $<?php echo number_format($product['min_price'], 2); ?> - $<?php echo number_format($product['max_price'], 2); ?>
                                            <?php endif; ?>
                                            
                                            <?php if ($product['pricing_tiers'] > 1): ?>
                                            <small class="text-muted d-block">
                                                <?php echo $product['pricing_tiers']; ?> pricing tier<?php echo $product['pricing_tiers'] !== 1 ? 's' : ''; ?>
                                            </small>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Plugin Footer -->
                                    <div class="plugin-footer">
                                        <div class="d-grid gap-2">
                                            <a href="product-details.php?id=<?php echo $product['product_id']; ?>" 
                                               class="btn btn-primary">
                                                <i class="fas fa-info-circle me-1"></i>
                                                View Details
                                            </a>
                                            
                                            <div class="row g-1">
                                                <?php if ($product['demo_url']): ?>
                                                <div class="col">
                                                    <a href="<?php echo htmlspecialchars($product['demo_url']); ?>" 
                                                       target="_blank" class="btn btn-sm btn-outline-info w-100">
                                                        <i class="fas fa-external-link-alt"></i>
                                                        Demo
                                                    </a>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <div class="col">
                                                    <button class="btn btn-sm btn-outline-secondary w-100" 
                                                            onclick="addToWishlist(<?php echo $product['product_id']; ?>)">
                                                        <i class="fas fa-heart"></i>
                                                        Save
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Stats -->
                                        <div class="d-flex justify-content-between text-muted mt-2">
                                            <small>
                                                <i class="fas fa-download me-1"></i>
                                                <?php echo number_format($product['download_count']); ?> downloads
                                            </small>
                                            <small>
                                                <i class="fas fa-calendar me-1"></i>
                                                <?php echo date('M Y', strtotime($product['created_at'])); ?>
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <div class="row">
                            <div class="col-12">
                                <nav aria-label="Products pagination">
                                    <ul class="pagination justify-content-center">
                                        <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&category=<?php echo $category_filter; ?>&price=<?php echo $price_filter; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>">
                                                <i class="fas fa-chevron-left"></i>
                                            </a>
                                        </li>
                                        <?php endif; ?>
                                        
                                        <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                        <li class="page-item <?php echo $i === (int)$page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>&category=<?php echo $category_filter; ?>&price=<?php echo $price_filter; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        </li>
                                        <?php endfor; ?>
                                        
                                        <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&category=<?php echo $category_filter; ?>&price=<?php echo $price_filter; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>">
                                                <i class="fas fa-chevron-right"></i>
                                            </a>
                                        </li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>
                                
                                <div class="text-center text-muted">
                                    Showing <?php echo count($products); ?> of <?php echo $total_products; ?> plugins
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </div>

        <?php 
        if (file_exists('partials/footer.php')) {
            try {
                include_once 'partials/footer.php';
            } catch (Exception $e) {
                echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
            }
        } else {
            echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
        }
        ?>
    </div>
</div>

<?php 
if (file_exists('partials/footer-scripts.php')) {
    try {
        include_once 'partials/footer-scripts.php';
    } catch (Exception $e) {
        echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
    }
} else {
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
}
?>

<script>
function addToWishlist(productId) {
    // Add to wishlist functionality
    fetch('api/add-to-wishlist.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            product_id: productId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update button state
            const button = event.target.closest('button');
            button.innerHTML = '<i class="fas fa-heart text-danger"></i> Saved';
            button.classList.add('border-danger');
            
            // Show success message
            showToast('Product added to wishlist!', 'success');
        } else {
            showToast('Failed to add to wishlist', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('An error occurred', 'error');
    });
}

function showToast(message, type) {
    // Simple toast notification
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'success' ? 'success' : 'danger'} position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 250px;';
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check' : 'exclamation'}-circle me-2"></i>
        ${message}
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;
    
    document.body.appendChild(toast);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        if (toast.parentElement) {
            toast.remove();
        }
    }, 3000);
}

// Auto-submit search form on enter
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('input[name="search"]');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                this.form.submit();
            }
        });
    }
});
</script>

</body>
</html>