<?php

namespace MovieEngine\Frontend;

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

class Reviews {
    public function __construct() {
        add_action('comment_form_logged_in_after', [$this, 'add_rating_field']);
        add_filter('preprocess_comment', [$this, 'verify_rating_data']);
        add_action('comment_post', [$this, 'save_comment_rating']);
        add_filter('comment_text', [$this, 'display_rating_in_comment'], 10, 2);
    }


    public function add_rating_field() {
        if (is_user_logged_in()) {
            $post_id = get_the_ID();
            $post_type = get_post_type($post_id);

            if (!in_array($post_type, ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
                return;
            }

            $user_id = get_current_user_id();

            $args = [
                'user_id' => $user_id,
                'post_id' => $post_id,
                'count' => true,
                'parent' => 0
            ];
            $comment_count = get_comments($args);

            if ($comment_count > 0) {
                echo '<p class="movie-engine-already-rated-msg">' . esc_html__('You have already reviewed this title. You can edit your review below.', 'cine-movie-engine') . '</p>';
                return;
            }
        }
?>
        <div class="movie-engine-rating-input">
            <label><?php esc_html_e('Your Rating', 'cine-movie-engine'); ?></label>
            <div class="movie-engine-star-rating-select">
                <?php for ($i = 10; $i >= 1; $i--): ?>
                    <input type="radio" id="rating-<?php echo esc_attr($i); ?>" name="movie_engine_rating" value="<?php echo esc_attr($i); ?>" required>
                    <label for="rating-<?php echo esc_attr($i); ?>" title="<?php echo esc_attr($i); ?> stars"></label>
                <?php endfor; ?>
            </div>
        </div>
<?php
    }


    public function verify_rating_data($commentdata) {
        if (!empty($commentdata['comment_parent'])) {
            return $commentdata;
        }

        if (is_user_logged_in()) {
            $post_id = $commentdata['comment_post_ID'];
            $post_type = get_post_type($post_id);

            if (!in_array($post_type, ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
                return $commentdata;
            }

            $user_id = get_current_user_id();

            $args = [
                'user_id' => $user_id,
                'post_id' => $post_id,
                'count' => true,
                'parent' => 0
            ];

            if (get_comments($args) > 0) {
                wp_die(esc_html__('You have already rated this title.', 'cine-movie-engine'));
            }
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (!isset($_POST['movie_engine_rating']) || !is_numeric($_POST['movie_engine_rating'])) {
        }

        return $commentdata;
    }


    public function save_comment_rating($comment_id) {
        $comment = get_comment($comment_id);
        if (!$comment) return;

        $post_type = get_post_type($comment->comment_post_ID);
        if (!in_array($post_type, ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (isset($_POST['movie_engine_rating'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $rating = intval(wp_unslash($_POST['movie_engine_rating']));
            update_comment_meta($comment_id, 'movie_engine_rating', $rating);

            $comment = get_comment($comment_id);
            if ($comment) {
                $this->update_post_average_rating($comment->comment_post_ID);
            }
        }
    }


    public function update_post_average_rating($post_id) {
        $args = [
            'post_id' => $post_id,
            'status' => 'approve',
            // phpcs:ignore WordPress.DB.SlowDBQuery
            'meta_key' => 'movie_engine_rating',
        ];
        $comments = get_comments($args);

        if ($comments) {
            $total = 0;
            $count = 0;
            foreach ($comments as $comment) {
                $rating = get_comment_meta($comment->comment_ID, 'movie_engine_rating', true);
                if ($rating) {
                    $total += intval($rating);
                    $count++;
                }
            }
            if ($count > 0) {
                $average = round($total / $count, 1);
                update_post_meta($post_id, '_movie_engine_user_rating', $average);
                update_post_meta($post_id, '_movie_engine_user_rating_count', $count);
            } else {
                update_post_meta($post_id, '_movie_engine_user_rating', 0);
                update_post_meta($post_id, '_movie_engine_user_rating_count', 0);
            }
        }
    }


    public static function can_edit_comment($comment) {
        $can_edit = false;
        return apply_filters('movie_engine_can_edit_review', $can_edit, $comment);
    }

    public function display_rating_in_comment($text, $comment = null) {
        if (!$comment) {
            $comment = get_comment();
        }

        if (!$comment || is_admin()) {
            return $text;
        }

        $post_type = get_post_type($comment->comment_post_ID);
        if (!in_array($post_type, ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
            return $text;
        }

        if (isset($GLOBALS['movie_engine_rating_rendered_' . $comment->comment_ID])) {
            return $text;
        }

        $rating_html = self::render_rating_html($comment);
        if ($rating_html) {
            return $rating_html . $text;
        }

        return $text;
    }

    public static function render_rating_html($comment) {
        $rating = get_comment_meta($comment->comment_ID, 'movie_engine_rating', true);
        if (!$rating) return '';

        $stars = '';
        for ($i = 1; $i <= 10; $i++) {
            $class = $i <= $rating ? 'fa-solid fa-star' : 'fa-regular fa-star';
            $stars .= '<i class="' . esc_attr($class) . '"></i>';
        }

        $can_edit = self::can_edit_comment($comment);

        $rating_html = '<div class="movie-engine-user-rating-display me-user-rating-display">';
        $rating_html .= '<div class="me-stars">' . $stars . '</div>';

        if ($can_edit) {
            $rating_html .= '<div class="movie-engine-review-actions">';
            $rating_html .= '<button class="movie-engine-btn-edit-review me-btn-edit" data-id="' . $comment->comment_ID . '" data-content="' . esc_attr($comment->comment_content) . '" data-rating="' . $rating . '"><i class="fas fa-edit"></i> ' . esc_html__('Edit', 'cine-movie-engine') . '</button>';
            $rating_html .= '</div>';
        }

        $rating_html .= '</div>';
        $GLOBALS['movie_engine_rating_rendered_' . $comment->comment_ID] = true;

        return $rating_html;
    }
}
