<?php
/**
 * DevDiggers Extensions Page Template
 *
 * @author DevDiggers
 * @version 1.0.0
 * @package DevDiggers\Framework
 */

use DevDiggers\Framework\Includes\DDFW_SVG;

defined( 'ABSPATH' ) || exit(); // Exit if accessed directly.

// Get website plugins
$plugins_api = DDFW_Plugins_API::instance();
$website_plugins = $plugins_api->get_website_plugins();
$featured_plugins = $plugins_api->get_featured_plugins();
$plugin_stats = $plugins_api->get_plugin_statistics();

// Get installed plugins for comparison
$installed_plugins = get_plugins();
$active_plugins = get_option('active_plugins', []);
?>

<div class="wrap devdiggers-wrap">
    <div class="ddfw-extensions-page">
    <!-- Page Header -->
    <div class="ddfw-page-header">
        <div class="ddfw-page-title">
            <h1><?php esc_html_e('DevDiggers Extensions', 'devdiggers-framework'); ?></h1>
            <p><?php esc_html_e('Discover and manage all available DevDiggers WooCommerce extensions', 'devdiggers-framework'); ?></p>
        </div>
        <div class="ddfw-page-actions">
            <button type="button" class="ddfw-button ddfw-button-secondary" onclick="refreshExtensionsCache()">
                <?php DDFW_SVG::get_svg_icon('refresh', false, ['size' => 16]); ?>
                <?php esc_html_e('Refresh', 'devdiggers-framework'); ?>
            </button>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="ddfw-extensions-stats">
        <div class="ddfw-stat-card">
            <div class="ddfw-stat-icon">
                <?php DDFW_SVG::get_svg_icon('puzzle-piece', false, ['size' => 24]); ?>
            </div>
            <div class="ddfw-stat-content">
                <h3><?php echo esc_html($plugin_stats['total_plugins']); ?></h3>
                <p><?php esc_html_e('Total Extensions', 'devdiggers-framework'); ?></p>
            </div>
        </div>
        
        <div class="ddfw-stat-card">
            <div class="ddfw-stat-icon">
                <?php DDFW_SVG::get_svg_icon('star', false, ['size' => 24]); ?>
            </div>
            <div class="ddfw-stat-content">
                <h3><?php echo esc_html($plugin_stats['average_rating']); ?></h3>
                <p><?php esc_html_e('Average Rating', 'devdiggers-framework'); ?></p>
            </div>
        </div>
        
        <div class="ddfw-stat-card">
            <div class="ddfw-stat-icon">
                <?php DDFW_SVG::get_svg_icon('download', false, ['size' => 24]); ?>
            </div>
            <div class="ddfw-stat-content">
                <h3><?php echo esc_html($plugin_stats['total_sales']); ?>+</h3>
                <p><?php esc_html_e('Total Downloads', 'devdiggers-framework'); ?></p>
            </div>
        </div>
        
        <div class="ddfw-stat-card">
            <div class="ddfw-stat-icon">
                <?php DDFW_SVG::get_svg_icon('check-circle', false, ['size' => 24]); ?>
            </div>
            <div class="ddfw-stat-content">
                <h3><?php echo esc_html($plugin_stats['active_plugins']); ?></h3>
                <p><?php esc_html_e('Installed', 'devdiggers-framework'); ?></p>
            </div>
        </div>
    </div>

    <!-- Featured Extensions -->
    <?php if (!empty($featured_plugins)): ?>
    <div class="ddfw-featured-section">
        <h2><?php esc_html_e('Featured Extensions', 'devdiggers-framework'); ?></h2>
        <div class="ddfw-featured-grid">
            <?php foreach ($featured_plugins as $plugin): ?>
                <?php
                $is_installed = false;
                $is_active = false;
                $admin_url = '';

                foreach ($installed_plugins as $plugin_file => $installed_plugin) {
                    if (strpos($installed_plugin['Name'], $plugin['name']) !== false ||
                        strpos($installed_plugin['Name'], 'DevDiggers') !== false) {
                        $is_installed = true;
                        $is_active = in_array($plugin_file, $active_plugins);
                        $plugin_slug = dirname($plugin_file);
                        $admin_url = admin_url('admin.php?page=' . $plugin_slug . '-dashboard');
                        break;
                    }
                }
                ?>
                <div class="ddfw-featured-card <?php echo $is_active ? 'ddfw-plugin-active' : ($is_installed ? 'ddfw-plugin-installed' : 'ddfw-plugin-available'); ?>">
                    <div class="ddfw-plugin-image">
                        <img src="<?php echo esc_url($plugin['image']); ?>" alt="<?php echo esc_attr($plugin['name']); ?>" />
                        <?php if ($is_active): ?>
                            <div class="ddfw-plugin-badge ddfw-badge-active">
                                <?php esc_html_e('Active', 'devdiggers-framework'); ?>
                            </div>
                        <?php elseif ($is_installed): ?>
                            <div class="ddfw-plugin-badge ddfw-badge-installed">
                                <?php esc_html_e('Installed', 'devdiggers-framework'); ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="ddfw-plugin-content">
                        <h3><?php echo esc_html($plugin['name']); ?></h3>
                        <p><?php echo esc_html($plugin['description']); ?></p>
                        <div class="ddfw-plugin-meta">
                            <span class="ddfw-plugin-price"><?php echo esc_html($plugin['price']); ?></span>
                            <span class="ddfw-plugin-rating">
                                <?php DDFW_SVG::get_svg_icon('star', false, ['size' => 14]); ?>
                                <?php echo esc_html($plugin['rating']); ?>
                            </span>
                        </div>
                        <?php if ($is_active): ?>
                            <a href="<?php echo esc_url($admin_url); ?>" class="ddfw-button ddfw-button-primary">
                                <?php esc_html_e('Configure', 'devdiggers-framework'); ?>
                            </a>
                        <?php elseif ($is_installed): ?>
                            <a href="<?php echo esc_url(admin_url('plugins.php')); ?>" class="ddfw-button ddfw-button-secondary">
                                <?php esc_html_e('Activate', 'devdiggers-framework'); ?>
                            </a>
                        <?php else: ?>
                            <a href="<?php echo esc_url($plugin['url']); ?>" target="_blank" class="ddfw-button ddfw-button-primary">
                                <?php esc_html_e('View Extension', 'devdiggers-framework'); ?>
                                <?php DDFW_SVG::get_svg_icon('external-link', false, ['size' => 14]); ?>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- All Extensions -->
    <div class="ddfw-all-extensions-section">
        <div class="ddfw-section-header">
            <h2><?php esc_html_e('All Extensions', 'devdiggers-framework'); ?></h2>
            <div class="ddfw-filter-controls">
                <select id="category-filter" class="ddfw-select">
                    <option value=""><?php esc_html_e('All Categories', 'devdiggers-framework'); ?></option>
                    <?php
                    $categories = array_unique(array_column($website_plugins, 'category'));
                    foreach ($categories as $category): ?>
                        <option value="<?php echo esc_attr($category); ?>"><?php echo esc_html($category); ?></option>
                    <?php endforeach; ?>
                </select>
                <select id="status-filter" class="ddfw-select">
                    <option value=""><?php esc_html_e('All Status', 'devdiggers-framework'); ?></option>
                    <option value="active"><?php esc_html_e('Active', 'devdiggers-framework'); ?></option>
                    <option value="installed"><?php esc_html_e('Installed', 'devdiggers-framework'); ?></option>
                    <option value="available"><?php esc_html_e('Available', 'devdiggers-framework'); ?></option>
                </select>
            </div>
        </div>
        
        <div class="ddfw-extensions-grid" id="extensions-grid">
            <?php foreach ($website_plugins as $plugin): ?>
                <?php
                $is_installed = false;
                $is_active = false;
                $admin_url = '';

                foreach ($installed_plugins as $plugin_file => $installed_plugin) {
                    if (strpos($installed_plugin['Name'], $plugin['name']) !== false ||
                        strpos($installed_plugin['Name'], 'DevDiggers') !== false) {
                        $is_installed = true;
                        $is_active = in_array($plugin_file, $active_plugins);
                        $plugin_slug = dirname($plugin_file);
                        $admin_url = admin_url('admin.php?page=' . $plugin_slug . '-dashboard');
                        break;
                    }
                }
                ?>
                <div class="ddfw-extension-card <?php echo $is_active ? 'ddfw-plugin-active' : ($is_installed ? 'ddfw-plugin-installed' : 'ddfw-plugin-available'); ?>" 
                     data-category="<?php echo esc_attr($plugin['category']); ?>" 
                     data-status="<?php echo $is_active ? 'active' : ($is_installed ? 'installed' : 'available'); ?>">
                    <div class="ddfw-plugin-image">
                        <img src="<?php echo esc_url($plugin['image']); ?>" alt="<?php echo esc_attr($plugin['name']); ?>" />
                        <?php if ($is_active): ?>
                            <div class="ddfw-plugin-badge ddfw-badge-active">
                                <?php esc_html_e('Active', 'devdiggers-framework'); ?>
                            </div>
                        <?php elseif ($is_installed): ?>
                            <div class="ddfw-plugin-badge ddfw-badge-installed">
                                <?php esc_html_e('Installed', 'devdiggers-framework'); ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="ddfw-plugin-content">
                        <div class="ddfw-plugin-header">
                            <h3><?php echo esc_html($plugin['name']); ?></h3>
                            <span class="ddfw-plugin-category"><?php echo esc_html($plugin['category']); ?></span>
                        </div>
                        <p><?php echo esc_html($plugin['description']); ?></p>
                        <div class="ddfw-plugin-meta">
                            <span class="ddfw-plugin-rating">
                                <?php DDFW_SVG::get_svg_icon('star', false, ['size' => 14]); ?>
                                <?php echo esc_html($plugin['rating']); ?>
                            </span>
                            <span class="ddfw-plugin-sales"><?php echo esc_html($plugin['sales']); ?></span>
                            <span class="ddfw-plugin-price"><?php echo esc_html($plugin['price']); ?></span>
                        </div>
                        <div class="ddfw-plugin-features">
                            <?php foreach ($plugin['features'] as $feature): ?>
                                <span class="ddfw-feature-tag"><?php echo esc_html($feature); ?></span>
                            <?php endforeach; ?>
                        </div>
                        <div class="ddfw-plugin-actions">
                            <?php if ($is_active): ?>
                                <a href="<?php echo esc_url($admin_url); ?>" class="ddfw-button ddfw-button-primary">
                                    <?php esc_html_e('Configure', 'devdiggers-framework'); ?>
                                </a>
                            <?php elseif ($is_installed): ?>
                                <a href="<?php echo esc_url(admin_url('plugins.php')); ?>" class="ddfw-button ddfw-button-secondary">
                                    <?php esc_html_e('Activate', 'devdiggers-framework'); ?>
                                </a>
                            <?php else: ?>
                                <a href="<?php echo esc_url($plugin['url']); ?>" target="_blank" class="ddfw-button ddfw-button-primary">
                                    <?php esc_html_e('View Extension', 'devdiggers-framework'); ?>
                                    <?php DDFW_SVG::get_svg_icon('external-link', false, ['size' => 14]); ?>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
function refreshExtensionsCache() {
    const extensionsGrid = document.getElementById('extensions-grid');
    if (!extensionsGrid) return;

    extensionsGrid.style.opacity = '0.5';
    
    fetch(ddfwFrameworkObject.ajax.ajaxUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=ddfw_refresh_plugins_cache&nonce=${ddfwFrameworkObject.ajax.ajaxNonce}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.reload();
        } else {
            extensionsGrid.style.opacity = '1';
            alert('Failed to refresh extensions cache');
        }
    })
    .catch(error => {
        console.error('Error refreshing extensions cache:', error);
        extensionsGrid.style.opacity = '1';
        alert('Error refreshing extensions cache');
    });
}

// Filter functionality
document.addEventListener('DOMContentLoaded', function() {
    const categoryFilter = document.getElementById('category-filter');
    const statusFilter = document.getElementById('status-filter');
    const extensionCards = document.querySelectorAll('.ddfw-extension-card');

    function filterExtensions() {
        const selectedCategory = categoryFilter.value;
        const selectedStatus = statusFilter.value;

        extensionCards.forEach(card => {
            const cardCategory = card.getAttribute('data-category');
            const cardStatus = card.getAttribute('data-status');

            const categoryMatch = !selectedCategory || cardCategory === selectedCategory;
            const statusMatch = !selectedStatus || cardStatus === selectedStatus;

            if (categoryMatch && statusMatch) {
                card.style.display = 'block';
            } else {
                card.style.display = 'none';
            }
        });
    }

    categoryFilter.addEventListener('change', filterExtensions);
    statusFilter.addEventListener('change', filterExtensions);
});
</script>
    </div>
</div>
