<?php
/**
 * Volade Feedback — Plugin reviews & ratings
 *
 * @package Volade\SDK
 * @license GPL-2.0-or-later
 */

trait Volade_Feedback {

	public function init_feedback() {
		add_action( 'wp_ajax_volade_submit_review', array( $this, 'ajax_submit_review' ) );
	}

	public function submit_review( $user_id, $plugin_slug, $rating, $content = '' ) {
		global $wpdb;

		if ( $rating < 1 || $rating > 5 ) {
			return new WP_Error( 'invalid_rating', __( 'La note doit être entre 1 et 5.', 'core-version-switcher-by-volade' ) );
		}

		$plugin_slug = sanitize_key( $plugin_slug );
		if ( empty( $plugin_slug ) ) {
			return new WP_Error( 'invalid_plugin', __( 'Plugin invalide.', 'core-version-switcher-by-volade' ) );
		}

		$existing = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM {$wpdb->prefix}volade_reviews WHERE user_id = %d AND plugin_slug = %s LIMIT 1",
				$user_id,
				$plugin_slug
			)
		);

		$row = array(
			'user_id'     => $user_id,
			'plugin_slug' => $plugin_slug,
			'rating'      => (int) $rating,
			'content'     => sanitize_textarea_field( $content ),
			'updated_at'  => current_time( 'mysql' ),
		);

		if ( $existing ) {
			$wpdb->update( "{$wpdb->prefix}volade_reviews", $row, array( 'id' => $existing ) );
			$review_id = (int) $existing;
		} else {
			$row['created_at'] = current_time( 'mysql' );
			$wpdb->insert( "{$wpdb->prefix}volade_reviews", $row );
			$review_id = (int) $wpdb->insert_id;
			$this->add_xp( $user_id, 'review' );
		}

		$this->log_event(
			$user_id,
			'review_submitted',
			array(
				'plugin_slug' => $plugin_slug,
				'rating'      => $rating,
			),
			$plugin_slug
		);

		$api = Volade_API::get_instance();
		if ( $api ) {
			$api->post(
				'/reviews/submit',
				array(
					'user_id'     => $user_id,
					'plugin_slug' => $plugin_slug,
					'rating'      => $rating,
					'content'     => $content,
				)
			);
		}

		return $review_id;
	}

	public function get_user_reviews( $user_id = 0 ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return array();
			}
			$user_id = $user['id'];
		}

		global $wpdb;
		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT plugin_slug, rating, content, created_at, updated_at
             FROM {$wpdb->prefix}volade_reviews WHERE user_id = %d ORDER BY updated_at DESC",
				$user_id
			),
			ARRAY_A
		) ?: array();
	}

	public function get_plugin_rating( $plugin_slug ) {
		global $wpdb;
		$stats = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT AVG(rating) as avg_rating, COUNT(*) as count
             FROM {$wpdb->prefix}volade_reviews WHERE plugin_slug = %s",
				$plugin_slug
			)
		);
		return array(
			'average' => $stats && $stats->count ? round( (float) $stats->avg_rating, 1 ) : 0,
			'count'   => $stats ? (int) $stats->count : 0,
		);
	}

	public function ajax_submit_review() {
		check_ajax_referer( 'volade_nonce', 'nonce' );
		if ( ! $this->is_user_logged_in() ) {
			wp_send_json_error( __( 'Non authentifié.', 'core-version-switcher-by-volade' ) );
		}
		$user   = $this->get_current_user();
		$result = $this->submit_review(
			$user['id'],
			sanitize_key( $_POST['plugin_slug'] ?? '' ),
			(int) ( $_POST['rating'] ?? 0 ),
			sanitize_textarea_field( $_POST['content'] ?? '' )
		);
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}
		wp_send_json_success( array( 'review_id' => $result ) );
	}
}
