<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Get API Key status
$api_key = rank_get_api_key(); // Use renamed function
$is_api_key_set = ! empty( $api_key );

// Get health check categories
$health_check_categories = rank_get_health_check_categories(); // Use renamed function

// Determine the current tab
$current_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'bulk_fix'; // Default to 'bulk_fix'

// We'll let WordPress handle the wrap div and notices
// But we need to output our own H1 tag with the SVG icon

?>
<div class="wrap" data-api-key-set="<?php echo $is_api_key_set ? 'yes' : 'no'; ?>">
    <h1 style="display:none;" class="wp-heading-inline"><?php echo get_admin_page_title(); ?></h1>
    <?php
    // This is where WordPress will automatically insert notices ABOVE our H1
    // because the notices hooks run before our page content
    ?>
    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 1em;">
        <svg fill="currentColor" class="overflow-visible" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 16 16" style="width: 1.5em; height: 2.5em; flex-shrink: 0;padding-top:2px;"><g transform="translate(-4)"><g transform="translate(4)"><path d="M8,0a8,8,0,1,0,8,8A8.009,8.009,0,0,0,8,0ZM7.726,15.053a6.206,6.206,0,1,1,6.206-6.206A6.206,6.206,0,0,1,7.726,15.053Z"></path><circle cx="3.414" cy="3.414" r="3.414" transform="translate(5.533 5.084)"></circle></g></g></svg>
        <h1>RANK AI by Morningscore</h1>
    </div>

<?php // --- Tab Navigation --- ?>
<h2 class="nav-tab-wrapper">
    <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=bulk_fix" class="nav-tab <?php echo $current_tab === 'bulk_fix' ? 'nav-tab-active' : ''; ?>">
    ❤️ Fix health problems
    </a>
    <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=api_config" class="nav-tab <?php echo $current_tab === 'api_config' ? 'nav-tab-active' : ''; ?>">
        🔑 API key
    </a>
    <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=fixes_overview" class="nav-tab <?php echo $current_tab === 'fixes_overview' ? 'nav-tab-active' : ''; ?>">
        ✅ Fixes
    </a>
    <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=data_management" class="nav-tab <?php echo $current_tab === 'data_management' ? 'nav-tab-active' : ''; ?>">
    💾 Data
    </a>
    <div class="nav-tab-spinner"></div>
    <div class="rank-experimental-label" data-tooltip="Expect fixes to work in +80% of cases. This is normal for something as complex as WordPress. Nothing breaks if it does not work. Good luck, captain! 🧑‍🚀👍️">80% success</div>
</h2>
<?php // --- End Tab Navigation --- ?>

<div class="tab-content">
    <div class="tab-content-loader"></div>

        <?php // --- Bulk Fix Tab Content --- ?>
        <?php if ( $current_tab === 'bulk_fix' ) : ?>
            
            <?php if ($is_api_key_set): ?>
                <div class="rank-section">
                    
                    <div id="rank-global-credit-status" style="margin-bottom: 15px; font-weight: bold;"></div>
                    
                    <?php
                    // Check if any multilingual plugins are active
                    if (!function_exists('is_plugin_active')) {
                        require_once(ABSPATH . 'wp-admin/includes/plugin.php');
                    }
                    
                    $multilingual_plugins_active = false;
                    $active_plugins = get_option('active_plugins');

                    // Check for WPML
                    if (in_array('sitepress-multilingual-cms/sitepress.php', $active_plugins) ||
                        defined('ICL_SITEPRESS_VERSION') ||
                        defined('WPML_PLUGIN_PATH') ||
                        class_exists('SitePress') ||
                        is_plugin_active('sitepress-multilingual-cms/sitepress.php')) {
                        $multilingual_plugins_active = true;
                    }
                    
                    // Check for Polylang
                    if (in_array('polylang/polylang.php', $active_plugins) ||
                        in_array('polylang-pro/polylang.php', $active_plugins) ||
                        function_exists('pll_current_language') ||
                        is_plugin_active('polylang/polylang.php') ||
                        is_plugin_active('polylang-pro/polylang.php')) {
                        $multilingual_plugins_active = true;
                    }
                    
                    // Check for TranslatePress
                    if (in_array('translatepress-multilingual/index.php', $active_plugins) ||
                        class_exists('TRP_Translate_Press') ||
                        is_plugin_active('translatepress-multilingual/index.php')) {
                        $multilingual_plugins_active = true;
                    }
                    
                    // Check for Weglot
                    if (in_array('weglot/weglot.php', $active_plugins) ||
                        function_exists('weglot_get_current_language') ||
                        is_plugin_active('weglot/weglot.php')) {
                        $multilingual_plugins_active = true;
                    }

                    // Display multilingual notice - initially hidden, will be shown only in overview by JavaScript
                    if ($multilingual_plugins_active) {
                        echo '<div id="rank-multilingual-notice" style="background-color: #f0f8ff !important; padding: 15px !important; border-left: 4px solid #007cba !important; margin: 15px 0 !important; display: none !important; visibility: visible !important; opacity: 1 !important; position: relative !important; z-index: 9999 !important; font-size: 14px !important; line-height: 1.4 !important;">';
                        echo '<p style="margin: 0 !important; padding: 0 !important; color: #333 !important;">🌍️ <strong>Language plugin detected and supported </strong> <a href="https://morningscore.io/automatic-seo-wordpress-plugin-rank-ai/#lwptoc13" target="_blank">See guide</a></p>';
                        echo '</div>';
                    }
                    ?>
                    
                    <div id="rank-health-issues-container" style="display:none;">
                        <div style="display: flex; align-items: center; justify-content: space-between;">
                            <h2>Fix health problems automatically</h2>
                            <div id="rank-health-issues-loading">
                                <div class="spinner is-active" style="float:none; margin: 0;"></div>
                            </div>
                        </div>
                        <p class="description">Get all pages on your website fixed automatically for each health problem found in your Morningscore account.</p>
                        
                        <?php
                        // Health issues will be populated by AJAX
                        ?>
                    </div>
                    
                    <div id="rank-processing-area" style="display:none;">
                        <input type="hidden" id="rank-batch-id" value="">
                        <input type="hidden" id="rank-selected-issue-type" value="">
                        
                        <div id="rank-status-container">
                            <p id="rank-status-message">Ready to process...</p>
                            <div id="rank-progress-bar-container" class="rank-progress-container" style="display:none;">
                                <div id="rank-progress-bar" class="rank-progress-bar" style="width: 0%;">0%</div>
                            </div>
                            <h3 id="rank-counts"></h3>
                        </div>
                        
                        <div id="rank-approval-area" style="margin-bottom: 15px;">
                            <?php // Approval items will be loaded here by JavaScript ?>
                        </div>
                        
                        <div class="rank-buttons-container">
                            <button id="rank-start-button" class="button button-primary" style="display:none;">Manual</button>
                            <button id="rank-auto-process-button" class="button button-secondary" style="display:none; float:right;">Automatic</button>
                        </div>
                        
                        <div class="rank-log-container" style="display:none;">
                            <h3>Processing log<div id="rank-log-spinner" class="spinner" style="float:none; display:none;"></div></h3>
                            <p>All fixes can be changed later in the Fixes tab <span class="rank-edit-icon dashicons dashicons-edit"></span></p>
                            <div id="rank-log-output" class="rank-log"></div>
                        </div>
                        
                        <div class="rank-cancel-container">
                            <button id="rank-cancel-button" class="button">Cancel</button>
                        </div>
                    </div>
                </div>
                    
                </div>
            <?php endif; ?>
        <?php endif; ?>
        <?php // --- End Bulk Fix Tab Content --- ?>


        <?php // --- API Configuration Tab Content --- ?>
        <?php if ( $current_tab === 'api_config' ) : ?>
            <div class="rank-section">
                <h2>🔑 API key</h2>
                <form id="rank-api-key-form" method="post" action="options.php">
                    <?php settings_fields( 'rank_options_group' ); ?>
                    <?php do_settings_sections( 'rank_options_group' ); ?>
                    <table class="form-table">
                        <tr valign="top">
                            <th scope="row">Morningscore API Key</th>
                            <td>
                                <input type="text" id="rank_api_key" name="rank_api_key" value="<?php echo esc_attr( $api_key ); ?>" size="50" />
                                <p class="description">Enter your API key from Morningscore.</p>
                                <?php if ($is_api_key_set): ?>
                                    <p style="color: green;">API Key is set. Now you can <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=bulk_fix">fix health problems</a></p>
                                <?php else: ?>
                                    <p style="color: red;">API Key is not set. Please enter your key.</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                    <?php submit_button('Save API Key'); ?>
                    <div style="margin-top: 100px;">
                        <h3>Find the API key here:</h3>
                        <p>Paid Morningscore subscription needed (<a href="https://morningscore.io/pricing/" target="_blank">all plans offer API</a>) to get API key. All fixes are owned by you forever.</p>
                       <p> <button
  type="button"
  class="button button-secondary"
  onclick="window.open('https://v3.morningscore.io/settings/api','_blank')"
>
  Direct link to API settings page
</button></p>
                        <img src="<?php echo esc_url( plugins_url( 'get-api-key-morningscore.png', __FILE__ ) ); ?>" alt="How to get your Morningscore API Key" style="max-width: 100%; height: auto; border: 1px solid #c1c1c1; width: 70%;">
                    </div>
                </form>
            </div>
        <?php endif; ?>
        <?php // --- End API Configuration Tab Content --- ?>

        <?php // --- Fixes Overview Tab Content --- ?>
        <?php if ( $current_tab === 'fixes_overview' ) : ?>
            <div class="rank-section">
                <h2>View and edit applied Fixes</h2>
                <p>Click on each to see and edit changes. <b>Fixes can take up to 2 minutes to appear</b></p>

                <div id="rank-fixes-accordion">
                    <?php foreach ( $health_check_categories as $key => $label ) :
                        // Map the category keys for broken links to match the option names
                        $category_key = $key;
                        if ($key === 'broken_internal_links') {
                            $category_key = 'broken_links_internal';
                        } elseif ($key === 'broken_external_links') {
                            $category_key = 'broken_links_external';
                        }
                    ?>
                        <div class="rank-accordion-item">
                            <button type="button" class="rank-accordion-header" data-category="<?php echo esc_attr( $category_key ); ?>" data-issue-type="<?php echo esc_attr( $key ); ?>" style="display: flex; align-items: center; width: 100%; background-color: #f6f7f7; border: 1px solid #ccd0d4; padding: 10px 15px; text-align: left; font-size: 1em; font-weight: 600; cursor: pointer;">
                                <span style="flex: 1;"><?php echo esc_html( $label ); ?></span>
                                <span class="rank-accordion-meta">
                                    <span class="rank-accordion-count">✅ (...)</span> <?php // Show (...) initially ?>
                                    <span class="rank-accordion-toggle dashicons dashicons-arrow-down-alt2" style="margin-left: 10px;"></span>
                                </span>
                            </button>
                            <div class="rank-accordion-content" style="display: none;">
                                <div class="rank-accordion-table-container">
                                    <?php // Table will be loaded here via AJAX ?>
                                    <p class="rank-accordion-loading" style="display: none;">Loading... 5-15 seconds</p>
                                    <p class="rank-accordion-no-data" style="display: none;">No fixes found for this category.</p>
                                </div>
                                <div class="rank-accordion-pagination">
                                    <?php // Pagination controls will be loaded here ?>
                                </div>
                                <div style="text-align: right; margin-top: 10px; padding: 10px 0;">
                                    <?php
                                    // Only show CSV export for database-stored fixes (not for broken links which are in wp_options)
                                    $is_broken_links = in_array($key, ['broken_links_internal', 'broken_links_external'], true);
                                    if (!$is_broken_links) :
                                    ?>
                                        <button type="button" class="rank-csv-export-btn button button-small" data-category="<?php echo esc_attr( $category_key ); ?>" data-issue-type="<?php echo esc_attr( $key ); ?>" title="Export all fixes in this category to CSV" style="padding: 2px 8px; height: auto; line-height: 1.5; margin-right: 5px;">
                                            <span class="dashicons dashicons-download" style="font-size: 14px; width: 14px; height: 14px; line-height: 1.5;"></span> CSV Export
                                        </button>
                                    <?php endif; ?>
                                    <button type="button" class="rank-delete-all-btn button button-small" data-category="<?php echo esc_attr( $category_key ); ?>" data-issue-type="<?php echo esc_attr( $key ); ?>" title="Delete all fixes in this category" style="padding: 2px 8px; height: auto; line-height: 1.5;">
                                        <span class="dashicons dashicons-trash" style="font-size: 14px; width: 14px; height: 14px; line-height: 1.5;"></span> Delete All
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
        <?php // --- End Fixes Overview Tab Content --- ?>


        <?php // --- Data Management Tab Content --- ?>
        <?php if ( $current_tab === 'data_management' ) : ?>
            <div class="rank-section">
                <h2>System Status</h2>
                <p>This section shows the status of various system components required for RANK AI to function properly.</p>
                
                <?php
                // Get system status
                $status = Rank_Processor::system_status_check();
                ?>
                
                <div class="rank-status-card">
                    <h3>Database Tables</h3>
                    <?php if ($status['table_exists']): ?>
                        <p class="rank-status-ok">✅ SEO overrides table exists.</p>
                    <?php else: ?>
                        <p class="rank-status-error">❌ SEO overrides table does not exist.</p>
                        <p>Try deactivating and reactivating the plugin to create the table.</p>
                    <?php endif; ?>
                </div>
                
                <div class="rank-status-card">
                    <h3>Action Scheduler</h3>
                    <?php if ($status['action_scheduler']['exists']): ?>
                        <p class="rank-status-ok">✅ Action Scheduler is installed.</p>
                        <?php if (!$status['action_scheduler']['hooks_registered']): ?>
                            <p class="rank-status-error">❌ Rank AI hooks are not registered.</p>
                        <?php endif; ?>
                    <?php else: ?>
                        <p class="rank-status-error">❌ Action Scheduler is not installed.</p>
                    <?php endif; ?>
                </div>

                <div class="rank-status-card">
                    <h3>PHP Version</h3>
                    <?php if ($status['php_version']['is_recommended']): ?>
                        <p class="rank-status-ok">✅ You are using PHP <?php echo $status['php_version']['current']; ?></p>
                    <?php else: ?>
                        <p class="rank-status-warning">⚠️ You are currently on PHP <?php echo $status['php_version']['current']; ?>. PHP <?php echo $status['php_version']['recommended']; ?> or higher is recommended.</p>
                    <?php endif; ?>
                </div>

            </div>
            
            <div class="rank-section" style="margin-top: 30px;">
                <h2>🔍 Debug Logs</h2>
                <p>View recent debug logs from RANK AI processing. Show this to our support if fixes are not being added to the Fixes tab.</p>
                
                <div style="margin-bottom: 15px;">
                    <button type="button" id="rank-refresh-logs" class="button button-secondary">Refresh Logs</button>
                    <label style="margin-left: 15px;">
                        <input type="checkbox" id="rank-debug-enabled" <?php checked(get_option('rank_debug_enabled', false)); ?>>
                        Enable debug logging
                    </label>
                </div>
                
                <div id="rank-logs-container" style="background: #f1f1f1; border: 1px solid #ccc; padding: 15px; height: 500px; overflow-y: auto; font-family: monospace; font-size: 12px; white-space: pre-wrap;">
                    <div id="rank-logs-loading" style="text-align: center; padding: 20px;">
                        <div class="spinner is-active"></div>
                        <p>Loading debug logs...</p>
                    </div>
                    <div id="rank-logs-content" style="display: none;"></div>
                    <div id="rank-logs-error" style="display: none; color: #d63638; text-align: center; padding: 20px;">
                        <p>Unable to load debug logs. Make sure WP_DEBUG_LOG is enabled in wp-config.php</p>
                    </div>
                </div>
                
                <div style="margin-top: 15px; padding: 10px; background: #e7f3ff; border-left: 4px solid #007cba;">
                    <h4>Debug Log Information:</h4>
                    <ul style="margin: 5px 0;">
                        <li><strong>Location:</strong> Custom RANK AI log file (protected from public access)</li>
                        <li><strong>No WordPress debug required:</strong> Works independently of WP_DEBUG_LOG setting</li>
                        <li><strong>Lines shown:</strong> Last 20 RANK AI log entries</li>
                        <li><strong>File size limit:</strong> Automatically managed (max 200KB)</li>
                        <li><strong>Performance:</strong> Zero overhead when disabled - enable only for troubleshooting</li>
                    </ul>
                </div>
            </div>
            
            <div class="rank-section rank-danger-zone" style="margin-top: 30px;">
                <h2>Danger Zone</h2>
                <p><strong>Warning:</strong> This action will permanently delete all SEO overrides (titles, alt tags, etc.) created by RANK AI from your database. This cannot be undone.</p>
                <button type="button" id="rank-show-delete-confirm" class="button button-secondary">Delete All RANK AI Changes</button>

                <div id="rank-delete-confirmation-area" style="display: none; margin-top: 15px; padding: 15px; border: 1px solid #dc3232; background-color: #fef7f7;">
                    <p>To confirm deletion, please type "<strong>DELETE</strong>" into the box below and click the confirm button.</p>
                    <label for="rank-delete-confirm-input">Confirmation:</label>
                    <input type="text" id="rank-delete-confirm-input" name="rank_delete_confirm_input" size="20" />
                    <button type="button" id="rank-confirm-delete-button" class="button button-danger" disabled>Confirm Deletion</button>
                    <p id="rank-delete-status" style="margin-top: 10px;"></p>
                </div>
            </div>
        <?php endif; ?>
        <?php // --- End Data Management Tab Content --- ?>


</div> <?php // end .tab-content ?>

<div style="text-align: left; margin: 20px 0;"> <?php // Added container for centering ?>
    <a href="https://morningscore.io" target="_blank"><img src="<?php echo esc_url( plugins_url( 'Rank.webp', __FILE__ ) ); ?>" alt="RANK AI Logo" width="200"></a>
</div> <!-- Close the wrap div -->

<?php
// Debug information section removed - use Data Management tab for debug logs
?>