<?php

namespace MovieEngine\Frontend\Users;

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

class UserInteractions {

    public function __construct() {
        add_action('wp_ajax_movie_engine_submit_rating', [$this, 'ajax_submit_rating']);
        add_shortcode('movie_engine_user_rating', [$this, 'render_rating_ui']);
    }

    public function ajax_submit_rating() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('You must be logged in to rate.', 'cine-movie-engine')]);
        }

        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
        $rating = isset($_POST['rating']) ? floatval($_POST['rating']) : 0;

        if (!$post_id || $rating < 0 || $rating > 10) {
            wp_send_json_error(['message' => esc_html__('Invalid data.', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        $this->save_user_rating($user_id, $post_id, $rating);

        wp_send_json_success([
            'message' => esc_html__('Thanks for rating!', 'cine-movie-engine'),
            'new_avg' => $this->get_average_rating($post_id)
        ]);
    }

    private function save_user_rating($user_id, $post_id, $rating) {
        update_user_meta($user_id, '_movie_engine_rating_' . $post_id, $rating);

        $ratings = get_post_meta($post_id, '_movie_engine_user_ratings_list', true);
        if (!is_array($ratings)) {
            $ratings = [];
        }

        $ratings[$user_id] = $rating;
        update_post_meta($post_id, '_movie_engine_user_ratings_list', $ratings);

        $total = array_sum($ratings);
        $count = count($ratings);
        $average = $count > 0 ? round($total / $count, 1) : 0;

        update_post_meta($post_id, '_movie_engine_user_rating_avg', $average);
        update_post_meta($post_id, '_movie_engine_user_rating', $average); // Sync with other parts of the plugin
        update_post_meta($post_id, '_movie_engine_user_rating_count', $count);
    }

    public function get_average_rating($post_id) {
        return get_post_meta($post_id, '_movie_engine_user_rating_avg', true) ?: 0;
    }

    public function render_rating_ui($atts) {
        $post_id = get_the_ID();
        $user_id = get_current_user_id();
        $user_rating = $user_id ? get_user_meta($user_id, '_movie_engine_rating_' . $post_id, true) : 0;
        $avg_rating = $this->get_average_rating($post_id);

        ob_start();
?>
        <div class="movie-engine-user-rating-box" data-post-id="<?php echo esc_attr($post_id); ?>">
            <div class="movie-engine-rating-stars">
                <?php for ($i = 1; $i <= 10; $i++): ?>
                    <span class="dashicons dashicons-star-filled movie-engine-star <?php echo esc_attr($i <= $user_rating ? 'active' : ''); ?>" data-value="<?php echo esc_attr($i); ?>"></span>
                <?php endfor; ?>
            </div>
            <div class="movie-engine-rating-stats">
                <span class="movie-engine-avg-val"><?php echo esc_attr($avg_rating ?: '0.0'); ?></span>
                <span class="movie-engine-rating-text"><?php echo esc_attr($user_id && $user_rating ? esc_html__('Your rating', 'cine-movie-engine') : esc_html__('User score', 'cine-movie-engine')); ?></span>
            </div>
        </div>

<?php
        return ob_get_clean();
    }
}
