<?php
/**
 * My Account Dashboard — Rewards widget.
 *
 * Renders the current user's points balance and badge on the
 * WooCommerce My Account → Dashboard tab.
 *
 * @package Ugcify\Integrations\WooCommerce
 */

namespace Ugcify\Integrations\WooCommerce;

use Ugcify\Admin\API\RewardSettingsAPI;
use Ugcify\Points\PointsManager;
use Ugcify\Points\TierManager;
use Ugcify\Rewards\BadgeResolver;

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

/**
 * Class MyAccountDashboard
 */
class MyAccountDashboard {

	/**
	 * Boot the integration.
	 */
	public function __construct() {
		add_action( 'woocommerce_account_dashboard', array( $this, 'render' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );
	}

	/**
	 * Render the rewards widget on the dashboard tab.
	 *
	 * @return void
	 */
	public function render(): void {
		$user_id = get_current_user_id();

		if ( 0 === $user_id ) {
			return;
		}

		// Ensure dependencies are loaded — they may not be available on frontend pages
		// since the REST API router loads them lazily on rest_api_init.
		require_once UGCIFY_PATH . 'includes/Admin/API/RewardSettingsAPI.php';
		require_once UGCIFY_PATH . 'includes/Database/PointsRepository.php';
		require_once UGCIFY_PATH . 'includes/Points/PointsManager.php';
		require_once UGCIFY_PATH . 'includes/Points/TierManager.php';
		require_once UGCIFY_PATH . 'includes/Rewards/BadgeResolver.php';

		$settings = RewardSettingsAPI::get_reward_settings();

		$manager = new PointsManager();
		$manager->recalculate_user_summary( $user_id );
		$summary = $manager->get_user_summary( $user_id );
		$summary = CheckoutRedemption::apply_pending_redemption_to_summary( $summary, $user_id );
		$ledger  = $manager->get_user_transactions( $user_id, 5 );

		// Recalculate tier fresh from current settings + actual data so it is
		// never stale when admin changes thresholds after points were credited.
		$summary['current_tier'] = ! empty( $settings['tiers_enabled'] )
			? TierManager::calculate_tier( $user_id, $settings )
			: 'guest';
		$badge = BadgeResolver::resolve_display_badge( $user_id, $summary, $settings );

		$this->render_html( $summary, $badge, $ledger );
	}

	/**
	 * Output the HTML for the rewards widget.
	 *
	 * @param array      $summary Reward summary: total_earned, total_used, available_balance.
	 * @param array|null $badge   Resolved badge or null.
	 * @param array      $ledger  Recent transaction rows.
	 */
	private function render_html( array $summary, ?array $badge, array $ledger = array() ): void {
		$total_earned      = $summary['total_earned'] ?? 0;
		$total_used        = $summary['total_used'] ?? 0;
		$available_balance = $summary['available_balance'] ?? 0;
		?>
		<div class="ugcify-rewards-dashboard">
			<h3 class="ugcify-rewards-dashboard__title">
				<?php esc_html_e( 'My Rewards', 'ugcify' ); ?>
			</h3>

			<div class="ugcify-rewards-dashboard__cards">
				<?php // ---- Available Balance Card ---- ?>
				<div class="ugcify-rewards-dashboard__card">
					<span class="ugcify-rewards-dashboard__card-label">
						<?php esc_html_e( 'Available Points', 'ugcify' ); ?>
					</span>
					<span class="ugcify-rewards-dashboard__card-value">
						<?php echo esc_html( number_format_i18n( $available_balance ) ); ?>
					</span>
				</div>

				<?php // ---- Total Earned Card ---- ?>
				<div class="ugcify-rewards-dashboard__card">
					<span class="ugcify-rewards-dashboard__card-label">
						<?php esc_html_e( 'Total Earned', 'ugcify' ); ?>
					</span>
					<span class="ugcify-rewards-dashboard__card-value">
						<?php echo esc_html( number_format_i18n( $total_earned ) ); ?>
					</span>
				</div>

				<?php // ---- Used Points Card ---- ?>
				<div class="ugcify-rewards-dashboard__card">
					<span class="ugcify-rewards-dashboard__card-label">
						<?php esc_html_e( 'Points Used', 'ugcify' ); ?>
					</span>
					<span class="ugcify-rewards-dashboard__card-value">
						<?php echo esc_html( number_format_i18n( $total_used ) ); ?>
					</span>
				</div>

				<?php // ---- Badge Card ---- ?>
				<div class="ugcify-rewards-dashboard__card">
					<span class="ugcify-rewards-dashboard__card-label">
						<?php esc_html_e( 'Current Badge', 'ugcify' ); ?>
					</span>
					<?php if ( $badge ) : ?>
						<div class="ugcify-rewards-dashboard__badge">
							<?php if ( ! empty( $badge['icon_url'] ) ) : ?>
								<img
									class="ugcify-rewards-dashboard__badge-icon"
									src="<?php echo esc_url( $badge['icon_url'] ); ?>"
									alt="<?php echo esc_attr( $badge['name'] ); ?>"
								/>
							<?php endif; ?>
							<span class="ugcify-rewards-dashboard__badge-name">
								<?php echo esc_html( $badge['name'] ); ?>
							</span>
						</div>
					<?php else : ?>
						<span class="ugcify-rewards-dashboard__card-value ugcify-rewards-dashboard__card-value--muted">
							<?php esc_html_e( 'No badge yet', 'ugcify' ); ?>
						</span>
					<?php endif; ?>
				</div>
			</div>

			<?php if ( $badge && ! empty( $badge['discount_type'] ) ) : ?>
				<p class="ugcify-rewards-dashboard__discount-note">
					<?php
					if ( 'discount' === $badge['discount_type'] ) {
						printf(
							/* translators: 1: discount percentage, 2: badge name */
							esc_html__( 'You enjoy a %1$s%% discount with your %2$s badge!', 'ugcify' ),
							esc_html( $badge['amount'] ),
							esc_html( $badge['name'] )
						);
					} else {
						$currency = function_exists( 'get_woocommerce_currency_symbol' ) ? (string) call_user_func( 'get_woocommerce_currency_symbol' ) : '$';
						printf(
							/* translators: 1: currency symbol, 2: flat amount, 3: conversion points, 4: badge name */
							esc_html__( 'You earn %1$s%2$s per %3$s conversion points with your %4$s badge!', 'ugcify' ),
							esc_html( $currency ),
							esc_html( $badge['amount'] ),
							esc_html( $badge['conversion_points'] ?? 1 ),
							esc_html( $badge['name'] )
						);
					}
					?>
				</p>
			<?php endif; ?>

			<?php if ( ! empty( $ledger ) ) : ?>
				<div class="ugcify-rewards-dashboard__activity">
					<h4 class="ugcify-rewards-dashboard__activity-title">
						<?php esc_html_e( 'Recent Activity', 'ugcify' ); ?>
					</h4>
					<table class="ugcify-rewards-dashboard__table">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Date', 'ugcify' ); ?></th>
								<th><?php esc_html_e( 'Description', 'ugcify' ); ?></th>
								<th><?php esc_html_e( 'Points', 'ugcify' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $ledger as $tx ) : ?>
								<tr>
									<td><?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $tx->created_at ) ) ); ?></td>
									<td><?php echo esc_html( $this->format_transaction_description( $tx ) ); ?></td>
									<td class="<?php echo (int) $tx->points >= 0 ? 'ugcify-rewards-dashboard__points--positive' : 'ugcify-rewards-dashboard__points--negative'; ?>">
										<?php echo (int) $tx->points >= 0 ? '+' : ''; ?><?php echo esc_html( number_format_i18n( (int) $tx->points ) ); ?>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Format point ledger descriptions for display.
	 *
	 * @param object $transaction Transaction row.
	 * @return string
	 */
	private function format_transaction_description( $transaction ): string {
		$description = (string) ( $transaction->description ?? '' );
		$action      = (string) ( $transaction->action ?? '' );

		if ( 0 === strpos( $description, 'social_share_click:' ) || ( '' === $description && 'pts_share_click' === $action ) ) {
			return __( 'Social share link clicked', 'ugcify' );
		}

		if ( 0 === strpos( $description, 'social_share_reviewer_conversion:' ) ) {
			return __( 'Social share purchase completed for your review', 'ugcify' );
		}

		if ( 0 === strpos( $description, 'social_share_conversion:' ) || ( '' === $description && 'pts_share_conversion' === $action ) ) {
			return __( 'Social share purchase completed', 'ugcify' );
		}

		return $description;
	}

	/**
	 * Enqueue scoped inline styles for the rewards dashboard.
	 */
	public function enqueue_styles(): void {
		if ( ! function_exists( 'is_account_page' ) || ! is_account_page() ) {
			return;
		}
		$css = '
			.ugcify-rewards-dashboard{margin:24px 0 32px;padding:24px;border:1px solid #e0e0e0;border-radius:8px;background:#fff}
			.ugcify-rewards-dashboard__title{margin:0 0 16px;font-size:18px;font-weight:600}
			.ugcify-rewards-dashboard__cards{display:flex;gap:16px;flex-wrap:wrap}
			.ugcify-rewards-dashboard__card{flex:1 1 180px;display:flex;flex-direction:column;gap:8px;padding:16px;border:1px solid #eee;border-radius:6px;background:#fafafa}
			.ugcify-rewards-dashboard__card-label{font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:#666}
			.ugcify-rewards-dashboard__card-value{font-size:28px;font-weight:700;color:#1a1a1a;line-height:1.2}
			.ugcify-rewards-dashboard__card-value--muted{font-size:16px;font-weight:400;color:#999}
			.ugcify-rewards-dashboard__badge{display:flex;align-items:center;gap:10px}
			.ugcify-rewards-dashboard__badge-icon{width:36px;height:36px;object-fit:contain;border-radius:4px}
			.ugcify-rewards-dashboard__badge-name{font-size:20px;font-weight:600;color:#1a1a1a}
			.ugcify-rewards-dashboard__discount-note{margin:16px 0 0;padding:10px 14px;background:#f0f7f0;border-left:3px solid #4caf50;border-radius:4px;font-size:14px;color:#333}
			.ugcify-rewards-dashboard__activity{margin-top:20px}
			.ugcify-rewards-dashboard__activity-title{margin:0 0 10px;font-size:15px;font-weight:600}
			.ugcify-rewards-dashboard__table{width:100%;border-collapse:collapse;font-size:13px}
			.ugcify-rewards-dashboard__table th,.ugcify-rewards-dashboard__table td{padding:8px 10px;text-align:left;border-bottom:1px solid #eee}
			.ugcify-rewards-dashboard__table th{font-weight:600;color:#666;font-size:11px;text-transform:uppercase;letter-spacing:.3px}
			.ugcify-rewards-dashboard__points--positive{color:#00a32a;font-weight:600}
			.ugcify-rewards-dashboard__points--negative{color:#d63638;font-weight:600}
		';
		wp_register_style( 'ugcify-rewards-dashboard', false ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters
		wp_enqueue_style( 'ugcify-rewards-dashboard' );
		wp_add_inline_style( 'ugcify-rewards-dashboard', $css );
	}
}
