<?php
class PC_Community_Suggestions_Admin {
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));

        add_action('admin_post_pc_delete_suggestion', array($this, 'handle_suggestion_deletion'));
    }
    
    public function add_admin_menu() {
        add_menu_page(
            __('Community Suggestions', 'pc-community-suggestions-7d3f'),
            __('Suggestions', 'pc-community-suggestions-7d3f'),
            'manage_options',
            'pc_community_suggestions',
            array($this, 'render_admin_page'),
            'dashicons-lightbulb',
            30
        );
        
        add_submenu_page(
            'pc_community_suggestions',
            __('All Suggestions', 'pc-community-suggestions-7d3f'),
            __('All Suggestions', 'pc-community-suggestions-7d3f'),
            'manage_options',
            'pc_community_suggestions',
            array($this, 'render_admin_page')
        );
        

        
        add_submenu_page(
            'pc_community_suggestions',
            __('Settings', 'pc-community-suggestions-7d3f'),
            __('Settings', 'pc-community-suggestions-7d3f'),
            'manage_options',
            'pc_community_suggestions_settings',
            array($this, 'render_settings_page')
        );
    }
    
    public function register_settings() {
        register_setting('pc_community_suggestions_settings', 'pc_community_suggestions_default_sort');
        
        add_settings_section(
            'pc_community_suggestions_general',
            __('General Settings', 'pc-community-suggestions-7d3f'),
            array($this, 'render_settings_section'),
            'pc_community_suggestions_settings'
        );
        

        
        add_settings_field(
            'pc_community_suggestions_default_sort',
            __('Default Sort Order', 'pc-community-suggestions-7d3f'),
            array($this, 'render_sort_field'),
            'pc_community_suggestions_settings',
            'pc_community_suggestions_general'
        );
    }
    
    public function render_settings_section() {
        echo '<p>' . __('Configure how community suggestions work on your site.', 'pc-community-suggestions-7d3f') . '</p>';
    }
    

    
    public function render_sort_field() {
        $default_sort = get_option('pc_community_suggestions_default_sort', 'popular');
        ?>
        <select name="pc_community_suggestions_default_sort">
            <option value="popular" <?php selected($default_sort, 'popular'); ?>><?php esc_html_e('Most Upvoted', 'pc-community-suggestions-7d3f'); ?></option>
            <option value="newest" <?php selected($default_sort, 'newest'); ?>><?php esc_html_e('Newest', 'pc-community-suggestions-7d3f'); ?></option>
        </select>
        <p class="description">
            <?php esc_html_e('Default sorting method for the suggestions page.', 'pc-community-suggestions-7d3f'); ?>
        </p>
        <?php
    }
    
    public function render_admin_page() {
        $current_tab = $_GET['tab'] ?? 'all';
        $sort = isset($_GET['sort']) && in_array($_GET['sort'], ['popular', 'newest']) ? $_GET['sort'] : 'newest';
        
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Community Suggestions', 'pc-community-suggestions-7d3f'); ?></h1>
            
            <div class="pc-admin-controls">
                <div class="pc-sort-dropdown">
                    <label for="pc-admin-sort"><?php esc_html_e('Sort by:', 'pc-community-suggestions-7d3f'); ?></label>
                    <select id="pc-admin-sort" onchange="window.location.href='?page=pc_community_suggestions&sort=' + this.value">
                        <option value="newest" <?php selected($sort, 'newest'); ?>><?php esc_html_e('Newest', 'pc-community-suggestions-7d3f'); ?></option>
                        <option value="popular" <?php selected($sort, 'popular'); ?>><?php esc_html_e('Most Upvoted', 'pc-community-suggestions-7d3f'); ?></option>
                    </select>
                </div>
            </div>
            
            <div class="pc-admin-content">
                <?php $this->render_suggestions_table($sort); ?>
            </div>
        </div>
        <?php
    }
    

    
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Community Suggestions Settings', 'pc-community-suggestions-7d3f'); ?></h1>
            
            <form method="post" action="options.php">
                <?php
                settings_fields('pc_community_suggestions_settings');
                do_settings_sections('pc_community_suggestions_settings');
                submit_button();
                ?>
            </form>
            
            <div class="pc-settings-stats">
                <h2><?php esc_html_e('Statistics', 'pc-community-suggestions-7d3f'); ?></h2>
                <div class="pc-stats-grid">
                    <div class="pc-stat-card">
                        <h3><?php echo esc_html(PC_Community_Suggestions_Database::get_suggestion_count()); ?></h3>
                        <p><?php esc_html_e('Total Suggestions', 'pc-community-suggestions-7d3f'); ?></p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    private function render_suggestions_table($sort = 'newest') {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'pc_community_suggestions';
        $order_by = $sort === 'newest' ? 'created_at DESC' : 'upvotes DESC, created_at DESC';
        
        $suggestions = $wpdb->get_results(
            "SELECT s.*, u.user_login, u.display_name 
             FROM $table_name s 
             LEFT JOIN {$wpdb->users} u ON s.user_id = u.ID 
             ORDER BY $order_by"
        );
        
        ?>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th><?php esc_html_e('Title', 'pc-community-suggestions-7d3f'); ?></th>
                    <th><?php esc_html_e('Author', 'pc-community-suggestions-7d3f'); ?></th>
                    <th><?php esc_html_e('Upvotes', 'pc-community-suggestions-7d3f'); ?></th>
                    <th><?php esc_html_e('Date', 'pc-community-suggestions-7d3f'); ?></th>
                    <th><?php esc_html_e('Actions', 'pc-community-suggestions-7d3f'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($suggestions)) : ?>
                    <tr>
                        <td colspan="5"><?php esc_html_e('No suggestions found.', 'pc-community-suggestions-7d3f'); ?></td>
                    </tr>
                <?php else : ?>
                    <?php foreach ($suggestions as $suggestion) : ?>
                        <tr>
                            <td>
                                <strong><?php echo esc_html($suggestion->title); ?></strong>
                                <div class="row-actions">
                                    <span class="view">
                                        <a href="#" onclick="pcPreviewSuggestion(<?php echo esc_attr($suggestion->id); ?>)">
                                            <?php esc_html_e('View Details', 'pc-community-suggestions-7d3f'); ?>
                                        </a> | 
                                    </span>
                                    <span class="comment">
                                        <a href="#" onclick="pcAddComment(<?php echo esc_attr($suggestion->id); ?>)">
                                            <?php esc_html_e('Add Comment', 'pc-community-suggestions-7d3f'); ?>
                                        </a>
                                    </span>
                                </div>
                            </td>
                            <td><?php echo esc_html($suggestion->display_name ?: $suggestion->user_login); ?></td>
                            <td><?php echo esc_html($suggestion->upvotes); ?></td>
                            <td><?php echo date_i18n(get_option('date_format'), strtotime($suggestion->created_at)); ?></td>
                            <td>
                                <a href="<?php echo wp_nonce_url(admin_url('admin-post.php?action=pc_delete_suggestion&id=' . $suggestion->id), 'pc_delete_suggestion_' . $suggestion->id); ?>" 
                                   class="button button-small button-link-delete" 
                                   onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete this suggestion?', 'pc-community-suggestions-7d3f'); ?>')">
                                    <?php esc_html_e('Delete', 'pc-community-suggestions-7d3f'); ?>
                                </a>
                            </td>
                        </tr>
                        <tr id="pc-comments-<?php echo esc_attr($suggestion->id); ?>" class="pc-comments-row" style="display: none;">
                            <td colspan="5" class="pc-comments-cell">
                                <div class="pc-comments-container">
                                    <h4><?php esc_html_e('Admin Comments', 'pc-community-suggestions-7d3f'); ?></h4>
                                    <div class="pc-comments-list" id="pc-comments-list-<?php echo esc_attr($suggestion->id); ?>">
                                        <?php
                                        $comments = PC_Community_Suggestions_Database::get_comments($suggestion->id);
                                        if (empty($comments)) {
                                            echo '<p class="pc-no-comments">' . esc_html__('No comments yet.', 'pc-community-suggestions-7d3f') . '</p>';
                                        } else {
                                            foreach ($comments as $comment) {
                                                echo '<div class="pc-comment-item" data-comment-id="' . esc_attr($comment->id) . '">';
                                                echo '<div class="pc-comment-header">';
                                                echo '<strong>' . esc_html($comment->display_name ?: $comment->user_login) . '</strong>';
                                                echo '<span class="pc-comment-date">' . esc_html(date_i18n(get_option('date_format'), strtotime($comment->created_at))) . '</span>';
                                                echo '</div>';
                                                echo '<div class="pc-comment-content">' . wp_kses_post(wpautop($comment->comment)) . '</div>';
                                                echo '<div class="pc-comment-actions">';
                                                echo '<button class="button button-small button-link-delete" onclick="pcDeleteComment(' . esc_attr($comment->id) . ')">' . esc_html__('Delete', 'pc-community-suggestions-7d3f') . '</button>';
                                                echo '</div>';
                                                echo '</div>';
                                            }
                                        }
                                        ?>
                                    </div>
                                    <div class="pc-add-comment">
                                        <h5><?php esc_html_e('Add Comment', 'pc-community-suggestions-7d3f'); ?></h5>
                                        <textarea id="pc-comment-<?php echo esc_attr($suggestion->id); ?>" rows="3" placeholder="<?php esc_attr_e('Enter your comment...', 'pc-community-suggestions-7d3f'); ?>"></textarea>
                                        <button type="button" class="button button-small" onclick="pcSubmitComment(<?php echo esc_attr($suggestion->id); ?>)">
                                            <?php esc_html_e('Add Comment', 'pc-community-suggestions-7d3f'); ?>
                                        </button>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
        <?php
    }
    

    
    public function handle_suggestion_deletion() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have permission to perform this action.', 'pc-community-suggestions-7d3f'));
        }
        
        $suggestion_id = intval($_GET['id'] ?? 0);
        check_admin_referer('pc_delete_suggestion_' . $suggestion_id);
        
        if ($suggestion_id > 0) {
            PC_Community_Suggestions_Database::delete_suggestion($suggestion_id);
            wp_redirect(admin_url('admin.php?page=pc_community_suggestions&deleted=1'));
            exit;
        }
        
        wp_redirect(admin_url('admin.php?page=pc_community_suggestions&error=1'));
        exit;
    }
}