<?php
/**
 * AYSA SEO History Admin Controller
 * 
 * Handles admin interface for SEO generation history, including menu registration,
 * AJAX handlers, and integration with WordPress admin.
 * 
 * @package AYSA
 * @since 1.0.0
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class Aysa_Seo_History_Admin {
    
    /**
     * The SEO history manager instance
     * 
     * @var Aysa_Seo_History
     */
    private $seo_history;
    
    /**
     * Initialize the admin interface
     */
    public function __construct() {
        $this->seo_history = aysa_get_seo_history();
        $this->init_hooks();
    }
    
    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('wp_ajax_aysa_get_seo_history_details', array($this, 'ajax_get_history_details'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    }
    
    /**
     * Add admin menu pages
     */
    public function add_admin_menu() {
        // Add as submenu under On-Page Optimization
        add_submenu_page(
            'aysa-on-page-optimization',
            'SEO History',
            'SEO History',
            'manage_options',
            'aysa-seo-history',
            array($this, 'display_history_page')
        );
    }
    
    /**
     * Display the history page
     */
    public function display_history_page() {
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        
        // Include the history page template
        include_once plugin_dir_path(__FILE__) . 'partials/aysa-seo-history.php';
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        // Only load on our history page
        if (strpos($hook, 'aysa-seo-history') === false) {
            return;
        }
        
        // Enqueue jQuery if not already loaded
        wp_enqueue_script('jquery');
        
        // Add inline styles for better mobile responsiveness
        wp_add_inline_style('wp-admin', '
            @media (max-width: 782px) {
                .aysa-stats-grid {
                    grid-template-columns: 1fr !important;
                }
                
                .aysa-history-filters > form > div {
                    grid-template-columns: 1fr !important;
                }
                
                .wp-list-table .aysa-generated-content {
                    max-width: 200px;
                }
            }
        ');
    }
    
    /**
     * AJAX handler for getting detailed history entry information
     */
    public function ajax_get_history_details() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash((string) $_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'aysa_history_details')) {
            wp_die(__('Security check failed', 'aysa'));
        }
        
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('Insufficient permissions', 'aysa'));
        }
        
        $entry_id = isset($_POST['entry_id']) ? intval($_POST['entry_id']) : 0;
        
        if (!$entry_id) {
            wp_send_json_error('Invalid entry ID');
        }
        
        // Get the detailed entry data
        global $wpdb;
        $table_name = $wpdb->prefix . 'aysa_seo_history';
        
        $entry = $wpdb->get_row($wpdb->prepare(
            "SELECT h.*, u.display_name as user_name 
             FROM {$table_name} h 
             LEFT JOIN {$wpdb->users} u ON h.wp_user_id = u.ID 
             WHERE h.id = %d",
            $entry_id
        ));
        
        if (!$entry) {
            wp_send_json_error('Entry not found');
        }
        
        // Parse JSON fields
        $generated_data = json_decode($entry->generated_data, true) ?: array();
        $previous_data = json_decode($entry->previous_data, true) ?: array();
        $generation_metadata = json_decode($entry->generation_metadata, true) ?: array();
        $api_response_data = json_decode($entry->api_response_data, true) ?: array();
        
        // Generate HTML for the modal
        ob_start();
        ?>
        <div class="aysa-history-details">
            <!-- Basic Information -->
            <div class="aysa-detail-section" style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border-radius: 4px;">
                <h3 style="margin: 0 0 10px; color: #333;">Basic Information</h3>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">
                    <div><strong>Entry ID:</strong> #<?php echo esc_html((string) $entry->id); ?></div>
                    <div><strong>Entity:</strong> <?php echo esc_html($entry->entity_type); ?> #<?php echo esc_html((string) $entry->entity_id); ?></div>
                    <div><strong>Keyword:</strong> <?php echo esc_html($entry->keyword); ?></div>
                    <div><strong>Version:</strong> v<?php echo esc_html((string) $entry->version); ?></div>
                    <div><strong>Generator:</strong> <?php echo esc_html($entry->generator_type); ?></div>
                    <div><strong>Method:</strong> <?php echo esc_html($entry->generation_method); ?></div>
                    <div><strong>User:</strong> <?php echo esc_html($entry->user_name ?: 'Unknown'); ?></div>
                    <div><strong>Created:</strong> <?php echo esc_html(wp_date('M j, Y H:i:s', strtotime($entry->created_at))); ?></div>
                </div>
            </div>
            
            <!-- Status Information -->
            <div class="aysa-detail-section" style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border-radius: 4px;">
                <h3 style="margin: 0 0 10px; color: #333;">Status & Performance</h3>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">
                    <div><strong>Status:</strong> 
                        <span style="color: <?php echo esc_attr($entry->is_applied ? '#00a32a' : ($entry->is_reverted ? '#d63638' : '#666')); ?>">
                            <?php echo esc_html($entry->is_applied ? 'Applied' : ($entry->is_reverted ? 'Reverted' : ucfirst((string) $entry->status))); ?>
                        </span>
                    </div>
                    <div><strong>Current Version:</strong> <?php echo esc_html($entry->is_current_version ? 'Yes' : 'No'); ?></div>
                    <div><strong>Partial Failure:</strong> <?php echo esc_html($entry->partial_failure ? 'Yes' : 'No'); ?></div>
                    <?php if ($entry->confidence_score): ?>
                        <div><strong>Confidence:</strong> <?php echo esc_html(number_format((float) $entry->confidence_score, 1)); ?>%</div>
                    <?php endif; ?>
                    <?php if ($entry->api_response_time): ?>
                        <div><strong>Response Time:</strong> <?php echo esc_html(number_format(((float) $entry->api_response_time) / 1000, 2)); ?>s</div>
                    <?php endif; ?>
                    <?php if ($entry->failed_fields): ?>
                        <div><strong>Failed Fields:</strong> <?php echo esc_html($entry->failed_fields); ?></div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Generated Content -->
            <div class="aysa-detail-section" style="margin-bottom: 20px;">
                <h3 style="margin: 0 0 15px; color: #333;">Generated Content</h3>
                
                <?php if (!empty($entry->meta_title)): ?>
                    <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <h4 style="margin: 0 0 5px; color: #0073aa;">Meta Title</h4>
                        <p style="margin: 0; font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 3px;">
                            <?php echo esc_html($entry->meta_title); ?>
                        </p>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($entry->meta_description)): ?>
                    <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <h4 style="margin: 0 0 5px; color: #0073aa;">Meta Description</h4>
                        <p style="margin: 0; font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 3px;">
                            <?php echo esc_html($entry->meta_description); ?>
                        </p>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($entry->meta_keywords)): ?>
                    <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <h4 style="margin: 0 0 5px; color: #0073aa;">Meta Keywords</h4>
                        <p style="margin: 0; font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 3px;">
                            <?php echo esc_html($entry->meta_keywords); ?>
                        </p>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($entry->secondary_keywords)): ?>
                    <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <h4 style="margin: 0 0 5px; color: #0073aa;">Secondary Keywords</h4>
                        <p style="margin: 0; font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 3px;">
                            <?php echo esc_html($entry->secondary_keywords); ?>
                        </p>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($entry->product_title)): ?>
                    <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <h4 style="margin: 0 0 5px; color: #0073aa;">Product/Category Title</h4>
                        <p style="margin: 0; font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 3px;">
                            <?php echo esc_html($entry->product_title); ?>
                        </p>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($entry->product_description)): ?>
                    <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <h4 style="margin: 0 0 5px; color: #0073aa;">Product/Category Description</h4>
                        <div style="margin: 0; font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 3px; max-height: 200px; overflow-y: auto;">
                            <?php echo nl2br(esc_html($entry->product_description)); ?>
                        </div>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($entry->permalink)): ?>
                    <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <h4 style="margin: 0 0 5px; color: #0073aa;">Permalink</h4>
                        <p style="margin: 0; font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 3px;">
                            <?php echo esc_html($entry->permalink); ?>
                        </p>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Previous Values (if available) -->
            <?php if (!empty($previous_data)): ?>
                <div class="aysa-detail-section" style="margin-bottom: 20px;">
                    <h3 style="margin: 0 0 15px; color: #333;">Previous Values</h3>
                    <div style="background: #fff3cd; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto;">
                        <pre style="margin: 0; white-space: pre-wrap;"><?php echo esc_html(json_encode($previous_data, JSON_PRETTY_PRINT)); ?></pre>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Generation Metadata -->
            <?php if (!empty($generation_metadata)): ?>
                <div class="aysa-detail-section" style="margin-bottom: 20px;">
                    <h3 style="margin: 0 0 15px; color: #333;">Generation Metadata</h3>
                    <div style="background: #e7f3ff; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto;">
                        <pre style="margin: 0; white-space: pre-wrap;"><?php echo esc_html(json_encode($generation_metadata, JSON_PRETTY_PRINT)); ?></pre>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- API Response Data -->
            <?php if (!empty($api_response_data)): ?>
                <div class="aysa-detail-section" style="margin-bottom: 20px;">
                    <h3 style="margin: 0 0 15px; color: #333;">API Response Data</h3>
                    <div style="background: #f0f9ff; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; max-height: 300px; overflow-y: auto;">
                        <pre style="margin: 0; white-space: pre-wrap;"><?php echo esc_html(json_encode($api_response_data, JSON_PRETTY_PRINT)); ?></pre>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Raw Data (for debugging) -->
            <details style="margin-top: 20px;">
                <summary style="cursor: pointer; padding: 10px; background: #f3f4f6; border-radius: 4px; font-weight: 600;">Raw Database Entry (Debug)</summary>
                <div style="margin-top: 10px; background: #f8f9fa; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 11px; max-height: 300px; overflow-y: auto;">
                    <pre style="margin: 0; white-space: pre-wrap;"><?php echo esc_html(json_encode($entry, JSON_PRETTY_PRINT)); ?></pre>
                </div>
            </details>
        </div>
        <?php
        
        $html = ob_get_clean();
        
        wp_send_json_success(array(
            'html' => $html,
            'entry_id' => $entry_id
        ));
    }
    
    /**
     * Get a helper function to check if the history table exists
     * 
     * @return bool
     */
    public static function is_history_table_available() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'aysa_seo_history';
        
        $table_exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
            DB_NAME,
            $table_name
        ));
        
        return $table_exists > 0;
    }
    
    /**
     * Add admin notices if the history table is not available
     */
    public static function maybe_show_setup_notice() {
        if (!self::is_history_table_available()) {
            add_action('admin_notices', function() {
                echo '<div class="notice notice-warning"><p>';
                echo '<strong>AYSA SEO History:</strong> The history table is not set up. ';
                echo 'Please activate the AYSA plugin or run the database setup to enable SEO history tracking.';
                echo '</p></div>';
            });
        }
    }
}

// Initialize the admin interface
if (is_admin()) {
    new Aysa_Seo_History_Admin();
    
    // Show setup notice if needed
    Aysa_Seo_History_Admin::maybe_show_setup_notice();
}
