<?php
/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 * 
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 * 
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 * 
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 * 
 * END OF HEADER
 */

/**
 * CastConductor Shoutout Moderation Admin Page
 *
 * Handles the WordPress admin interface for the optional shoutout moderation system.
 * Provides comprehensive moderation controls, statistics, and settings management.
 *
 * @package CastConductor
 * @since 5.0.0
 */

class CastConductor_Shoutout_Moderation_Admin {

    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 20);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_cc_moderation_action', array($this, 'handle_ajax_action'));
        add_action('admin_notices', array($this, 'shoutout_shortcode_notice'));
    }

    /**
     * Display shortcode notice on shoutouts post list page
     */
    public function shoutout_shortcode_notice() {
        $screen = get_current_screen();
        if (!$screen || $screen->post_type !== 'cc_shoutout' || $screen->base !== 'edit') {
            return;
        }
        ?>
        <div class="notice notice-info" style="padding: 15px;">
            <h3 style="margin: 0 0 10px 0;"><?php _e('Embed Shoutout Form on Your Website', 'castconductor'); ?></h3>
            <p style="margin: 0 0 10px 0;"><?php _e('Use this shortcode to add a shoutout submission form to any page, post, or widget:', 'castconductor'); ?></p>
            <div style="display: flex; align-items: center; gap: 10px;">
                <code id="shoutout-shortcode-notice" style="padding: 10px 15px; background: #f0f0f1; border: 1px solid #c3c4c7; border-radius: 4px; font-size: 14px;">[castconductor_shoutout_form]</code>
                <button type="button" class="button button-primary" onclick="
                    navigator.clipboard.writeText('[castconductor_shoutout_form]').then(function() {
                        var btn = event.target;
                        var originalText = btn.innerHTML;
                        btn.innerHTML = '<?php esc_attr_e('Copied!', 'castconductor'); ?> ✓';
                        btn.disabled = true;
                        setTimeout(function() {
                            btn.innerHTML = originalText;
                            btn.disabled = false;
                        }, 2000);
                    });
                ">
                    <span class="dashicons dashicons-clipboard" style="vertical-align: text-bottom;"></span>
                    <?php _e('Copy', 'castconductor'); ?>
                </button>
                <a href="<?php echo admin_url('admin.php?page=castconductor-settings'); ?>" class="button"><?php _e('More Options', 'castconductor'); ?></a>
            </div>
        </div>
        <?php
    }

    /**
     * Add admin menu page
     */
    public function add_admin_menu() {
        add_submenu_page(
            'castconductor',
            __('Shoutout Moderation', 'castconductor'),
            __('Moderation', 'castconductor'),
            'manage_options',
            'castconductor-moderation',
            array($this, 'render_admin_page')
        );
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook_suffix) {
        if ($hook_suffix !== 'castconductor_page_castconductor-moderation') {
            return;
        }

        // Enqueue admin styles
        wp_enqueue_style(
            'castconductor-moderation-admin',
            CASTCONDUCTOR_PLUGIN_URL . 'assets/css/admin-shoutout-moderation.css',
            array(),
            CASTCONDUCTOR_VERSION
        );

        // Enqueue admin scripts
        wp_enqueue_script(
            'castconductor-moderation-admin',
            CASTCONDUCTOR_PLUGIN_URL . 'assets/js/admin-shoutout-moderation.js',
            array('jquery'),
            CASTCONDUCTOR_VERSION,
            true
        );

        // Localize script with AJAX data
        wp_localize_script(
            'castconductor-moderation-admin',
            'castconductorModerationAjax',
            array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'rest_url' => rest_url(),
                'nonce' => wp_create_nonce('wp_rest'),
                'strings' => array(
                    'confirm_approve' => __('Are you sure you want to approve this shoutout?', 'castconductor'),
                    'confirm_reject' => __('Are you sure you want to reject this shoutout?', 'castconductor'),
                    'confirm_bulk' => __('Are you sure you want to perform this bulk action?', 'castconductor'),
                    'loading' => __('Loading...', 'castconductor'),
                    'error' => __('An error occurred. Please try again.', 'castconductor'),
                    'success' => __('Action completed successfully.', 'castconductor'),
                )
            )
        );
    }

    /**
     * Render the admin page
     */
    public function render_admin_page() {
        // Check if moderation is enabled
        $settings = get_option('castconductor_shoutout_moderation_settings', array());
        $moderation_enabled = isset($settings['moderation_enabled']) ? $settings['moderation_enabled'] : false;

        ?>
        <div class="wrap shoutout-moderation-page">
            <div id="shoutout-moderation-container">
                <h1><?php _e('CastConductor Shoutout Moderation', 'castconductor'); ?></h1>

                <?php if (!$moderation_enabled): ?>
                    <div class="notice notice-info">
                        <p>
                            <?php _e('Shoutout moderation is currently disabled. Enable it in the Settings tab to start moderating user submissions.', 'castconductor'); ?>
                        </p>
                    </div>
                <?php endif; ?>

                <!-- Navigation Tabs -->
                <div class="moderation-nav-tabs">
                    <button class="moderation-nav-tab active" data-tab="pending">
                        <?php _e('Pending Review', 'castconductor'); ?>
                        <span id="pending-count" class="nav-count"></span>
                    </button>
                    <button class="moderation-nav-tab" data-tab="statistics">
                        <?php _e('Statistics', 'castconductor'); ?>
                    </button>
                    <button class="moderation-nav-tab" data-tab="settings">
                        <?php _e('Settings', 'castconductor'); ?>
                    </button>
                </div>

                <!-- Tab Content -->
                <div class="moderation-tab-content">
                    
                    <!-- Pending Review Tab -->
                    <div id="pending-tab" class="moderation-tab-pane active">
                        <?php $this->render_pending_tab(); ?>
                    </div>

                    <!-- Statistics Tab -->
                    <div id="statistics-tab" class="moderation-tab-pane">
                        <?php $this->render_statistics_tab(); ?>
                    </div>

                    <!-- Settings Tab -->
                    <div id="settings-tab" class="moderation-tab-pane">
                        <?php $this->render_settings_tab(); ?>
                    </div>

                </div>
            </div>

            <!-- Modals -->
            <?php $this->render_modals(); ?>

            <!-- Notifications Container -->
            <div id="moderation-notifications"></div>

            <!-- Loader -->
            <div id="moderation-loader" class="moderation-loader">
                <div class="loader-spinner"></div>
                <div class="loader-text"><?php _e('Loading...', 'castconductor'); ?></div>
            </div>
        </div>

        <script>
            // Tab switching functionality
            document.addEventListener('DOMContentLoaded', function() {
                const tabs = document.querySelectorAll('.moderation-nav-tab');
                const panes = document.querySelectorAll('.moderation-tab-pane');

                tabs.forEach(tab => {
                    tab.addEventListener('click', function() {
                        const targetTab = this.dataset.tab;

                        // Update active tab
                        tabs.forEach(t => t.classList.remove('active'));
                        this.classList.add('active');

                        // Update active pane
                        panes.forEach(pane => pane.classList.remove('active'));
                        document.getElementById(targetTab + '-tab').classList.add('active');
                    });
                });
            });
        </script>
        <?php
    }

    /**
     * Render pending review tab
     */
    private function render_pending_tab() {
        ?>
        <div class="moderation-controls">
            <div class="bulk-actions">
                <select id="bulk-action-select">
                    <option value=""><?php _e('Bulk Actions', 'castconductor'); ?></option>
                    <option value="approve"><?php _e('Approve Selected', 'castconductor'); ?></option>
                    <option value="reject"><?php _e('Reject Selected', 'castconductor'); ?></option>
                    <option value="delete"><?php _e('Delete Selected', 'castconductor'); ?></option>
                </select>
                <button type="button" id="bulk-action-btn" class="button" disabled>
                    <?php _e('Apply', 'castconductor'); ?>
                </button>
                <span class="selected-count">
                    <?php _e('Selected:', 'castconductor'); ?> <span id="selected-count">0</span>
                </span>
            </div>

            <div class="refresh-controls">
                <label class="auto-refresh-control">
                    <input type="checkbox" id="auto-refresh-toggle" checked>
                    <?php _e('Auto-refresh (30s)', 'castconductor'); ?>
                </label>
                <button type="button" id="refresh-moderation-btn" class="button">
                    <span class="dashicons dashicons-update"></span>
                    <?php _e('Refresh', 'castconductor'); ?>
                </button>
            </div>
        </div>

        <div class="pending-shoutouts-container">
            <div class="pending-shoutouts-header">
                <label>
                    <input type="checkbox" id="select-all-shoutouts">
                    <?php _e('Select All', 'castconductor'); ?>
                </label>
            </div>
            <div id="pending-shoutouts-list">
                <!-- Populated by JavaScript -->
            </div>
        </div>

        <div id="moderation-pagination">
            <!-- Populated by JavaScript -->
        </div>
        <?php
    }

    /**
     * Render statistics tab
     */
    private function render_statistics_tab() {
        ?>
        <div class="moderation-stats">
            <div class="stats-section">
                <h3><?php _e('All Time Statistics', 'castconductor'); ?></h3>
                <div id="all-time-stats" class="stats-grid">
                    <!-- Populated by JavaScript -->
                </div>
            </div>

            <div class="stats-section">
                <h3><?php _e('Today\'s Activity', 'castconductor'); ?></h3>
                <div id="today-stats" class="stats-grid">
                    <!-- Populated by JavaScript -->
                </div>
            </div>
        </div>

        <div class="stats-charts">
            <h3><?php _e('Moderation Trends', 'castconductor'); ?></h3>
            <p class="description">
                <?php _e('Advanced analytics and trend charts will be available in a future update.', 'castconductor'); ?>
            </p>
        </div>
        <?php
    }

    /**
     * Render settings tab
     */
    private function render_settings_tab() {
        ?>
        <form id="moderation-settings-form" class="moderation-settings-form">
            
            <!-- Shortcode Section -->
            <div class="setting-group shortcode-section">
                <h3><?php _e('Embed Shoutout Form', 'castconductor'); ?></h3>
                <p class="setting-description">
                    <?php _e('Use this shortcode to embed the shoutout submission form on any page, post, or widget.', 'castconductor'); ?>
                </p>
                <div class="shortcode-copy-container" style="display: flex; align-items: center; gap: 10px; margin: 15px 0;">
                    <code id="shoutout-shortcode" style="padding: 10px 15px; background: #f0f0f1; border: 1px solid #c3c4c7; border-radius: 4px; font-size: 14px; font-family: monospace;">[castconductor_shoutout_form]</code>
                    <button type="button" id="copy-shortcode-btn" class="button button-secondary" onclick="
                        navigator.clipboard.writeText('[castconductor_shoutout_form]').then(function() {
                            var btn = document.getElementById('copy-shortcode-btn');
                            var originalText = btn.innerHTML;
                            btn.innerHTML = '<?php esc_attr_e('Copied!', 'castconductor'); ?> ✓';
                            btn.disabled = true;
                            setTimeout(function() {
                                btn.innerHTML = originalText;
                                btn.disabled = false;
                            }, 2000);
                        });
                    ">
                        <span class="dashicons dashicons-clipboard" style="margin-right: 5px; vertical-align: text-bottom;"></span>
                        <?php _e('Copy Shortcode', 'castconductor'); ?>
                    </button>
                </div>
                <details style="margin-top: 10px;">
                    <summary style="cursor: pointer; font-weight: 500; color: #2271b1;"><?php _e('Advanced Shortcode Options', 'castconductor'); ?></summary>
                    <div style="margin-top: 10px; padding: 15px; background: #f6f7f7; border-radius: 4px;">
                        <p style="margin-bottom: 10px;"><strong><?php _e('Theme:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px;">[castconductor_shoutout_form theme="dark"]</code>
                        
                        <p style="margin-bottom: 10px;"><strong><?php _e('Custom Button Text:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px;">[castconductor_shoutout_form button_text="Send Your Shoutout!"]</code>
                        
                        <p style="margin-bottom: 10px;"><strong><?php _e('Custom Width:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px;">[castconductor_shoutout_form width="400px"]</code>
                        
                        <p style="margin-bottom: 10px;"><strong><?php _e('Custom Placeholders:', 'castconductor'); ?></strong></p>
                        <code style="display: block; margin-bottom: 15px;">[castconductor_shoutout_form placeholder_name="Your Name" placeholder_message="What do you want to say?"]</code>
                        
                        <p style="margin-bottom: 10px;"><strong><?php _e('Full Example:', 'castconductor'); ?></strong></p>
                        <code style="display: block; font-size: 12px;">[castconductor_shoutout_form theme="dark" width="500px" button_text="Shout it!" placeholder_name="Name" placeholder_location="City" placeholder_message="Your message..."]</code>
                    </div>
                </details>
            </div>
            
            <!-- General Settings -->
            <div class="setting-group">
                <h3><?php _e('General Settings', 'castconductor'); ?></h3>
                
                <div class="setting-row">
                    <div class="setting-control">
                        <label class="setting-checkbox-label">
                            <input type="checkbox" id="moderation-enabled" name="moderation_enabled">
                            <strong><?php _e('Enable Shoutout Moderation', 'castconductor'); ?></strong>
                        </label>
                        <div class="setting-description">
                            <?php _e('When enabled, all shoutouts will require approval before being displayed.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="setting-row">
                    <div class="setting-control">
                        <label class="setting-checkbox-label">
                            <input type="checkbox" id="auto-approve" name="auto_approve">
                            <strong><?php _e('Auto-approve low-risk shoutouts', 'castconductor'); ?></strong>
                        </label>
                        <div class="setting-description">
                            <?php _e('Automatically approve shoutouts that pass all filters and have low risk scores.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="setting-row">
                    <div class="setting-control">
                        <label class="setting-checkbox-label">
                            <input type="checkbox" id="email-notifications" name="email_notifications">
                            <strong><?php _e('Email notifications', 'castconductor'); ?></strong>
                        </label>
                        <div class="setting-description">
                            <?php _e('Send email notifications when new shoutouts are submitted for review.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="setting-row">
                    <div class="setting-control">
                        <label for="notification-email"><?php _e('Notification Email', 'castconductor'); ?></label>
                        <input type="email" id="notification-email" name="notification_email" 
                               value="<?php echo esc_attr(get_option('admin_email')); ?>" 
                               placeholder="<?php esc_attr_e('admin@example.com', 'castconductor'); ?>">
                        <div class="setting-description">
                            <?php _e('Email address to receive moderation notifications.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Content Filtering -->
            <div class="setting-group">
                <h3><?php _e('Content Filtering', 'castconductor'); ?></h3>
                
                <div class="setting-row">
                    <div class="setting-control">
                        <label class="setting-checkbox-label">
                            <input type="checkbox" id="word-filter" name="word_filter">
                            <strong><?php _e('Enable word filtering', 'castconductor'); ?></strong>
                        </label>
                        <div class="setting-description">
                            <?php _e('Flag shoutouts containing inappropriate words for manual review.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="setting-row">
                    <div class="setting-control">
                        <label class="setting-checkbox-label">
                            <input type="checkbox" id="duplicate-check" name="duplicate_check">
                            <strong><?php _e('Check for duplicate content', 'castconductor'); ?></strong>
                        </label>
                        <div class="setting-description">
                            <?php _e('Flag potential duplicate shoutouts submitted within 24 hours.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- reCAPTCHA Settings -->
            <div class="setting-group">
                <h3><?php _e('reCAPTCHA v3 Protection', 'castconductor'); ?></h3>
                
                <div class="setting-row">
                    <div class="setting-control">
                        <label class="setting-checkbox-label">
                            <input type="checkbox" id="recaptcha-enabled" name="recaptcha_enabled">
                            <strong><?php _e('Enable reCAPTCHA v3', 'castconductor'); ?></strong>
                        </label>
                        <div class="setting-description">
                            <?php _e('Use Google reCAPTCHA v3 to score and filter submissions based on likelihood of being spam.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="setting-row">
                    <div class="setting-control">
                        <label for="recaptcha-site-key"><?php _e('Site Key', 'castconductor'); ?></label>
                        <input type="text" id="recaptcha-site-key" name="recaptcha_site_key" 
                               placeholder="6Lc...">
                        <div class="setting-description">
                            <?php _e('Your reCAPTCHA v3 site key from Google.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="setting-row">
                    <div class="setting-control">
                        <label for="recaptcha-secret-key"><?php _e('Secret Key', 'castconductor'); ?></label>
                        <input type="text" id="recaptcha-secret-key" name="recaptcha_secret_key" 
                               placeholder="6Lc...">
                        <div class="setting-description">
                            <?php _e('Your reCAPTCHA v3 secret key from Google.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="setting-row">
                    <div class="setting-control">
                        <label for="recaptcha-threshold"><?php _e('Score Threshold', 'castconductor'); ?></label>
                        <input type="number" id="recaptcha-threshold" name="recaptcha_threshold" 
                               min="0" max="1" step="0.1" value="0.5">
                        <div class="setting-description">
                            <?php _e('Minimum reCAPTCHA score required (0.0 - 1.0). Lower scores indicate higher likelihood of spam.', 'castconductor'); ?>
                        </div>
                    </div>
                </div>

                <div class="recaptcha-test">
                    <button type="button" id="test-recaptcha-btn" class="button button-secondary">
                        <?php _e('Test Configuration', 'castconductor'); ?>
                    </button>
                    <span class="description">
                        <?php _e('Test your reCAPTCHA configuration.', 'castconductor'); ?>
                    </span>
                </div>
            </div>

            <div class="setting-row">
                <button type="submit" class="button button-primary">
                    <?php _e('Save Settings', 'castconductor'); ?>
                </button>
            </div>

        </form>
        <?php
    }

    /**
     * Render modals
     */
    private function render_modals() {
        ?>
        <!-- Reject Modal -->
        <div id="reject-modal" class="moderation-modal">
            <div class="modal-content">
                <button class="modal-close" onclick="this.closest('.moderation-modal').style.display='none'">&times;</button>
                <div class="modal-header">
                    <h3><?php _e('Reject Shoutout', 'castconductor'); ?></h3>
                </div>
                <div class="modal-body">
                    <label for="reject-reason"><?php _e('Reason for rejection (optional):', 'castconductor'); ?></label>
                    <textarea id="reject-reason" placeholder="<?php esc_attr_e('e.g., Inappropriate content, spam, etc.', 'castconductor'); ?>"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="button" onclick="this.closest('.moderation-modal').style.display='none'">
                        <?php _e('Cancel', 'castconductor'); ?>
                    </button>
                    <button type="button" id="confirm-reject" class="button button-secondary">
                        <?php _e('Reject Shoutout', 'castconductor'); ?>
                    </button>
                </div>
            </div>
        </div>

        <!-- Bulk Action Modal -->
        <div id="bulk-action-modal" class="moderation-modal">
            <div class="modal-content">
                <button class="modal-close" onclick="this.closest('.moderation-modal').style.display='none'">&times;</button>
                <div class="modal-header">
                    <h3><?php _e('Confirm Bulk Action', 'castconductor'); ?></h3>
                </div>
                <div class="modal-body">
                    <p><?php _e('Are you sure you want to', 'castconductor'); ?> <span id="bulk-action-text"></span>?</p>
                    <div id="bulk-reason" style="display: none;">
                        <label for="bulk-reason-input"><?php _e('Reason (for rejections):', 'castconductor'); ?></label>
                        <textarea id="bulk-reason-input" placeholder="<?php esc_attr_e('Bulk rejection reason...', 'castconductor'); ?>"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="button" onclick="this.closest('.moderation-modal').style.display='none'">
                        <?php _e('Cancel', 'castconductor'); ?>
                    </button>
                    <button type="button" id="confirm-bulk-action" class="button button-primary">
                        <?php _e('Confirm', 'castconductor'); ?>
                    </button>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Handle AJAX actions
     */
    public function handle_ajax_action() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'wp_rest')) {
            wp_die(__('Security check failed', 'castconductor'));
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('Insufficient permissions', 'castconductor'));
        }

        $action = sanitize_text_field($_POST['action']);
        $response = array('success' => false, 'message' => '');

        switch ($action) {
            case 'cc_test_connection':
                $response = $this->test_moderation_connection();
                break;

            default:
                $response['message'] = __('Unknown action', 'castconductor');
                break;
        }

        wp_send_json($response);
    }

    /**
     * Test moderation system connection
     */
    private function test_moderation_connection() {
        try {
            // Test database connection and basic functionality
            global $wpdb;
            
            $table_name = $wpdb->prefix . 'castconductor_content_blocks';
            $test_query = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE type = 'shoutout'");
            
            if ($test_query !== null) {
                return array(
                    'success' => true,
                    'message' => sprintf(
                        __('Moderation system is working. Found %d shoutouts in database.', 'castconductor'),
                        intval($test_query)
                    )
                );
            } else {
                return array(
                    'success' => false,
                    'message' => __('Database connection test failed.', 'castconductor')
                );
            }
        } catch (Exception $e) {
            return array(
                'success' => false,
                'message' => sprintf(
                    __('Test failed: %s', 'castconductor'),
                    $e->getMessage()
                )
            );
        }
    }
}

// Initialize the admin class
if (is_admin()) {
    new CastConductor_Shoutout_Moderation_Admin();
}
