<?php
if (!defined('ABSPATH')) die('Restricted Access');
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-flash-tune'));
}
if (!function_exists('get_plugins')) {
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
}

$aiflt_page_title = __('Addon Manager', 'ai-flash-tune');
$highlight_addon = isset($_GET['addon']) ? sanitize_key(wp_unslash($_GET['addon'])) : '';

if (isset($_GET['aiflt_refresh_license'])) {
    delete_transient('aiflt_license_status_cache');
    delete_transient('aiflt_license_data_cache');
}

$license_key_saved = class_exists('AIFLT_License_Manager') && method_exists('AIFLT_License_Manager', 'has_saved_license_key') ? AIFLT_License_Manager::has_saved_license_key() : (get_option('aiflt_pro_license_key', '') !== '');
$status_data = class_exists('AIFLT_License_Manager') ? AIFLT_License_Manager::get_addon_statuses() : ['status' => 'unavailable', 'message' => __('License manager is unavailable.', 'ai-flash-tune'), 'data' => []];
$entitled_addons = is_array($status_data['data'] ?? null) ? $status_data['data'] : [];
$installed_plugins = get_plugins();

$all_possible_addons = [
    'ai-flash-tune-ai-action-center' => ['name'=>__('AI Action Center','ai-flash-tune'),'description'=>__('Turns funnel, cart, checkout, product, and speed signals into one prioritized conversion plan.','ai-flash-tune'),'symbol'=>'✦','category'=>__('Conversion command center','ai-flash-tune'),'target_page'=>'aiftac-action-center','buy_url'=>'https://aiflashtune.com/pricing#ai-action-center'],
    'ai-flash-tune-product-optimizer' => ['name'=>__('Product Optimizer','ai-flash-tune'),'description'=>__('Diagnose weak product pages, improve copy safely, clarify CTA, and strengthen trust without inventing claims.','ai-flash-tune'),'symbol'=>'↯','category'=>__('Product conversion','ai-flash-tune'),'target_page'=>'aiftpo-product-optimizer','buy_url'=>'https://aiflashtune.com/pricing#product-optimizer'],
    'ai-flash-tune-cart-recovery' => ['name'=>__('Cart Recovery & Abandonment Intelligence','ai-flash-tune'),'description'=>__('Review abandoned carts, identify likely reasons, plan recovery messages, and protect revenue.','ai-flash-tune'),'symbol'=>'✉','category'=>__('Cart recovery','ai-flash-tune'),'target_page'=>'aiftcr-recovery-center','buy_url'=>'https://aiflashtune.com/pricing#cart-recovery'],
    'ai-flash-tune-checkout-optimizer' => ['name'=>__('Checkout Optimizer','ai-flash-tune'),'description'=>__('Audit checkout friction and safely apply field, trust, and UX improvements with review-first controls.','ai-flash-tune'),'symbol'=>'▰','category'=>__('Checkout friction','ai-flash-tune'),'target_page'=>'aiftco-optimizer-dashboard','buy_url'=>'https://aiflashtune.com/pricing#checkout-optimizer'],
    'ai-flash-tune-advanced-segmentation' => ['name'=>__('Advanced Segmentation','ai-flash-tune'),'description'=>__('Compare desktop vs mobile, guest vs registered, product/category behavior, and funnel groups.','ai-flash-tune'),'symbol'=>'◿','category'=>__('Behavior comparison','ai-flash-tune'),'target_page'=>'aiftas-segmentation','buy_url'=>'https://aiflashtune.com/pricing#segmentation'],
    'ai-flash-tune-alert-center' => ['name'=>__('Alert Center','ai-flash-tune'),'description'=>__('Track urgent conversion risks such as checkout friction, abandoned-cart pressure, and slow-page warnings.','ai-flash-tune'),'symbol'=>'!','category'=>__('Risk monitoring','ai-flash-tune'),'target_page'=>'aiftal-alert-center','buy_url'=>'https://aiflashtune.com/pricing#alerts'],
    'ai-flash-tune-reports' => ['name'=>__('Reports & Exports','ai-flash-tune'),'description'=>__('Export weekly summaries, CSV files, and client-ready performance reports.','ai-flash-tune'),'symbol'=>'≡','category'=>__('Reporting','ai-flash-tune'),'target_page'=>'aiftrp-reports','buy_url'=>'https://aiflashtune.com/pricing#reports'],
];

$license_status = $status_data['status'] ?? 'unavailable';
$license_all_modules = ($license_status === 'success') && (!empty($status_data['all_modules']) || empty($entitled_addons));
if ($license_all_modules) {
    $entitled_addons = array_fill_keys(array_keys($all_possible_addons), ['enabled' => true, 'source' => 'pro_license']);
}

function aiflt_addon_card_state($addon_slug, $installed_plugins) {
    $state = ['installed'=>false,'active'=>false,'plugin_file'=>'','version'=>''];
    foreach ($installed_plugins as $file => $details) {
        if (strpos($file, $addon_slug . '/') === 0) {
            $state['installed'] = true;
            $state['plugin_file'] = $file;
            $state['version'] = $details['Version'] ?? '';
            $state['active'] = is_plugin_active($file);
            break;
        }
    }
    return $state;
}
$module_states = [];
$active_count = 0;
$installed_count = 0;
foreach ($all_possible_addons as $slug => $addon) {
    $state = aiflt_addon_card_state($slug, $installed_plugins);
    $module_states[$slug] = $state;
    if ($state['installed']) $installed_count++;
    if ($state['active']) $active_count++;
}
$total_count = count($all_possible_addons);
?>
<div class="ai-flash-tune-admin-wrapper">
    <?php include_once('ai-flash-tune-admin-sidebar.php'); ?>
    <div class="ai-flash-tune-main-content">
        <div class="ai-flash-tune-page-header ai-flash-tune-mb-8 aiflt-addon-manager-hero">
            <div>
                <span class="ai-flash-tune-main-title"><?php echo esc_html($aiflt_page_title); ?></span>
                <p class="ai-flash-tune-page-subtitle"><?php echo esc_html__('Install, activate, open, and track AI Flash Tune modules from one place.', 'ai-flash-tune'); ?></p>
            </div>
        </div>

        <div class="aiflt-addon-summary-grid ai-flash-tune-mb-8">
            <div class="aiflt-addon-summary-card"><span><?php echo esc_html__('Active modules','ai-flash-tune'); ?></span><strong><?php echo esc_html($active_count); ?></strong></div>
            <div class="aiflt-addon-summary-card"><span><?php echo esc_html__('Installed modules','ai-flash-tune'); ?></span><strong><?php echo esc_html($installed_count); ?></strong></div>
            <div class="aiflt-addon-summary-card"><span><?php echo esc_html__('Available modules','ai-flash-tune'); ?></span><strong><?php echo esc_html($total_count); ?></strong></div>
            <div class="aiflt-addon-summary-card"><span><?php echo esc_html__('License','ai-flash-tune'); ?></span><strong><?php echo esc_html(($license_status === 'success') ? __('Connected','ai-flash-tune') : ($license_key_saved ? __('Needs check','ai-flash-tune') : __('Missing','ai-flash-tune'))); ?></strong></div>
        </div>

        <?php if (($status_data['status'] ?? '') === 'no_key') : ?>
            <div class="ai-flash-tune-notice-bar ai-flash-tune-notice-info ai-flash-tune-mb-8"><div class="ai-flash-tune-notice-content"><span class="aiflt-notice-symbol">i</span><span><strong><?php echo esc_html__('License not connected.', 'ai-flash-tune'); ?></strong> <?php echo esc_html__('Add your PRO license key in Settings to validate the order, download modules, activate this site, and receive updates.', 'ai-flash-tune'); ?> <a href="<?php echo esc_url(admin_url('admin.php?page=aiflt_settings')); ?>" class="ai-flash-tune-font-bold hover:underline ml-2"><?php echo esc_html__('Open Settings','ai-flash-tune'); ?></a></span></div></div>
        <?php elseif (($status_data['status'] ?? '') === 'success') : ?>
            <div class="ai-flash-tune-notice-bar ai-flash-tune-notice-success ai-flash-tune-mb-8"><div class="ai-flash-tune-notice-content"><span class="aiflt-notice-symbol">✓</span><span><strong><?php echo esc_html__('License connected.', 'ai-flash-tune'); ?></strong> <?php echo esc_html($license_all_modules ? __('Your PRO license is valid. All AI Flash Tune modules are available to install.', 'ai-flash-tune') : __('Your license is valid. Available modules are based on the server entitlement response.', 'ai-flash-tune')); ?> <a href="<?php echo esc_url(add_query_arg('aiflt_refresh_license', '1', admin_url('admin.php?page=aiflt_addon_manager'))); ?>" class="ai-flash-tune-font-bold hover:underline ml-2"><?php echo esc_html__('Refresh license','ai-flash-tune'); ?></a></span></div></div>
        <?php else : ?>
            <div class="ai-flash-tune-notice-bar ai-flash-tune-notice-warning ai-flash-tune-mb-8"><div class="ai-flash-tune-notice-content"><span class="aiflt-notice-symbol">!</span><span><strong><?php echo esc_html__('License check needs attention.', 'ai-flash-tune'); ?></strong> <?php echo esc_html($status_data['message'] ?? __('Unable to verify license.', 'ai-flash-tune')); ?> <a href="<?php echo esc_url(add_query_arg('aiflt_refresh_license', '1', admin_url('admin.php?page=aiflt_addon_manager'))); ?>" class="ai-flash-tune-font-bold hover:underline ml-2"><?php echo esc_html__('Recheck license','ai-flash-tune'); ?></a> <a href="<?php echo esc_url(admin_url('admin.php?page=aiflt_settings')); ?>" class="ai-flash-tune-font-bold hover:underline ml-2"><?php echo esc_html__('Review key','ai-flash-tune'); ?></a></span></div></div>
        <?php endif; ?>

        <div class="ai-flash-tune-card ai-flash-tune-mb-8 aiflt-addon-manager-card">
            <div class="aiflt-addon-manager-heading">
                <div>
                    <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-card-title"><?php echo esc_html__('Modules', 'ai-flash-tune'); ?></span>
                    <p class="ai-flash-tune-text-gray-600 ai-flash-tune-mb-0"><?php echo esc_html__('Each card shows install, activation, license, and update status for every AI Flash Tune module.', 'ai-flash-tune'); ?></p>
                </div>
                <?php if (!empty($highlight_addon)) : ?><span class="aiflt-focus-pill"><?php echo esc_html__('Focused from previous screen', 'ai-flash-tune'); ?></span><?php endif; ?>
            </div>
            <div class="aiflt-addon-grid">
                <?php foreach ($all_possible_addons as $aiflt_slug => $addon) : ?>
                    <?php
                    $state = $module_states[$aiflt_slug];
                    $is_entitled = isset($entitled_addons[$aiflt_slug]);
                    $is_highlighted = $highlight_addon === $aiflt_slug;
                    $status_class = $state['active'] ? 'is-active' : ($state['installed'] ? 'is-installed' : 'is-available');
                    $status_label = $state['active'] ? __('Active','ai-flash-tune') : ($state['installed'] ? __('Installed','ai-flash-tune') : __('Not installed','ai-flash-tune'));
                    ?>
                    <div id="<?php echo esc_attr($aiflt_slug); ?>" class="aiflt-addon-card <?php echo esc_attr($status_class); ?> <?php echo $is_highlighted ? 'is-highlighted' : ''; ?>">
                        <div class="aiflt-addon-card-top">
                            <span class="aiflt-addon-symbol" aria-hidden="true"><?php echo esc_html($addon['symbol']); ?></span>
                            <div class="aiflt-addon-title-wrap"><span class="aiflt-addon-category"><?php echo esc_html($addon['category']); ?></span><h3><?php echo esc_html($addon['name']); ?></h3></div>
                            <span class="aiflt-addon-status-badge <?php echo esc_attr($status_class); ?>"><?php echo esc_html($status_label); ?></span>
                        </div>
                        <p class="aiflt-addon-description"><?php echo esc_html($addon['description']); ?></p>
                        <div class="aiflt-addon-meta-row"><span><?php echo esc_html__('Version:', 'ai-flash-tune'); ?> <strong><?php echo $state['version'] ? esc_html($state['version']) : esc_html__('—','ai-flash-tune'); ?></strong></span><span><?php echo esc_html__('Updates:', 'ai-flash-tune'); ?> <strong><?php echo esc_html__('Manual check', 'ai-flash-tune'); ?></strong></span></div>
                        <div class="aiflt-addon-actions" data-addon-slug="<?php echo esc_attr($aiflt_slug); ?>" data-token="<?php echo esc_attr($status_data['token'] ?? ''); ?>">
                            <?php if ($state['active']) : ?>
                                <a class="ai-flash-tune-btn ai-flash-tune-btn-blue" href="<?php echo esc_url(admin_url('admin.php?page=' . $addon['target_page'])); ?>"><?php echo esc_html__('Open module', 'ai-flash-tune'); ?></a>
                                <button type="button" class="ai-flash-tune-btn ai-flash-tune-btn-gray aift-manage-addon-btn" data-action="deactivate"><?php echo esc_html__('Deactivate', 'ai-flash-tune'); ?></button>
                                <button type="button" class="ai-flash-tune-btn ai-flash-tune-btn-light aift-manage-addon-btn" data-action="check_update"><?php echo esc_html__('Check update', 'ai-flash-tune'); ?></button>
                            <?php elseif ($state['installed']) : ?>
                                <button type="button" class="ai-flash-tune-btn ai-flash-tune-btn-green aift-manage-addon-btn" data-action="activate"><?php echo esc_html__('Activate module', 'ai-flash-tune'); ?></button>
                                <button type="button" class="ai-flash-tune-btn ai-flash-tune-btn-light aift-manage-addon-btn" data-action="check_update"><?php echo esc_html__('Check update', 'ai-flash-tune'); ?></button>
                                <button type="button" class="ai-flash-tune-btn ai-flash-tune-btn-gray aift-manage-addon-btn" data-action="delete"><?php echo esc_html__('Delete', 'ai-flash-tune'); ?></button>
                            <?php elseif ($is_entitled) : ?>
                                <button type="button" class="ai-flash-tune-btn ai-flash-tune-btn-blue aift-manage-addon-btn" data-action="install"><?php echo esc_html__('Install module', 'ai-flash-tune'); ?></button>
                            <?php elseif ($license_key_saved) : ?>
                                <a href="<?php echo esc_url(add_query_arg('aiflt_refresh_license', '1', admin_url('admin.php?page=aiflt_addon_manager'))); ?>" class="ai-flash-tune-btn ai-flash-tune-btn-gray"><?php echo esc_html__('Check license', 'ai-flash-tune'); ?></a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=aiflt_settings')); ?>" class="ai-flash-tune-btn ai-flash-tune-btn-light"><?php echo esc_html__('Review key', 'ai-flash-tune'); ?></a>
                            <?php else : ?>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=aiflt_settings')); ?>" class="ai-flash-tune-btn ai-flash-tune-btn-gray"><?php echo esc_html__('Add license', 'ai-flash-tune'); ?></a>
                                <a href="<?php echo esc_url($addon['buy_url']); ?>" target="_blank" rel="noopener" class="ai-flash-tune-btn ai-flash-tune-btn-light"><?php echo esc_html__('Learn more', 'ai-flash-tune'); ?></a>
                            <?php endif; ?>
                            <span class="aift-spinner" style="display:none;"><span class="aiflt-mini-spinner"></span></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>
<?php if (!empty($highlight_addon)) : ?>
<script>
jQuery(function($){
    var target = $('#<?php echo esc_js($highlight_addon); ?>');
    if (target.length) { $('html, body').animate({ scrollTop: target.offset().top - 120 }, 350); }
});
</script>
<?php endif; ?>
