<?php
/**
 * Volade Activity — User timeline from events
 *
 * @package Volade\SDK
 * @license GPL-2.0-or-later
 */

trait Volade_Activity {

	public function init_activity() {
		add_action( 'wp_ajax_volade_export_data', array( $this, 'ajax_export_data' ) );
	}

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

		global $wpdb;
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT event_type, event_data, plugin_slug, created_at
             FROM {$wpdb->prefix}volade_events
             WHERE user_id = %d
             ORDER BY created_at DESC
             LIMIT %d",
				$user_id,
				$limit
			),
			ARRAY_A
		);

		return array_map( array( $this, 'format_activity_item' ), $rows ?: array() );
	}

	public function format_activity_item( $row ) {
		$data = json_decode( $row['event_data'] ?? '', true );
		if ( ! is_array( $data ) ) {
			$data = array();
		}

		$labels = array(
			'xp_earned'           => __( 'XP gagnés', 'core-version-switcher-by-volade' ),
			'level_up'            => __( 'Niveau supérieur !', 'core-version-switcher-by-volade' ),
			'badge_earned'        => __( 'Badge obtenu', 'core-version-switcher-by-volade' ),
			'referral_converted'  => __( 'Parrainage converti', 'core-version-switcher-by-volade' ),
			'site_activated'      => __( 'Site activé', 'core-version-switcher-by-volade' ),
			'onboarding_complete' => __( 'Onboarding terminé', 'core-version-switcher-by-volade' ),
			'review_submitted'    => __( 'Avis envoyé', 'core-version-switcher-by-volade' ),
			'login'               => __( 'Connexion', 'core-version-switcher-by-volade' ),
			'mission_completed'   => __( 'Mission validée', 'core-version-switcher-by-volade' ),
			'plugin_active'       => __( 'Plugin activé', 'core-version-switcher-by-volade' ),
			'register'            => __( 'Inscription', 'core-version-switcher-by-volade' ),
		);

		$type   = $row['event_type'];
		$label  = $labels[ $type ] ?? ucfirst( str_replace( '_', ' ', $type ) );
		$detail = '';

		if ( $type === 'xp_earned' && isset( $data['amount'] ) ) {
			$detail = '+' . (int) $data['amount'] . ' XP';
		} elseif ( $type === 'level_up' && isset( $data['new_level'] ) ) {
			/* translators: %d: user level number. */
			$detail = sprintf( __( 'Niveau %d', 'core-version-switcher-by-volade' ), (int) $data['new_level'] );
		} elseif ( $type === 'badge_earned' && isset( $data['badge_key'] ) ) {
			$detail = $this->get_badge_name( $data['badge_key'] );
		} elseif ( $type === 'mission_completed' && isset( $data['title'] ) ) {
			$detail = $data['title'];
			if ( isset( $data['xp'] ) ) {
				$detail .= ' (+' . (int) $data['xp'] . ' XP)';
			}
		} elseif ( $type === 'site_activated' && isset( $data['site_url'] ) ) {
			$detail = $data['site_url'];
		} elseif ( $type === 'plugin_active' && isset( $data['plugin'] ) ) {
			$detail = $data['plugin'];
		}

		$timestamp = strtotime( $row['created_at'] );

		return array(
			'type'         => $type,
			'label'        => $label,
			'detail'       => $detail,
			'plugin'       => $row['plugin_slug'] ?? '',
			'date'         => $row['created_at'],
			'date_h'       => mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $row['created_at'] ),
			'relative'     => $this->get_activity_relative_time( $timestamp ),
			'day_key'      => wp_date( 'Y-m-d', $timestamp ),
			'icon'         => $this->get_activity_icon( $type ),
			'tone'         => $this->get_activity_tone( $type ),
			'filter_group' => $this->get_activity_filter_group( $type ),
		);
	}

	public function get_activity_icon( $type ) {
		$icons = array(
			'xp_earned'           => '⭐',
			'level_up'            => '🚀',
			'badge_earned'        => '🏆',
			'referral_converted'  => '🤝',
			'site_activated'      => '🌐',
			'onboarding_complete' => '🎓',
			'review_submitted'    => '💬',
			'login'               => '🔐',
			'register'            => '✨',
			'mission_completed'   => '🎯',
			'plugin_active'       => '📦',
		);
		return $icons[ $type ] ?? '📌';
	}

	public function get_activity_tone( $type ) {
		$tones = array(
			'xp_earned'          => 'xp',
			'level_up'           => 'level',
			'badge_earned'       => 'badge',
			'mission_completed'  => 'mission',
			'plugin_active'      => 'plugin',
			'referral_converted' => 'referral',
		);
		return $tones[ $type ] ?? 'default';
	}

	public function get_activity_filter_group( $type ) {
		if ( in_array( $type, array( 'xp_earned', 'level_up' ), true ) ) {
			return 'xp';
		}
		if ( in_array( $type, array( 'mission_completed' ), true ) ) {
			return 'missions';
		}
		if ( in_array( $type, array( 'badge_earned' ), true ) ) {
			return 'badges';
		}
		if ( in_array( $type, array( 'plugin_active', 'site_activated' ), true ) ) {
			return 'plugins';
		}
		return 'other';
	}

	public function get_activity_relative_time( $timestamp ) {
		if ( ! $timestamp ) {
			return '';
		}
		$diff = human_time_diff( $timestamp, current_time( 'timestamp' ) );
		/* translators: %s: human-readable time difference, e.g. "2 hours". */
		return sprintf( __( 'il y a %s', 'core-version-switcher-by-volade' ), $diff );
	}

	/**
	 * @return array<string, mixed>
	 */
	public function get_activity_stats( $user_id = 0 ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return array();
			}
			$user_id = $user['id'];
		}

		global $wpdb;
		$total = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->prefix}volade_events WHERE user_id = %d",
				$user_id
			)
		);

		$week_start = gmdate( 'Y-m-d H:i:s', strtotime( '-7 days' ) );
		$week_rows  = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT event_type, event_data FROM {$wpdb->prefix}volade_events
                 WHERE user_id = %d AND created_at >= %s",
				$user_id,
				$week_start
			),
			ARRAY_A
		);
		$week_xp    = 0;
		foreach ( $week_rows ?: array() as $row ) {
			if ( 'xp_earned' !== ( $row['event_type'] ?? '' ) ) {
				continue;
			}
			$data     = json_decode( $row['event_data'] ?? '', true );
			$week_xp += (int) ( is_array( $data ) ? ( $data['amount'] ?? 0 ) : 0 );
		}

		$missions = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->prefix}volade_events
                 WHERE user_id = %d AND event_type = 'mission_completed'",
				$user_id
			)
		);

		$plugins = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(DISTINCT plugin_slug) FROM {$wpdb->prefix}volade_events
                 WHERE user_id = %d AND event_type = 'plugin_active' AND plugin_slug != ''",
				$user_id
			)
		);

		$last = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT created_at FROM {$wpdb->prefix}volade_events
                 WHERE user_id = %d ORDER BY created_at DESC LIMIT 1",
				$user_id
			)
		);

		return array(
			'total_events'  => $total,
			'week_xp'       => $week_xp,
			'missions'      => $missions,
			'plugins'       => $plugins,
			'last_activity' => $last ? $this->get_activity_relative_time( strtotime( $last ) ) : '',
		);
	}

	/**
	 * @param array<int, array<string, mixed>> $events
	 * @return array<int, array{label:string,events:array}>
	 */
	public function group_activity_by_day( $events ) {
		$groups = array();
		$order  = array();

		foreach ( $events as $event ) {
			$day_key = $event['day_key'] ?? wp_date( 'Y-m-d' );
			if ( ! isset( $groups[ $day_key ] ) ) {
				$groups[ $day_key ] = array(
					'label'  => $this->get_activity_day_label( $day_key ),
					'events' => array(),
				);
				$order[]            = $day_key;
			}
			$groups[ $day_key ]['events'][] = $event;
		}

		$out = array();
		foreach ( $order as $key ) {
			$out[] = $groups[ $key ];
		}
		return $out;
	}

	public function get_activity_day_label( $day_key ) {
		$today     = wp_date( 'Y-m-d' );
		$yesterday = wp_date( 'Y-m-d', strtotime( '-1 day' ) );

		if ( $day_key === $today ) {
			return __( 'Aujourd\'hui', 'core-version-switcher-by-volade' );
		}
		if ( $day_key === $yesterday ) {
			return __( 'Hier', 'core-version-switcher-by-volade' );
		}

		$ts = strtotime( $day_key );
		if ( $ts && $ts >= strtotime( '-7 days' ) ) {
			return wp_date( 'l j F', $ts );
		}

		return wp_date( get_option( 'date_format' ), $ts );
	}

	public function export_user_data( $user_id = 0 ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return new WP_Error( 'not_logged_in', __( 'Non authentifié.', 'core-version-switcher-by-volade' ) );
			}
			$user_id = $user['id'];
		}

		global $wpdb;
		$user   = $this->get_user_data( $user_id );
		$events = $this->get_user_events( $user_id, 500 );
		$sites  = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT site_url, plugin_slug, wp_version, activated_at FROM {$wpdb->prefix}volade_sites WHERE user_id = %d",
				$user_id
			),
			ARRAY_A
		);

		return array(
			'exported_at' => current_time( 'mysql' ),
			'user'        => array(
				'pseudo'        => $user['pseudo'] ?? '',
				'email'         => $user['email'] ?? '',
				'xp'            => $user['xp'] ?? 0,
				'level'         => $user['level'] ?? 1,
				'referral_code' => $user['referral_code'] ?? '',
				'created_at'    => $user['created_at'] ?? '',
			),
			'badges'      => $user['badges'] ?? array(),
			'events'      => $events,
			'sites'       => $sites,
			'reviews'     => $this->get_user_reviews( $user_id ),
		);
	}

	public function ajax_export_data() {
		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();
		$data = $this->export_user_data( $user['id'] );
		wp_send_json_success( $data );
	}
}
