<?php
// Ensure the file is being run within the WordPress environment
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
// Add the admin menu page
function erbwp_add_admin_menu_page() {
    add_menu_page(
        'Post Ratings', // Page title
        'Post Ratings', // Menu title
        'manage_options', // Capability
        'erbwp-post-ratings', // Menu slug
        'erbwp_display_admin_page', // Function to display the page content
        'dashicons-star-filled', // Icon
        6 // Position
    );
}
add_action('admin_menu', 'erbwp_add_admin_menu_page');

// Enqueue admin scripts and styles
function erbwp_enqueue_admin_scripts($hook_suffix) {
    if ($hook_suffix === 'toplevel_page_erbwp-post-ratings') {
        wp_enqueue_style('bootstrap-css', plugins_url('/css/bootstrap.min.css', __FILE__));
        wp_enqueue_style('data-table-bootstrap-css', plugins_url('/css/datatables.min.css', __FILE__));
        wp_enqueue_style('custom-css-admin', plugins_url('/css/erbwp-admin.css', __FILE__));
        wp_enqueue_script('bootstrap-js', plugins_url('/js/bootstrap.bundle.min.js', __FILE__), array('jquery'), '3.4.1', true);
        wp_enqueue_script('data-table', plugins_url('/js/datatable.min.js', __FILE__), array('jquery'), null, true);
        wp_enqueue_script('data-table-pdf', plugins_url('/js/pdfmake.min.js', __FILE__), array('jquery'), null, true);
        wp_enqueue_script('data-table-vfs', plugins_url('/js/vfs-font.js', __FILE__), array('jquery'), null, true);
        wp_enqueue_script('chart-js', plugins_url('/js/chart.js', __FILE__), array('jquery'), null, true);
        wp_enqueue_script('erbwp-rating', plugins_url('/js/erbwp-admin.js', __FILE__), array('jquery'), null, true);
        wp_localize_script('erbwp-rating', 'erbwp_ajax', array(
            'url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('erbwp_ajax_nonce'),
        ));
    }
}
add_action('admin_enqueue_scripts', 'erbwp_enqueue_admin_scripts');

function erbwp_display_admin_page() {
    ?>
    <div class="wrap">
        <div id="overlay" style="display:none;">
            <div class="spinner-border"></div>
            Loading...
        </div>
        <h2>Post Ratings</h2>
        <div class="form-inline">
            <form id="rating-filter-form" class="form-inline">
                <label for="min_rating">Minimum Rating:</label>
                <select id="min_rating" name="min_rating">
                    <option value="All">All star</option>
                    <option value="1">1 star</option>
                    <option value="2">2 stars</option>
                    <option value="3">3 stars</option>
                    <option value="4">4 stars</option>
                    <option value="5">5 stars</option>
                </select>
                <button id="migrate-wp-comment" class="btn btn-primary mb-2">Migrate From WP Comment</button>
            </form>
        </div>
        <div id="post-ratings-container"></div>
        
    </div>
    
    <?php

    
}

function erbwp_filter_posts() {
    check_ajax_referer('erbwp_ajax_nonce', 'nonce');
    if (isset($_POST['min_rating'])) {
        $minRating = sanitize_text_field($_POST['min_rating']);
        $min_rating = $minRating == 'All' ? null : intval($minRating);

        $args = array(
            'post_type' => 'post',
            'posts_per_page' => -1, // Retrieve all posts
        );
        
        if ($min_rating != null) {
            $args['meta_query'] = array(
                array(
                    'key' => 'average_rating',
                    'value' => $min_rating,
                    'compare' => '>='
                )
            );
        }
        $query = new WP_Query($args);
        
        $posts = array();
        if ($query->have_posts()) {
            global $wpdb;
            while ($query->have_posts()) {
                $query->the_post();
                $table_name = $wpdb->prefix . 'reviews';
                $post_id = get_the_ID();
                $ratings = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}reviews WHERE post_id = %d AND parent_id = 0 ORDER BY date DESC", $post_id));
                $stars_count = array();
                foreach ($ratings as $rating) {
                    $key = $rating->rating;
                
                    if (!array_key_exists($key, $stars_count)) {
                        $stars_count[$key] = 0;
                    }
                    $stars_count[$key]++;
                }
                $average_rating = get_post_meta(get_the_ID(), 'average_rating', true);
                if (is_numeric($average_rating)) {
                    $average_rating = round($average_rating, 2);
                } else {
                    $average_rating = 'N/A';
                }
                $posts[] = array(
                    'id' => get_the_ID(),
                    'link' => get_the_permalink(),
                    'title' => get_the_title(),
                    'average_rating' => $average_rating,
                    'ratings' => $stars_count
                );
            
            }
        }
        
        
        wp_send_json_success($posts);
    }
    
    wp_send_json_error('An error occurred while filtering the posts.');
}
add_action('wp_ajax_erbwp_filter_posts', 'erbwp_filter_posts');

function erbwp_migrate_wp_comment() {
    check_ajax_referer('erbwp_ajax_nonce', 'nonce');
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1, // Retrieve all posts
    );
    
    $query = new WP_Query($args);
    if ($query->have_posts()) {
        global $wpdb;
        // delete all comments migrated from wp
        $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}reviews WHERE is_migrated_from_wp = %d", 1));
        $commentIdMap = [];
        while ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();
            // Get comments by post id
            $comments = get_comments(array(
                'post_id' => $post_id,
                'orderby' => 'comment_ID',
                'order' => 'ASC'
            ));
            foreach ($comments as $comment) {
                $table_name = $wpdb->prefix . 'reviews';
                $wpdb->insert($table_name, [
                    'post_id' => $post_id,
                    'user_id' => $comment->user_id,
                    'name' => $comment->comment_author,
                    'email' => $comment->comment_author_email,
                    'comment' => $comment->comment_content,
                    'rating' => 0,
                    'date' => $comment->comment_date,
                    'is_hidden' => false,
                    'parent_id' => $comment->comment_parent, // Store the actual parent_id
                    'is_migrated_from_wp' => true
                ]);
                // Store the mapping of old comment ID to new review ID
                $commentIdMap[$comment->comment_ID] = $wpdb->insert_id;
            }
        }
        
        // Assuming $comments is refreshed with the latest data including parent IDs
        // Update the parent_id in the reviews table based on the mapping
        foreach ($commentIdMap as $oldCommentId => $newReviewId) {
            // Directly use the $commentIdMap to find the new parent review ID
            // First, find the original comment to get its parent ID
            $originalComment = get_comment($oldCommentId);
            if ($originalComment && $originalComment->comment_parent != 0) {
                $oldParentId = $originalComment->comment_parent;
                // Check if this parent ID has a corresponding new review ID
                if (isset($commentIdMap[$oldParentId])) {
                    $newParentReviewId = $commentIdMap[$oldParentId];
                    $wpdb->update(
                        $table_name,
                        ['parent_id' => $newParentReviewId], // New parent_id
                        ['id' => $newReviewId] // Where clause to identify the review to update
                    );
                }
            }
        }
    }
    wp_send_json_success('Comments migrated successfully.');
}
add_action('wp_ajax_erbwp_migrate_wp_comment', 'erbwp_migrate_wp_comment');

function erbwp_approve_comment(){
    check_ajax_referer('erbwp_ajax_nonce', 'nonce');
    $commentId = sanitize_text_field($_POST['commentId']);
    global $wpdb;
    $table_name = $wpdb->prefix . 'reviews';
    $wpdb->update(
        $table_name,
        [
            'is_hidden' => 0,
            'hidden_reason' => null
        ],
        ['id' => $commentId]
    );
    wp_send_json_success('Comment approved successfully.');
}
add_action('wp_ajax_erbwp_approve_comment', 'erbwp_approve_comment');