<?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'));
}
$aiflt_page_title = __('Product Performance', 'ai-flash-tune');
// --- Check if addons are active to conditionally show features ---
$aiflt_is_product_doctor_active = is_plugin_active('ai-flash-tune-product-doctor/ai-flash-tune-product-doctor.php');
$aiflt_is_copy_enhancer_active = is_plugin_active('ai-flash-tune-copy-enhancer/ai-flash-tune-copy-enhancer.php');

// --- NEW LOGIC START ---
$aiflt_plugin_install_time = get_option('aiflt_activation_time', time());
$aiflt_default_start_timestamp = strtotime('-30 days');
$aiflt_min_valid_start_timestamp = $aiflt_plugin_install_time;

// Determine the earliest valid default date
$aiflt_effective_start_timestamp = max($aiflt_default_start_timestamp, $aiflt_min_valid_start_timestamp);
$aiflt_effective_default_start_date = gmdate('Y-m-d', $aiflt_effective_start_timestamp);
// --- NEW LOGIC END ---

// Only run database queries if WooCommerce is active to prevent errors.
if (aiflt_is_woocommerce_active()) {
    $aiflt_current_page = isset($_GET['paged']) ? intval($_GET['paged']) : 1;
    $aiflt_products_per_page = 10;
    $aiflt_offset = ($aiflt_current_page - 1) * $aiflt_products_per_page;
    
    // CRITICAL FIX: Use the calculated effective start date if not already set by GET param.
    $aiflt_start_date = isset($_GET['start_date']) ? sanitize_text_field(wp_unslash($_GET['start_date'])) : $aiflt_effective_default_start_date;
    $aiflt_end_date = isset($_GET['end_date']) ? sanitize_text_field(wp_unslash($_GET['end_date'])) : gmdate('Y-m-d');
    $aiflt_status_filter = isset($_GET['status_filter']) ? sanitize_text_field(wp_unslash($_GET['status_filter'])) : null;

    $aiflt_products_data = AIFLT_Products_Logic::get_all_products_with_stats($aiflt_products_per_page, $aiflt_offset, $aiflt_start_date, $aiflt_end_date, $aiflt_status_filter);
    $aiflt_products = $aiflt_products_data['products'];
    $aiflt_total_products = $aiflt_products_data['total_products'];
    $aiflt_total_pages = ceil($aiflt_total_products / $aiflt_products_per_page);
}
?>
<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-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mb-8 ai-flash-tune-page-header">
            <span class="ai-flash-tune-main-title"><?php echo esc_html($aiflt_page_title); ?></span>
            <?php
            if (aiflt_is_woocommerce_active()) { ?>
                <div class="ai-flash-tune-header-actions-wrapper">
                    <div class="ai-flash-tune-flex ai-flash-tune-flex-center ai-flash-tune-space-x-4 ai-flash-tune-header-actions">
                        <span class="ai-flash-tune-text-gray-600 ai-flash-tune-text-sm ai-flash-tune-last-updated">
                            <?php echo esc_html(gmdate('M d, Y', strtotime($aiflt_start_date))) . ' - ' . esc_html(gmdate('M d, Y', strtotime($aiflt_end_date))); ?>
                        </span>
                        <a class="ai-flash-tune-bg-blue-500 hover:ai-flash-tune-bg-blue-600 ai-flash-tune-text-white ai-flash-tune-font-semibold ai-flash-tune-py-2 ai-flash-tune-px-4 ai-flash-tune-rounded-lg ai-flash-tune-shadow-md ai-flash-tune-date-range-toggle" href="#">
                            <i class="fas fa-filter ai-flash-tune-mr-2"></i> <?php echo esc_html(__('Filters', 'ai-flash-tune')); ?>
                        </a>
                    </div>

                    <div id="ai-flash-tune-date-range-form-wrapper" class="ai-flash-tune-card ai-flash-tune-date-range-form hidden">
                        <form method="GET" class="ai-flash-tune-flex">
                            <input type="hidden" name="page" value="products" />
                            <div class="ai-flash-tune-date-range-field">
                                <label for="aiflt-products-start-date"><?php echo esc_html__('Start Date', 'ai-flash-tune'); ?></label>
                                <input type="text" id="aiflt-products-start-date" name="start_date" value="<?php echo esc_attr($aiflt_start_date); ?>" />
                            </div>
                            <div class="ai-flash-tune-date-range-field">
                                <label for="aiflt-products-end-date"><?php echo esc_html__('End Date', 'ai-flash-tune'); ?></label>
                                <input type="text" id="aiflt-products-end-date" name="end_date" value="<?php echo esc_attr($aiflt_end_date); ?>" />
                            </div>
                            <div class="ai-flash-tune-date-range-field">
                                <label for="status_filter"><?php echo esc_html__('Status', 'ai-flash-tune'); ?></label>
                                <select name="status_filter" id="status_filter">
                                    <option value="" <?php selected($aiflt_status_filter, ''); ?>><?php echo esc_html__('All Status', 'ai-flash-tune'); ?></option>
                                    <option value="Low-Performing" <?php selected($aiflt_status_filter, 'Low-Performing'); ?>><?php echo esc_html__('Low-Performing', 'ai-flash-tune'); ?></option>
                                    <option value="Good" <?php selected($aiflt_status_filter, 'Good'); ?>><?php echo esc_html__('Good', 'ai-flash-tune'); ?></option>
                                    <option value="Critical Leak" <?php selected($aiflt_status_filter, 'Critical Leak'); ?>><?php echo esc_html__('Critical Leak', 'ai-flash-tune'); ?></option>
                                    <option value="Needs Data" <?php selected($aiflt_status_filter, 'Needs Data'); ?>><?php echo esc_html__('Needs Data', 'ai-flash-tune'); ?></option>
                                </select>
                            </div>
                            <input type="submit" value="<?php echo esc_attr(__('Apply', 'ai-flash-tune')); ?>" class="ai-flash-tune-btn ai-flash-tune-btn-blue" />
                        </form>
                    </div>
                </div>
                <?php
            } ?>
        </div>
        <?php
        // Check for WooCommerce dependency at the top of the view file.
        if (!aiflt_is_woocommerce_active()) {
            $aiflt_install_url = admin_url('plugin-install.php?s=woocommerce&tab=search&type=term');
            $aiflt_wc_status = aiflt_get_woocommerce_status(); // Call the helper function
            ?>
            <div class="ai-flash-tune-wc-required-notice">
                <i class="fas fa-plug ai-flash-tune-notice-icon"></i>
                <p class="ai-flash-tune-notice-title"><?php echo esc_html__('WooCommerce is Required', 'ai-flash-tune'); ?></p>
                <p class="ai-flash-tune-notice-text"><?php echo esc_html__('This page requires WooCommerce to be installed and active to display product data. Please install or activate WooCommerce to continue.', 'ai-flash-tune'); ?></p>
                <a href="<?php echo esc_url($aiflt_wc_status['action_url']); ?>" class="ai-flash-tune-notice-button">
                    <?php echo esc_html($aiflt_wc_status['button_text']); ?>
                </a>
            </div>
            <?php
            return; // Stop rendering the rest of the page.
        } ?>
        <div class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-data-readiness-card">
            <div class="ai-flash-tune-free-card-header">
                <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-card-title">
                    <i class="fas fa-info-circle ai-flash-tune-text-indigo-600 ai-flash-tune-mr-2"></i><?php echo esc_html__('Product data readiness', 'ai-flash-tune'); ?>
                </span>
                <span class="ai-flash-tune-free-subtle-label"><?php echo esc_html__('Free local tracking', 'ai-flash-tune'); ?></span>
            </div>
            <p class="ai-flash-tune-text-gray-700 ai-flash-tune-section-description">
                <?php echo esc_html__('“Needs Data” means a product does not yet have enough tracked views, cart activity, or sales in the selected date range to calculate reliable performance. Visit product pages as a non-admin visitor, add products to cart, and refresh this report to confirm tracking.', 'ai-flash-tune'); ?>
            </p>
        </div>
        <div class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-products-section">
            <div class="ai-flash-tune-table-wrp">
                <table class="ai-flash-tune-min-w-full ai-flash-tune-divide-y ai-flash-tune-divide-gray-200 ai-flash-tune-product-table">
                    <thead class="ai-flash-tune-bg-gray-50">
                        <tr>
                            <th scope="col" class="ai-flash-tune-px-6 ai-flash-tune-py-3 ai-flash-tune-text-left ai-flash-tune-text-xs ai-flash-tune-font-medium ai-flash-tune-text-gray-500 ai-flash-tune-uppercase ai-flash-tune-tracking-wider" style="width: 50px;"><?php echo esc_html(__('Image', 'ai-flash-tune')); ?></th>
                            <th scope="col" class="ai-flash-tune-px-6 ai-flash-tune-py-3 ai-flash-tune-text-left ai-flash-tune-text-xs ai-flash-tune-font-medium ai-flash-tune-text-gray-500 ai-flash-tune-uppercase ai-flash-tune-tracking-wider"><?php echo esc_html(__('Product Name', 'ai-flash-tune')); ?></th>
                            <th scope="col" class="ai-flash-tune-px-6 ai-flash-tune-py-3 ai-flash-tune-text-left ai-flash-tune-text-xs ai-flash-tune-font-medium ai-flash-tune-text-gray-500 ai-flash-tune-uppercase ai-flash-tune-tracking-wider"><?php echo esc_html(__('Traffic (Views)', 'ai-flash-tune')); ?></th>
                            <th scope="col" class="ai-flash-tune-px-6 ai-flash-tune-py-3 ai-flash-tune-text-left ai-flash-tune-text-xs ai-flash-tune-font-medium ai-flash-tune-text-gray-500 ai-flash-tune-uppercase ai-flash-tune-tracking-wider"><?php echo esc_html(__('Sales', 'ai-flash-tune')); ?></th>
                            <th scope="col" class="ai-flash-tune-px-6 ai-flash-tune-py-3 ai-flash-tune-text-left ai-flash-tune-text-xs ai-flash-tune-font-medium ai-flash-tune-text-gray-500 ai-flash-tune-uppercase ai-flash-tune-tracking-wider"><?php echo esc_html(__('Conversion Rate', 'ai-flash-tune')); ?></th>
                            <th scope="col" class="ai-flash-tune-px-6 ai-flash-tune-py-3 ai-flash-tune-text-left ai-flash-tune-text-xs ai-flash-tune-font-medium ai-flash-tune-text-gray-500 ai-flash-tune-uppercase ai-flash-tune-tracking-wider"><?php echo esc_html(__('Status', 'ai-flash-tune')); ?></th>
                            <th scope="col" class="ai-flash-tune-px-6 ai-flash-tune-py-3 ai-flash-tune-text-left ai-flash-tune-text-xs ai-flash-tune-font-medium ai-flash-tune-text-gray-500 ai-flash-tune-uppercase ai-flash-tune-tracking-wider"><?php echo esc_html(__('Actions', 'ai-flash-tune')); ?></th>
                        </tr>
                    </thead>
                    <tbody class="ai-flash-tune-bg-white ai-flash-tune-divide-y ai-flash-tune-divide-gray-200">
                        <?php if (!empty($aiflt_products)) : ?>
                            <?php foreach ($aiflt_products as $aiflt_product) { ?>
                                <tr class="ai-flash-tune-product-row" data-product-id="<?php echo esc_attr($aiflt_product['product_id']); ?>" id="product-<?php echo esc_attr($aiflt_product['product_id']); ?>">
                                    <td data-label="<?php echo esc_attr__('Image', 'ai-flash-tune'); ?>" class="ai-flash-tune-px-6 ai-flash-tune-py-4">
                                        <?php 
                                        echo get_the_post_thumbnail(
                                            $aiflt_product['product_id'], 
                                            'thumbnail', 
                                            array('class' => 'ai-flash-tune-product-thumb', 'style' => 'max-width: 40px; height: auto;')
                                        ); 
                                        ?>
                                    </td>
                                    <td data-label="<?php echo esc_attr__('Product', 'ai-flash-tune'); ?>" class="ai-flash-tune-px-6 ai-flash-tune-py-4 ai-flash-tune-whitespace-nowrap ai-flash-tune-text-sm ai-flash-tune-font-medium ai-flash-tune-text-gray-900">
                                        <a target="_blank" href="<?php echo esc_url($aiflt_product['edit_link']); ?>">
                                            <?php echo esc_html($aiflt_product['name']); ?>
                                        </a>
                                    </td>
                                    <td data-label="<?php echo esc_attr__('Views', 'ai-flash-tune'); ?>" class="ai-flash-tune-px-6 ai-flash-tune-py-4 ai-flash-tune-whitespace-nowrap ai-flash-tune-text-sm ai-flash-tune-font-medium ai-flash-tune-text-gray-900"><?php echo esc_html($aiflt_product['views']); ?></td>
                                    <td data-label="<?php echo esc_attr__('Sales', 'ai-flash-tune'); ?>" class="ai-flash-tune-px-6 ai-flash-tune-py-4 ai-flash-tune-whitespace-nowrap ai-flash-tune-text-sm ai-flash-tune-font-medium ai-flash-tune-text-gray-900"><?php echo esc_html($aiflt_product['sales']); ?></td>
                                    <td data-label="<?php echo esc_attr__('Conversion', 'ai-flash-tune'); ?>" class="ai-flash-tune-px-6 ai-flash-tune-py-4 ai-flash-tune-whitespace-nowrap ai-flash-tune-text-sm ai-flash-tune-font-medium ai-flash-tune-text-gray-900"><?php echo esc_html($aiflt_product['conversion_rate']); ?></td>
                                    <td data-label="<?php echo esc_attr__('Status', 'ai-flash-tune'); ?>" class="ai-flash-tune-px-6 ai-flash-tune-py-4 ai-flash-tune-whitespace-nowrap ai-flash-tune-text-sm ai-flash-tune-font-medium ai-flash-tune-text-gray-900">
                                        <?php
                                            $aiflt_status_class = 'ai-flash-tune-status-sent';
                                            if (in_array($aiflt_product['status'], ['Low-Performing', 'Critical Leak'], true)) {
                                                $aiflt_status_class = 'ai-flash-tune-status-failed';
                                            } elseif ($aiflt_product['status'] === 'Needs Data') {
                                                $aiflt_status_class = 'ai-flash-tune-status-waiting';
                                            }
                                            $aiflt_status_title = ($aiflt_product['status'] === 'Needs Data')
                                                ? __('This product needs more tracked views, cart activity, or sales before performance can be judged reliably.', 'ai-flash-tune')
                                                : '';
                                        ?>
                                        <span title="<?php echo esc_attr($aiflt_status_title); ?>" class="ai-flash-tune-leading-5 ai-flash-tune-status-badge <?php echo esc_attr($aiflt_status_class); ?>"><?php echo esc_html($aiflt_product['status']); ?></span>
                                    </td>
                                    <td data-label="<?php echo esc_attr__('Actions', 'ai-flash-tune'); ?>" class="ai-flash-tune-px-6 ai-flash-tune-py-4 ai-flash-tune-whitespace-nowrap ai-flash-tune-text-left ai-flash-tune-text-sm ai-flash-tune-font-medium">
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=product-detail&product_id=' . $aiflt_product['product_id'])); ?>" class="ai-flash-tune-btn ai-flash-tune-btn-gray">
                                            <?php echo esc_html(__('View Details', 'ai-flash-tune')); ?>
                                        </a>
                                        <?php if ($aiflt_is_product_doctor_active): ?>
                                            <button class="ai-flash-tune-btn ai-flash-tune-btn-blue aiftpd-get-diagnosis-btn">
                                                <?php echo esc_html(__('Get AI Diagnosis', 'ai-flash-tune')); ?>
                                            </button>
                                        <?php endif; ?>
                                        <?php if ($aiflt_is_copy_enhancer_active): ?>
                                             <button class="ai-flash-tune-btn ai-flash-tune-btn-green aiftce-open-enhancer-btn">
                                                <?php echo esc_html(__('Enhance Copy', 'ai-flash-tune')); ?>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php if ($aiflt_is_product_doctor_active): ?>
                                <tr class="aiftpd-diagnosis-row" style="display:none;">
                                    <td colspan="12" class="ai-flash-tune-p-0">
                                        <div class="aiftpd-diagnosis-content"></div>
                                    </td>
                                </tr>
                                <?php endif; ?>
                                <?php if ($aiflt_is_copy_enhancer_active): ?>
                                <tr class="aiftce-enhancer-row" style="display:none;">
                                    <td colspan="6" class="ai-flash-tune-p-0">
                                        <div class="aiftce-enhancer-content">
                                            <div class="ai-flash-tune-flex ai-flash-tune-gap-4 ai-flash-tune-p-4">
                                                <button class="ai-flash-tune-btn ai-flash-tune-btn-white aiftce-get-suggestion-btn" data-type="title"><?php echo esc_html(__('Rewrite Title', 'ai-flash-tune')); ?></button>
                                                <button class="ai-flash-tune-btn ai-flash-tune-btn-white aiftce-get-suggestion-btn" data-type="description"><?php echo esc_html(__('Rewrite Description', 'ai-flash-tune')); ?></button>
                                            </div>
                                            <div class="aiftce-suggestion-result" style="display:none;"></div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            <?php } ?>
                        <?php else : ?>
                            <tr>
                                <td colspan="6" class="ai-flash-tune-px-6 ai-flash-tune-py-4 ai-flash-tune-text-center ai-flash-tune-text-sm ai-flash-tune-text-gray-500">
                                    <?php echo esc_html(__('No products found matching your criteria.', 'ai-flash-tune')); ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <!-- Pagination -->
            <?php if ($aiflt_total_pages > 1): ?>
                <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-items-center ai-flash-tune-pt-4">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-700">
                        <?php 
                            echo esc_html__('Showing ', 'ai-flash-tune') . absint( $aiflt_offset + 1 );
                            echo esc_html__(' to ', 'ai-flash-tune') . absint( min( ( $aiflt_offset + $aiflt_products_per_page ), $aiflt_total_products ) );
                            echo esc_html__(' of ', 'ai-flash-tune') . absint( $aiflt_total_products );
                            echo esc_html__(' products', 'ai-flash-tune');
                        ?>
                    </p>
                    <nav class="ai-flash-tune-pagination-nav">
                        <ul class="ai-flash-tune-flex ai-flash-tune-space-x-2">
                            <?php if ($aiflt_current_page > 1) { ?>
                                <li><a href="<?php echo esc_url(add_query_arg('paged', ($aiflt_current_page - 1), remove_query_arg(['start_date', 'end_date', 'status_filter']))); ?>" class="ai-flash-tune-py-2 ai-flash-tune-px-4 ai-flash-tune-border ai-flash-tune-rounded-lg ai-flash-tune-text-gray-700 ai-flash-tune-bg-white hover:ai-flash-tune-bg-gray-100">&laquo; <?php echo esc_html__('Previous', 'ai-flash-tune'); ?></a></li>
                            <?php } ?>
                            <?php for ($i = 1; $i <= $aiflt_total_pages; $i++) { ?>
                                <li><a href="<?php echo esc_url(add_query_arg('paged', $i, remove_query_arg(['start_date', 'end_date', 'status_filter']))); ?>" class="ai-flash-tune-py-2 ai-flash-tune-px-4 ai-flash-tune-border ai-flash-tune-rounded-lg <?php echo ($i === $aiflt_current_page) ? 'ai-flash-tune-bg-indigo-500 ai-flash-tune-text-white' : 'ai-flash-tune-bg-white hover:ai-flash-tune-bg-gray-100 ai-flash-tune-text-gray-700'; ?>"><?php echo esc_html($i); ?></a></li>
                            <?php } ?>
                            <?php if ($aiflt_current_page < $aiflt_total_pages) { ?>
                                <li><a href="<?php echo esc_url(add_query_arg('paged', ($aiflt_current_page + 1), remove_query_arg(['start_date', 'end_date', 'status_filter']))); ?>" class="ai-flash-tune-py-2 ai-flash-tune-px-4 ai-flash-tune-border ai-flash-tune-rounded-lg ai-flash-tune-text-gray-700 ai-flash-tune-bg-white hover:ai-flash-tune-bg-gray-100"><?php echo esc_html__('Next', 'ai-flash-tune'); ?> &raquo;</a></li>
                            <?php } ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        </div>

        <div class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-product-optimizer-cta">
            <div class="ai-flash-tune-free-card-header">
                <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-card-title">
                    <i class="fas fa-stethoscope ai-flash-tune-text-indigo-600 ai-flash-tune-mr-2"></i><?php echo esc_html__('Product Optimizer', 'ai-flash-tune'); ?>
                </span>
                <span class="ai-flash-tune-free-badge"><?php echo esc_html__('AI & Growth', 'ai-flash-tune'); ?></span>
            </div>
            <p class="ai-flash-tune-text-gray-700 ai-flash-tune-section-description">
                <?php echo esc_html__('Use product traffic, sales, conversion rate, visual-noise checks, and behavior signals to find product pages that need attention. AI optimization can diagnose copy, CTA, trust, and layout issues when the Product Optimizer module is active.', 'ai-flash-tune'); ?>
            </p>
            <div class="ai-flash-tune-growth-module-grid ai-flash-tune-mt-4">
                <div class="ai-flash-tune-growth-module"><i class="fas fa-chart-line"></i><span><?php echo esc_html__('Find weak products', 'ai-flash-tune'); ?></span></div>
                <div class="ai-flash-tune-growth-module"><i class="fas fa-pen"></i><span><?php echo esc_html__('Improve product copy', 'ai-flash-tune'); ?></span></div>
                <div class="ai-flash-tune-growth-module"><i class="fas fa-bullseye"></i><span><?php echo esc_html__('Clarify offer and CTA', 'ai-flash-tune'); ?></span></div>
            </div>
            <div class="ai-flash-tune-mt-4">
                <a class="ai-flash-tune-btn ai-flash-tune-btn-blue" href="<?php echo esc_url(admin_url(class_exists('AIFTPO_Logic') ? 'admin.php?page=aiftpo-product-optimizer' : 'admin.php?page=addon-manager&addon=ai-flash-tune-product-optimizer')); ?>">
                    <?php echo class_exists('AIFTPO_Logic') ? esc_html__('Open Product Optimizer', 'ai-flash-tune') : esc_html__('Review Product Optimizer module', 'ai-flash-tune'); ?>
                </a>
            </div>
        </div>
        </div>
        </div>
</div>
