<?php
/**
 * AYSA SEO Generation History Admin Interface
 * 
 * Displays SEO generation history with filtering, search, and version management.
 * 
 * @package AYSA
 * @since 1.0.0
 */

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

// Get the SEO history manager
$seo_history = aysa_get_seo_history();

// Handle actions
if (isset($_POST['action']) && wp_verify_nonce($_POST['aysa_history_nonce'], 'aysa_history_action')) {
    switch ($_POST['action']) {
        case 'cleanup_old':
            $days = intval($_POST['cleanup_days'] ?? 90);
            $deleted = $seo_history->cleanup_old_entries($days);
            echo '<div class="notice notice-success"><p>Cleaned up ' . $deleted . ' old entries.</p></div>';
            break;
            
        case 'mark_applied':
            if (isset($_POST['entry_id'])) {
                $seo_history->mark_as_applied(intval($_POST['entry_id']));
                echo '<div class="notice notice-success"><p>Entry marked as applied.</p></div>';
            }
            break;
            
        case 'mark_reverted':
            if (isset($_POST['entry_id'])) {
                $seo_history->mark_as_reverted(intval($_POST['entry_id']));
                echo '<div class="notice notice-success"><p>Entry marked as reverted.</p></div>';
            }
            break;
    }
}

// Get filter parameters
$search_term = sanitize_text_field($_GET['search'] ?? '');
$entity_type_filter = sanitize_text_field($_GET['entity_type'] ?? '');
$entity_id_filter = intval($_GET['entity_id'] ?? 0);
$generator_type_filter = sanitize_text_field($_GET['generator_type'] ?? '');
$user_filter = intval($_GET['user_id'] ?? 0);
$limit = intval($_GET['limit'] ?? 50);

// Get history data
if ($entity_id_filter > 0 && !empty($entity_type_filter)) {
    $history_entries = $seo_history->get_entity_history($entity_id_filter, $entity_type_filter, $limit);
} elseif (!empty($search_term)) {
    $history_entries = $seo_history->search_history($search_term, $limit);
} elseif ($user_filter > 0) {
    $history_entries = $seo_history->get_user_history($user_filter, $limit);
} else {
    $history_entries = $seo_history->get_recent_history($limit);
}

// Get statistics
$stats = $seo_history->get_statistics();

// Get users for filter dropdown
$users = get_users(array('fields' => array('ID', 'display_name')));

?>

<div class="wrap">
    <h1 class="wp-heading-inline">
        <span class="dashicons dashicons-chart-line"></span>
        SEO Generation History
    </h1>
    
    <hr class="wp-header-end">
    
    <!-- Statistics Dashboard -->
    <div class="aysa-stats-dashboard">
        <div class="aysa-stats-grid aysa-stats-grid--spaced">
            <div class="aysa-stat-card">
                <h3 class="aysa-stat-title aysa-stat-title--primary"><?php echo number_format($stats['total_generations']); ?></h3>
                <p class="aysa-stat-subtitle">Total Generations</p>
            </div>
            
            <div class="aysa-stat-card">
                <h3 class="aysa-stat-title aysa-stat-title--success"><?php echo number_format($stats['applied_count']); ?></h3>
                <p class="aysa-stat-subtitle">Applied Suggestions</p>
            </div>
            
            <div class="aysa-stat-card">
                <h3 class="aysa-stat-title aysa-stat-title--danger"><?php echo number_format($stats['recent_activity']); ?></h3>
                <p class="aysa-stat-subtitle">Last 30 Days</p>
            </div>
            
            <div class="aysa-stat-card">
                <h3 class="aysa-stat-title aysa-stat-title--warning">
                    <?php 
                    $applied_rate = $stats['total_generations'] > 0 ? 
                        round(($stats['applied_count'] / $stats['total_generations']) * 100, 1) : 0;
                    echo $applied_rate . '%';
                    ?>
                </h3>
                <p class="aysa-stat-subtitle">Application Rate</p>
            </div>
        </div>
        
        <!-- Entity Type Breakdown -->
        <div class="aysa-entity-breakdown aysa-summary-card">
            <h3 class="aysa-summary-title">Generations by Entity Type</h3>
            <div class="aysa-summary-flex">
                <?php foreach ($stats['by_entity_type'] as $entity_stat): ?>
                    <div class="aysa-summary-item">
                        <strong class="aysa-summary-value aysa-summary-value--primary"><?php echo number_format($entity_stat->count); ?></strong>
                        <br>
                        <span class="aysa-summary-label"><?php echo esc_html($entity_stat->entity_type); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Generator Type Breakdown -->
        <div class="aysa-generator-breakdown aysa-summary-card">
            <h3 class="aysa-summary-title">Generations by Generator Type</h3>
            <div class="aysa-summary-flex">
                <?php foreach ($stats['by_generator_type'] as $generator_stat): ?>
                    <div class="aysa-summary-item">
                        <strong class="aysa-summary-value aysa-summary-value--success"><?php echo number_format($generator_stat->count); ?></strong>
                        <br>
                        <span class="aysa-summary-label"><?php echo esc_html(ucfirst($generator_stat->generator_type)); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <!-- Filters and Search -->
    <div class="aysa-history-filters">
        <form method="get" action="">
            <input type="hidden" name="page" value="<?php echo esc_attr($_GET['page'] ?? ''); ?>">
            
            <div class="aysa-filter-grid">
                <div>
                    <label for="search" class="aysa-label">Search</label>
                    <input type="text" id="search" name="search" value="<?php echo esc_attr($search_term); ?>" 
                           placeholder="Search keywords, titles, descriptions..." 
                           class="aysa-input">
                </div>
                
                <div>
                    <label for="entity_type" class="aysa-label">Entity Type</label>
                    <select id="entity_type" name="entity_type" class="aysa-input">
                        <option value="">All Types</option>
                        <option value="Product" <?php selected($entity_type_filter, 'Product'); ?>>Product</option>
                        <option value="Category" <?php selected($entity_type_filter, 'Category'); ?>>Category</option>
                        <option value="Page" <?php selected($entity_type_filter, 'Page'); ?>>Page</option>
                        <option value="Post" <?php selected($entity_type_filter, 'Post'); ?>>Post</option>
                    </select>
                </div>

                <div>
                    <label for="entity_id" class="aysa-label">Entity ID</label>
                    <input type="number" id="entity_id" name="entity_id" min="1" value="<?php echo esc_attr($entity_id_filter > 0 ? $entity_id_filter : ''); ?>" class="aysa-input" placeholder="e.g. 4288">
                </div>
                
                <div>
                    <label for="generator_type" class="aysa-label">Generator</label>
                    <select id="generator_type" name="generator_type" class="aysa-input">
                        <option value="">All Generators</option>
                        <option value="original" <?php selected($generator_type_filter, 'original'); ?>>Original</option>
                        <option value="new" <?php selected($generator_type_filter, 'new'); ?>>New (Experimental)</option>
                        <option value="custom" <?php selected($generator_type_filter, 'custom'); ?>>Custom</option>
                    </select>
                </div>
                
                <div>
                    <label for="user_id" class="aysa-label">User</label>
                    <select id="user_id" name="user_id" class="aysa-input">
                        <option value="">All Users</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?php echo $user->ID; ?>" <?php selected($user_filter, $user->ID); ?>>
                                <?php echo esc_html($user->display_name); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div>
                    <label for="limit" class="aysa-label">Limit</label>
                    <select id="limit" name="limit" class="aysa-input">
                        <option value="25" <?php selected($limit, 25); ?>>25</option>
                        <option value="50" <?php selected($limit, 50); ?>>50</option>
                        <option value="100" <?php selected($limit, 100); ?>>100</option>
                        <option value="200" <?php selected($limit, 200); ?>>200</option>
                    </select>
                </div>
                
                <div>
                    <button type="submit" class="button button-primary aysa-btn-full">Filter</button>
                </div>
            </div>
        </form>
    </div>
    
    <!-- History Table -->
    <div class="aysa-history-table-container aysa-table-responsive">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th class="aysa-col-id">ID</th>
                    <th class="aysa-col-entity">Entity</th>
                    <th class="aysa-col-type">Type</th>
                    <th>Keyword</th>
                    <th>Generated Content</th>
                    <th class="aysa-col-version">Version</th>
                    <th class="aysa-col-generator">Generator</th>
                    <th class="aysa-col-status">Status</th>
                    <th class="aysa-col-user">User</th>
                    <th class="aysa-col-created">Created</th>
                    <th class="aysa-col-actions">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($history_entries)): ?>
                    <tr>
                        <td colspan="11" class="aysa-empty-state">
                            <span class="dashicons dashicons-search aysa-empty-state-icon"></span>
                            <br><br>
                            No SEO generation history found.
                            <?php if (!empty($search_term)): ?>
                                <br>Try adjusting your search criteria.
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($history_entries as $entry): ?>
                        <tr>
                            <td><strong>#<?php echo $entry->id; ?></strong></td>
                            
                            <td>
                                <strong><?php echo esc_html($entry->entity_id); ?></strong>
                                <?php if (!empty($entry->entity_name)): ?>
                                    <br><small class="aysa-text-muted"><?php echo esc_html($entry->entity_name); ?></small>
                                <?php endif; ?>
                            </td>
                            
                            <td>
                                <?php
                                $entity_type_class = 'aysa-entity-type-badge--other';
                                if ($entry->entity_type === 'Product') {
                                    $entity_type_class = 'aysa-entity-type-badge--product';
                                } elseif ($entry->entity_type === 'Category') {
                                    $entity_type_class = 'aysa-entity-type-badge--category';
                                } elseif ($entry->entity_type === 'Page') {
                                    $entity_type_class = 'aysa-entity-type-badge--page';
                                }
                                ?>
                                <span class="aysa-entity-type-badge <?php echo esc_attr($entity_type_class); ?>">
                                    <?php echo esc_html($entry->entity_type); ?>
                                </span>
                            </td>
                            
                            <td>
                                <strong class="aysa-keyword-strong"><?php echo esc_html($entry->keyword); ?></strong>
                                <?php if (!empty($entry->language) && $entry->language !== 'en'): ?>
                                    <br><small class="aysa-text-muted">Language: <?php echo esc_html($entry->language); ?></small>
                                <?php endif; ?>
                            </td>
                            
                            <td>
                                <div class="aysa-generated-content aysa-generated-content--max">
                                    <?php if (!empty($entry->meta_title)): ?>
                                        <div class="aysa-generated-block">
                                            <strong class="aysa-generated-label">META TITLE:</strong>
                                            <div class="aysa-generated-value">
                                                <?php echo esc_html(wp_trim_words($entry->meta_title, 8)); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($entry->meta_description)): ?>
                                        <div class="aysa-generated-block">
                                            <strong class="aysa-generated-label">META DESC:</strong>
                                            <div class="aysa-generated-value">
                                                <?php echo esc_html(wp_trim_words($entry->meta_description, 10)); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($entry->secondary_keywords)): ?>
                                        <div>
                                            <strong class="aysa-generated-label">KEYWORDS:</strong>
                                            <div class="aysa-generated-value">
                                                <?php echo esc_html(wp_trim_words($entry->secondary_keywords, 5)); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($entry->partial_failure): ?>
                                        <div class="aysa-generated-warning">
                                            <span class="aysa-generated-warning-label">⚠ Partial Failure</span>
                                            <?php if (!empty($entry->failed_fields)): ?>
                                                <br><small class="aysa-text-muted"><?php echo esc_html($entry->failed_fields); ?></small>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            
                            <td class="u-text-center">
                                <strong class="aysa-keyword-strong">v<?php echo $entry->version; ?></strong>
                                <?php if ($entry->is_current_version): ?>
                                    <br><span class="aysa-status-current">CURRENT</span>
                                <?php endif; ?>
                            </td>
                            
                            <td>
                                <?php $generator_class = $entry->generator_type === 'new' ? 'aysa-generator-badge--new' : 'aysa-generator-badge--legacy'; ?>
                                <span class="aysa-generator-badge <?php echo esc_attr($generator_class); ?>">
                                    <?php echo esc_html(strtoupper($entry->generator_type)); ?>
                                </span>
                                <br>
                                <small class="aysa-text-muted aysa-text-xs">
                                    <?php echo esc_html($entry->generation_method); ?>
                                </small>
                            </td>
                            
                            <td>
                                <?php
                                if ($entry->is_applied) {
                                    $status_text = 'APPLIED';
                                } elseif ($entry->is_reverted) {
                                    $status_text = 'REVERTED';
                                } else {
                                    $status_text = strtoupper($entry->status);
                                }
                                ?>
                                <?php
                                $status_class = 'aysa-status-badge--default';
                                if ($entry->is_applied) {
                                    $status_class = 'aysa-status-badge--applied';
                                } elseif ($entry->is_reverted) {
                                    $status_class = 'aysa-status-badge--reverted';
                                }
                                ?>
                                <span class="aysa-status-badge <?php echo esc_attr($status_class); ?>">
                                    <?php echo $status_text; ?>
                                </span>
                                
                                <?php if (!empty($entry->confidence_score)): ?>
                                    <br><small class="aysa-text-muted aysa-text-xs">
                                        Confidence: <?php echo number_format($entry->confidence_score, 1); ?>%
                                    </small>
                                <?php endif; ?>
                            </td>
                            
                            <td>
                                <?php echo esc_html($entry->user_name ?? 'Unknown'); ?>
                                <br><small class="aysa-text-muted aysa-text-xs">
                                    ID: <?php echo $entry->wp_user_id; ?>
                                </small>
                            </td>
                            
                            <td>
                                <strong><?php echo date('M j, Y', strtotime($entry->created_at)); ?></strong>
                                <br><small class="aysa-text-muted"><?php echo date('H:i:s', strtotime($entry->created_at)); ?></small>
                                
                                <?php if (!empty($entry->api_response_time)): ?>
                                    <br><small class="aysa-text-muted aysa-text-xs">
                                        <?php echo number_format($entry->api_response_time / 1000, 1); ?>s
                                    </small>
                                <?php endif; ?>
                            </td>
                            
                            <td>
                                <div class="aysa-entry-actions aysa-entry-actions--stack">
                                    <?php if (!$entry->is_applied && !$entry->is_reverted): ?>
                                        <form method="post" class="aysa-form-reset">
                                            <?php wp_nonce_field('aysa_history_action', 'aysa_history_nonce'); ?>
                                            <input type="hidden" name="action" value="mark_applied">
                                            <input type="hidden" name="entry_id" value="<?php echo $entry->id; ?>">
                                            <button type="submit" class="button button-small aysa-btn-compact">
                                                ✓ Applied
                                            </button>
                                        </form>
                                        
                                        <form method="post" class="aysa-form-reset">
                                            <?php wp_nonce_field('aysa_history_action', 'aysa_history_nonce'); ?>
                                            <input type="hidden" name="action" value="mark_reverted">
                                            <input type="hidden" name="entry_id" value="<?php echo $entry->id; ?>">
                                            <button type="submit" class="button button-small aysa-btn-compact">
                                                ✗ Reverted
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <button type="button" class="button button-small aysa-view-details" 
                                            data-entry-id="<?php echo $entry->id; ?>" 
                                            class="button button-small aysa-view-details aysa-btn-compact">
                                        👁 Details
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Cleanup Section -->
    <div class="aysa-cleanup-section">
        <h3 class="aysa-summary-title">Maintenance</h3>
        
        <form method="post" class="aysa-form-inline">
            <?php wp_nonce_field('aysa_history_action', 'aysa_history_nonce'); ?>
            <input type="hidden" name="action" value="cleanup_old">
            
            <label for="cleanup_days" class="aysa-mr-10">Delete entries older than:</label>
            <select name="cleanup_days" id="cleanup_days" class="aysa-mr-10">
                <option value="30">30 days</option>
                <option value="60">60 days</option>
                <option value="90" selected>90 days</option>
                <option value="180">180 days</option>
                <option value="365">1 year</option>
            </select>
            
            <button type="submit" class="button button-secondary" 
                    onclick="return confirm('Are you sure you want to delete old SEO history entries? This action cannot be undone.')">
                🗑 Cleanup Old Entries
            </button>
        </form>
        
        <p class="aysa-note-text">
            <strong>Note:</strong> Only non-current versions will be deleted. Current versions are preserved regardless of age.
        </p>
    </div>
</div>

<!-- Details Modal -->
<div id="aysa-details-modal" class="aysa-details-modal">
    <div class="aysa-details-modal-card">
        <div class="aysa-details-modal-header">
            <h2 class="aysa-details-modal-title">SEO Generation Details</h2>
            <button type="button" id="aysa-close-modal" class="aysa-details-modal-close">&times;</button>
        </div>
        <div id="aysa-modal-content"></div>
    </div>
</div>

<style>
.aysa-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
}
.aysa-stats-dashboard { margin: 20px 0; }
.aysa-stats-grid--spaced { margin-bottom: 20px; }
.aysa-stat-title { margin: 0; font-size: 24px; }
.aysa-stat-title--primary { color: #0073aa; }
.aysa-stat-title--success { color: #00a32a; }
.aysa-stat-title--danger { color: #d63638; }
.aysa-stat-title--warning { color: #f56e28; }
.aysa-stat-subtitle { margin: 5px 0 0; color: #666; }
.aysa-summary-card { background: #fff; padding: 15px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 20px; }
.aysa-summary-title { margin: 0 0 10px; color: #333; }
.aysa-summary-flex { display: flex; gap: 20px; flex-wrap: wrap; }
.aysa-summary-item { text-align: center; }
.aysa-summary-value { font-size: 18px; }
.aysa-summary-value--primary { color: #0073aa; }
.aysa-summary-value--success { color: #00a32a; }
.aysa-summary-label { color: #666; font-size: 12px; }
.aysa-filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end; }
.aysa-label { display: block; margin-bottom: 5px; font-weight: 600; }
.aysa-input { width: 100%; padding: 6px 8px; }
.aysa-btn-full { width: 100%; }
.aysa-col-id { width: 60px; }
.aysa-col-entity { width: 80px; }
.aysa-col-type { width: 100px; }
.aysa-col-version { width: 80px; }
.aysa-col-generator { width: 100px; }
.aysa-col-status { width: 80px; }
.aysa-col-user { width: 100px; }
.aysa-col-created { width: 120px; }
.aysa-col-actions { width: 100px; }
.aysa-empty-state { text-align: center; padding: 40px; color: #666; }
.aysa-empty-state-icon { font-size: 48px; opacity: .3; }
.aysa-text-muted { color: #666; }
.aysa-keyword-strong { color: #0073aa; }
.aysa-generated-content--max { max-width: 300px; }
.aysa-generated-block { margin-bottom: 8px; }
.aysa-generated-label { color: #333; font-size: 11px; }
.aysa-generated-value { color: #666; font-size: 12px; line-height: 1.3; }
.aysa-generated-warning { margin-top: 8px; }
.aysa-generated-warning-label { color: #d63638; font-size: 11px; font-weight: 600; }
.aysa-status-current { color: #00a32a; font-size: 11px; font-weight: 600; }
.aysa-text-xs { font-size: 10px; }
.aysa-status-badge { padding: 2px 6px; border-radius: 8px; font-size: 10px; font-weight: 600; }
.aysa-entry-actions--stack { display: flex; flex-direction: column; gap: 4px; }
.aysa-form-reset { margin: 0; }
.aysa-btn-compact { font-size: 10px; padding: 2px 6px; }
.aysa-form-inline { display: inline-block; margin-right: 20px; }
.aysa-mr-10 { margin-right: 10px; }
.aysa-note-text { color: #666; font-size: 12px; margin: 10px 0 0; }
.aysa-details-modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,.5); z-index: 100000; }
.aysa-details-modal-card { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #fff; padding: 20px; border-radius: 8px; max-width: 800px; max-height: 80vh; overflow-y: auto; width: 90%; }
.aysa-details-modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 1px solid #ddd; padding-bottom: 10px; }
.aysa-details-modal-title { margin: 0; }
.aysa-details-modal-close { background: none; border: none; font-size: 24px; cursor: pointer; }

.aysa-stat-card {
    background: #fff;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-align: center;
    transition: box-shadow 0.2s;
}

.aysa-stat-card:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.aysa-history-table-container {
    overflow-x: auto;
}

.aysa-generated-content {
    font-size: 12px;
    line-height: 1.4;
}

.aysa-entry-actions {
    min-width: 80px;
}

@media (max-width: 768px) {
    .aysa-stats-grid {
        grid-template-columns: 1fr 1fr;
    }
    
    .wp-list-table th,
    .wp-list-table td {
        padding: 8px 4px;
        font-size: 12px;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    // Handle details modal
    $('.aysa-view-details').on('click', function() {
        const entryId = $(this).data('entry-id');
        
        // Show loading
        $('#aysa-modal-content').html('<p>Loading details...</p>');
        $('#aysa-details-modal').show();
        
        // Fetch details via AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_seo_history_details',
                entry_id: entryId,
                nonce: '<?php echo wp_create_nonce('aysa_history_details'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $('#aysa-modal-content').html(response.data.html);
                } else {
                    $('#aysa-modal-content').html('<p>Error loading details: ' + response.data + '</p>');
                }
            },
            error: function() {
                $('#aysa-modal-content').html('<p>Error loading details. Please try again.</p>');
            }
        });
    });
    
    // Close modal
    $('#aysa-close-modal, #aysa-details-modal').on('click', function(e) {
        if (e.target === this) {
            $('#aysa-details-modal').hide();
        }
    });
    
    // Prevent modal content clicks from closing modal
    $('#aysa-details-modal > div').on('click', function(e) {
        e.stopPropagation();
    });
});
</script>
