<?php
/**
 * URL Management page template
 *
 * @package ContentPerformanceAnalyzer
 * @since 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Settings errors/messages
settings_errors('cpanalyzer_messages');
?>

<div class="wrap">
    <h1><?php esc_html_e('URL Management', 'content-performance-analyzer'); ?></h1>

    <?php
    if (function_exists('cpanalyzer_render_setup_mode_notice')) {
        cpanalyzer_render_setup_mode_notice();
    }
    ?>


    <!-- Statistics Dashboard -->
    <div class="cpanalyzer-stats-dashboard">
        <h2><?php esc_html_e('Processing Statistics', 'content-performance-analyzer'); ?></h2>
        <div class="cpanalyzer-stats-grid">
            <div class="cpanalyzer-stat-card">
                <span class="cpanalyzer-stat-label"><?php esc_html_e('Total URLs', 'content-performance-analyzer'); ?></span>
                <span class="cpanalyzer-stat-value"><?php echo esc_html($stats['total']); ?></span>
            </div>
            <div class="cpanalyzer-stat-card">
                <span class="cpanalyzer-stat-label"><?php esc_html_e('Pending', 'content-performance-analyzer'); ?></span>
                <span class="cpanalyzer-stat-value" style="color: #dba617;"><?php echo esc_html($stats['pending']); ?></span>
            </div>
            <div class="cpanalyzer-stat-card">
                <span class="cpanalyzer-stat-label"><?php esc_html_e('In Progress', 'content-performance-analyzer'); ?></span>
                <span class="cpanalyzer-stat-value" style="color: #0073aa;"><?php echo esc_html($stats['in_progress']); ?></span>
            </div>
            <div class="cpanalyzer-stat-card">
                <span class="cpanalyzer-stat-label"><?php esc_html_e('Completed', 'content-performance-analyzer'); ?></span>
                <span class="cpanalyzer-stat-value" style="color: #00a32a;"><?php echo esc_html($stats['success']); ?></span>
            </div>
            <div class="cpanalyzer-stat-card">
                <span class="cpanalyzer-stat-label"><?php esc_html_e('Failed', 'content-performance-analyzer'); ?></span>
                <span class="cpanalyzer-stat-value" style="color: #d63638;"><?php echo esc_html($stats['failed']); ?></span>
            </div>
        </div>
    </div>
    
    <!-- Site Page Picker Section -->
    <div class="cpanalyzer-upload-section">
        <h2><?php esc_html_e('Option 1: Pick Pages From Your Site', 'content-performance-analyzer'); ?></h2>
        <p class="description">
            <?php esc_html_e('Every published page and post from WordPress — the same pages your XML sitemap lists. Untick anything you want to leave out, then import.', 'content-performance-analyzer'); ?>
        </p>
        <p>
            <button type="button" id="cpanalyzer-load-site-pages" class="button">
                <?php esc_html_e('Reload Pages', 'content-performance-analyzer'); ?>
            </button>
        </p>

        <div id="cpanalyzer-site-pages-picker" style="display:none;">
            <p>
                <input type="search"
                        id="cpanalyzer-page-search"
                        placeholder="<?php esc_attr_e('Search pages by title or path…', 'content-performance-analyzer'); ?>"
                        style="width: 320px; max-width: 100%;" />
            </p>
            <p>
                <label>
                    <input type="checkbox" id="cpanalyzer-select-all-pages" checked />
                    <strong><?php esc_html_e('Select all', 'content-performance-analyzer'); ?></strong>
                    <span class="description"><?php esc_html_e('(applies to search results when filtering)', 'content-performance-analyzer'); ?></span>
                </label>
                <span id="cpanalyzer-selected-count" class="cpanalyzer-selected-count"></span>
            </p>

            <div id="cpanalyzer-site-pages-list" class="cpanalyzer-site-pages-list"></div>

            <p>
                <label>
                    <input type="radio" name="cpanalyzer_import_mode" value="replace" checked />
                    <?php esc_html_e('Replace existing URLs', 'content-performance-analyzer'); ?>
                </label><br>
                <label>
                    <input type="radio" name="cpanalyzer_import_mode" value="merge" />
                    <?php esc_html_e('Merge with existing URLs', 'content-performance-analyzer'); ?>
                </label>
            </p>

            <p>
                <button type="button" id="cpanalyzer-import-selected" class="button button-primary">
                    <?php esc_html_e('Import Selected Pages', 'content-performance-analyzer'); ?>
                </button>
                <span id="cpanalyzer-import-status" role="status" aria-live="polite"></span>
            </p>
        </div>
    </div>

    <!-- URL Input Section -->
    <div class="cpanalyzer-upload-section">
        <h2><?php esc_html_e('Option 2: Paste URLs Manually', 'content-performance-analyzer'); ?></h2>


        <form method="post" action="">
            <?php wp_nonce_field('cpanalyzer_upload_urls', 'cpanalyzer_upload_urls_nonce'); ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="cpanalyzer_url_list"><?php esc_html_e('URLs', 'content-performance-analyzer'); ?></label>
                    </th>
                    <td>
                        <textarea
                            name="cpanalyzer_url_list"
                            id="cpanalyzer_url_list"
                            rows="12"
                            class="large-text code"
                            placeholder="/about-us&#10;/blog/my-first-post&#10;https://example.com/pricing"
                            required
                        ></textarea>
                        <p class="description">
                            <?php esc_html_e('Paste one URL per line. Relative paths are preferred, but full URLs are also accepted and normalized.', 'content-performance-analyzer'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Upload Mode', 'content-performance-analyzer'); ?></th>
                    <td>
                        <label>
                            <input type="radio" name="cpanalyzer_upload_mode" value="replace" checked />
                            <?php esc_html_e('Replace existing URLs', 'content-performance-analyzer'); ?>
                        </label><br>
                        <label>
                            <input type="radio" name="cpanalyzer_upload_mode" value="merge" />
                            <?php esc_html_e('Merge with existing URLs', 'content-performance-analyzer'); ?>
                        </label>
                    </td>
                </tr>
            </table>
            
            <?php submit_button(__('Save URLs', 'content-performance-analyzer'), 'primary', 'submit', false); ?>
        </form>
    </div>

    <!-- Processing Instructions -->
    <div class="notice notice-info" style="border-left-color: #0073aa; background-color: #f0f6fc; padding: 15px; margin: 20px 0;">
        <div style="display: flex; align-items: flex-start; gap: 10px;">
            <span style="font-size: 18px; color: #0073aa;">ℹ️</span>
            <div>
                <h3 style="margin: 0 0 8px 0; color: #0073aa; font-size: 16px;">
                    <?php esc_html_e('How to Process Your URLs:', 'content-performance-analyzer'); ?>
                </h3>
                <p style="margin: 0; line-height: 1.5; color: #2c3e50;">
                    <?php esc_html_e('Paste your URLs, save them, then click "Start Batch Processing" below. Processing can take approximately 1 minute per URL. If some pages are still pending after the expected time, click the batch processing button again to continue.', 'content-performance-analyzer'); ?>
                </p>
            </div>
        </div>
    </div>
    
    <!-- Batch Processing Controls -->
    <div class="cpanalyzer-batch-controls">
        <h2><?php esc_html_e('Batch Processing', 'content-performance-analyzer'); ?></h2>
        
        <div class="cpanalyzer-batch-actions">
            <button id="cpanalyzer-start-batch" class="button button-primary">
                <?php esc_html_e('Start Batch Processing', 'content-performance-analyzer'); ?>
            </button>
            <button id="cpanalyzer-rescan-all" class="button">
                <?php esc_html_e('Rescan Existing URLs', 'content-performance-analyzer'); ?>
            </button>
            <button id="cpanalyzer-cancel-batch" class="button" style="display:none;">
                <?php esc_html_e('Cancel Processing', 'content-performance-analyzer'); ?>
            </button>
            <button id="cpanalyzer-refresh-status" class="button">
                <?php esc_html_e('Refresh Status', 'content-performance-analyzer'); ?>
            </button>
        </div>
        
        <!-- Progress bar removed - statistics cards above provide accurate progress info -->
    </div>
    
    <!-- URLs Table -->
    <div class="cpanalyzer-urls-table-section">
        <h2><?php esc_html_e('URL Status', 'content-performance-analyzer'); ?></h2>
        
            <?php if (empty($urls)): ?>
                <p><?php esc_html_e('No URLs have been added yet. Paste one URL per line above to begin analysis.', 'content-performance-analyzer'); ?></p>
            <?php else: ?>
                <table class="widefat striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e('ID', 'content-performance-analyzer'); ?></th>
                        <th><?php esc_html_e('URL', 'content-performance-analyzer'); ?></th>
                        <th><?php esc_html_e('Status', 'content-performance-analyzer'); ?></th>
                        <th><?php esc_html_e('Last Scanned', 'content-performance-analyzer'); ?></th>
                        <th><?php esc_html_e('Results', 'content-performance-analyzer'); ?></th>
                        <th><?php esc_html_e('Actions', 'content-performance-analyzer'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($urls as $cpanalyzer_url): ?>
                        <?php
                        $cpanalyzer_status_class = '';
                        $cpanalyzer_status_text = ucfirst($cpanalyzer_url->status);
                        
                        switch ($cpanalyzer_url->status) {
                            case 'success':
                                $cpanalyzer_status_class = 'cpanalyzer-status-success';
                                break;
                            case 'failed':
                                $cpanalyzer_status_class = 'cpanalyzer-status-failed';
                                break;
                            case 'in_progress':
                                $cpanalyzer_status_class = 'cpanalyzer-status-progress';
                                $cpanalyzer_status_text = __('In Progress', 'content-performance-analyzer');
                                break;
                            case 'pending':
                                $cpanalyzer_status_class = 'cpanalyzer-status-pending';
                                break;
                        }
                        
                        // Parse results if available
                        $cpanalyzer_results_summary = '';
                        if ($cpanalyzer_url->scan_result) {
                            $cpanalyzer_scan_data = json_decode($cpanalyzer_url->scan_result, true);
                            if (isset($cpanalyzer_scan_data['summary'])) {
                                $cpanalyzer_summary_parts = array();
                                foreach ($cpanalyzer_scan_data['summary'] as $cpanalyzer_summary_key => $cpanalyzer_summary_value) {
                                    $cpanalyzer_summary_parts[] = $cpanalyzer_summary_value;
                                }
                                $cpanalyzer_results_summary = implode(' | ', array_slice($cpanalyzer_summary_parts, 0, 2));
                            }
                        }
                        
                        // Parse AI suggestions if available
                        $cpanalyzer_ai_action = '';
                        $cpanalyzer_has_brief = false;
                        if ($cpanalyzer_url->ai_suggestions) {
                            $cpanalyzer_ai_data = json_decode($cpanalyzer_url->ai_suggestions, true);
                            if (isset($cpanalyzer_ai_data['action'])) {
                                $cpanalyzer_ai_action = $cpanalyzer_ai_data['action'];
                            }
                            if (isset($cpanalyzer_ai_data['content_refresh_brief'])) {
                                $cpanalyzer_has_brief = true;
                            }
                        }
                        ?>
                        <tr>
                            <td><?php echo esc_html($cpanalyzer_url->id); ?></td>
                            <td>
                                <strong><?php echo esc_html($cpanalyzer_url->url); ?></strong>
                                <?php if ($cpanalyzer_ai_action): ?>
                                    <br><small style="color: #0073aa;">AI: <?php echo esc_html($cpanalyzer_ai_action); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="<?php echo esc_attr($cpanalyzer_status_class); ?>">
                                    <?php echo esc_html($cpanalyzer_status_text); ?>
                                </span>
                                <?php if ($cpanalyzer_url->error_message): ?>
                                    <br><small style="color: #d63638;"><?php echo esc_html($cpanalyzer_url->error_message); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php 
                                if ($cpanalyzer_url->last_scanned) {
                                    echo esc_html(human_time_diff(strtotime($cpanalyzer_url->last_scanned), current_time('timestamp')) . ' ' . __('ago', 'content-performance-analyzer'));
                                } else {
                                    echo '–';
                                }
                            ?>
                            </td>
                            <td>
                                <?php if ($cpanalyzer_results_summary): ?>
                                    <small><?php echo esc_html($cpanalyzer_results_summary); ?></small>
                                <?php else: ?>
                                    –
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($cpanalyzer_url->status === 'failed'): ?>
                                    <button class="button button-small cpanalyzer-retry-url" data-url-id="<?php echo esc_attr($cpanalyzer_url->id); ?>">
                                        <?php esc_html_e('Retry', 'content-performance-analyzer'); ?>
                                    </button>
                                <?php endif; ?>
                                <?php if ($cpanalyzer_url->status === 'success'): ?>
                                    <button class="button button-small cpanalyzer-gen-brief"
                                        data-url-id="<?php echo esc_attr($cpanalyzer_url->id); ?>"
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('cpanalyzer_generate_brief')); ?>">
                                        <?php esc_html_e('Generate Brief', 'content-performance-analyzer'); ?>
                                    </button>
                                <?php endif; ?>
                                <?php if ($cpanalyzer_has_brief): ?>
                                    <button class="button button-small button-primary cpanalyzer-view-brief"
                                        data-url-id="<?php echo esc_attr($cpanalyzer_url->id); ?>"
                                        data-url="<?php echo esc_attr($cpanalyzer_url->url); ?>"
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('cpanalyzer_get_brief')); ?>">
                                        <?php esc_html_e('View Brief', 'content-performance-analyzer'); ?>
                                    </button>
                                <?php endif; ?>
                                <a href="<?php echo esc_url(home_url($cpanalyzer_url->url)); ?>" target="_blank" class="button button-small">
                                    <?php esc_html_e('View', 'content-performance-analyzer'); ?>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="tablenav">
                    <div class="tablenav-pages">
                        <?php
                        $cpanalyzer_pagination_args = array(
                            'base' => add_query_arg('paged', '%#%'),
                            'format' => '',
                            'prev_text' => __('&laquo; Previous', 'content-performance-analyzer'),
                            'next_text' => __('Next &raquo;', 'content-performance-analyzer'),
                            'total' => $total_pages,
                            'current' => $current_page
                        );
                        
                        echo wp_kses_post(paginate_links($cpanalyzer_pagination_args));
                        ?>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Content Refresh Brief Modal -->
<div id="cpanalyzer-brief-modal" class="cpanalyzer-modal" style="display:none;" role="dialog" aria-modal="true" aria-labelledby="cpanalyzer-brief-modal-title">
    <div class="cpanalyzer-modal-overlay"></div>
    <div class="cpanalyzer-modal-container">
        <div class="cpanalyzer-modal-header">
            <h2 id="cpanalyzer-brief-modal-title"><?php esc_html_e('Content Refresh Brief', 'content-performance-analyzer'); ?></h2>
            <p class="cpanalyzer-modal-url"></p>
            <button class="cpanalyzer-modal-close" aria-label="<?php esc_attr_e('Close', 'content-performance-analyzer'); ?>">&times;</button>
        </div>
        <div class="cpanalyzer-modal-body">
            <!-- Gap Analysis -->
            <div class="cpanalyzer-brief-section">
                <h3 class="cpanalyzer-brief-section-title cpanalyzer-brief-gap">
                    <span class="cpanalyzer-brief-icon">&#128269;</span>
                    <?php esc_html_e('Gap Analysis', 'content-performance-analyzer'); ?>
                </h3>
                <div class="cpanalyzer-brief-content" id="cpanalyzer-brief-gap-content">
                    <div class="cpanalyzer-brief-row">
                        <strong><?php esc_html_e('Missing Keywords:', 'content-performance-analyzer'); ?></strong>
                        <ul class="cpanalyzer-brief-list" id="cpanalyzer-gap-keywords"></ul>
                    </div>
                    <div class="cpanalyzer-brief-row">
                        <strong><?php esc_html_e('Competitor Gaps:', 'content-performance-analyzer'); ?></strong>
                        <p id="cpanalyzer-gap-competitor"></p>
                    </div>
                    <div class="cpanalyzer-brief-row">
                        <strong><?php esc_html_e('Intent Mismatch:', 'content-performance-analyzer'); ?></strong>
                        <p id="cpanalyzer-gap-intent"></p>
                    </div>
                </div>
            </div>

            <!-- Structural Plan -->
            <div class="cpanalyzer-brief-section">
                <h3 class="cpanalyzer-brief-section-title cpanalyzer-brief-structure">
                    <span class="cpanalyzer-brief-icon">&#128196;</span>
                    <?php esc_html_e('Structural Plan', 'content-performance-analyzer'); ?>
                </h3>
                <div class="cpanalyzer-brief-content" id="cpanalyzer-brief-structure-content">
                    <div class="cpanalyzer-brief-row">
                        <strong><?php esc_html_e('Recommended Sections:', 'content-performance-analyzer'); ?></strong>
                        <ol class="cpanalyzer-brief-list" id="cpanalyzer-structure-sections"></ol>
                    </div>
                    <div class="cpanalyzer-brief-row">
                        <strong><?php esc_html_e('Current Issues:', 'content-performance-analyzer'); ?></strong>
                        <p id="cpanalyzer-structure-issues"></p>
                    </div>
                    <div class="cpanalyzer-brief-row">
                        <strong><?php esc_html_e('Ideal Outline:', 'content-performance-analyzer'); ?></strong>
                        <p id="cpanalyzer-structure-outline"></p>
                    </div>
                </div>
            </div>

            <!-- Performance Fixes -->
            <div class="cpanalyzer-brief-section">
                <h3 class="cpanalyzer-brief-section-title cpanalyzer-brief-performance">
                    <span class="cpanalyzer-brief-icon">&#9889;</span>
                    <?php esc_html_e('Performance Fixes', 'content-performance-analyzer'); ?>
                </h3>
                <div class="cpanalyzer-brief-content" id="cpanalyzer-brief-performance-content">
                    <div class="cpanalyzer-brief-row cpanalyzer-brief-two-col">
                        <div>
                            <strong><?php esc_html_e('GA4 Actions:', 'content-performance-analyzer'); ?></strong>
                            <ul class="cpanalyzer-brief-list" id="cpanalyzer-perf-ga4"></ul>
                        </div>
                        <div>
                            <strong><?php esc_html_e('PSI Actions:', 'content-performance-analyzer'); ?></strong>
                            <ul class="cpanalyzer-brief-list" id="cpanalyzer-perf-psi"></ul>
                        </div>
                    </div>
                    <div class="cpanalyzer-brief-row cpanalyzer-brief-two-col">
                        <div>
                            <strong><?php esc_html_e('Priority:', 'content-performance-analyzer'); ?></strong>
                            <span id="cpanalyzer-perf-priority" class="cpanalyzer-priority-badge"></span>
                        </div>
                        <div>
                            <strong><?php esc_html_e('Estimated Impact:', 'content-performance-analyzer'); ?></strong>
                            <span id="cpanalyzer-perf-impact"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="cpanalyzer-modal-footer">
            <button class="button button-secondary cpanalyzer-modal-close"><?php esc_html_e('Close', 'content-performance-analyzer'); ?></button>
        </div>
    </div>
</div>




