<?php
/**
 * WooCommerce My Account creator invitations endpoint.
 *
 * @package Ugcify\Integrations\WooCommerce
 */

namespace Ugcify\Integrations\WooCommerce;

use Ugcify\Database\UserRepository;
use Ugcify\Influencer\InvitationService;
use Ugcify\Influencer\Settings;

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

/**
 * Class MyAccountInfluencerInvitations
 */
class MyAccountInfluencerInvitations {
	/**
	 * WooCommerce endpoint slug.
	 */
	private const ENDPOINT = 'creator-invitations';

	/**
	 * Creator user repository.
	 *
	 * @var UserRepository
	 */
	private $user_repository;

	/**
	 * Invitation service.
	 *
	 * @var InvitationService
	 */
	private $invitation_service;

	/**
	 * Constructor.
	 *
	 * @param UserRepository|null   $user_repository   Optional user repository.
	 * @param InvitationService|null $invitation_service Optional invitation service.
	 */
	public function __construct( ?UserRepository $user_repository = null, ?InvitationService $invitation_service = null ) {
		$this->user_repository   = $user_repository ?: new UserRepository();
		$this->invitation_service = $invitation_service ?: new InvitationService();

		add_action( 'init', array( $this, 'register_endpoint' ) );
		add_filter( 'woocommerce_account_menu_items', array( $this, 'add_menu_item' ) );
		add_action( 'woocommerce_account_' . self::ENDPOINT . '_endpoint', array( $this, 'render' ) );
	}

	/**
	 * Register the WooCommerce account endpoint.
	 *
	 * @return void
	 */
	public function register_endpoint(): void {
		add_rewrite_endpoint( self::ENDPOINT, EP_ROOT | EP_PAGES );
	}

	/**
	 * Inject the creator invitations menu item after Dashboard.
	 *
	 * @param array<string,string> $items Existing account menu items.
	 * @return array<string,string>
	 */
	public function add_menu_item( array $items ): array {
		if ( ! $this->should_show_menu_item() ) {
			return $items;
		}

		$updated = array();
		foreach ( $items as $key => $label ) {
			$updated[ $key ] = $label;

			if ( 'dashboard' === $key ) {
				$updated[ self::ENDPOINT ] = __( 'Creator Invitations', 'ugcify' );
			}
		}

		if ( ! isset( $updated[ self::ENDPOINT ] ) ) {
			$updated[ self::ENDPOINT ] = __( 'Creator Invitations', 'ugcify' );
		}

		return $updated;
	}

	/**
	 * Render the creator invitations endpoint.
	 *
	 * @return void
	 */
	public function render(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id     = get_current_user_id();
		$invitations = $this->invitation_service->get_invitations_for_user( $user_id, array(), 50 );

		$this->render_styles();

		if ( ! Settings::is_enabled() ) {
			$this->render_notice(
				__( 'The creator portal is currently disabled. Invitation tasks will appear here again once the portal is enabled.', 'ugcify' )
			);
			return;
		}

		$pending_count  = count(
			array_filter(
				$invitations,
				static function ( array $invitation ) {
					return 'pending' === ( $invitation['status'] ?? '' );
				}
			)
		);
		$accepted_count = count(
			array_filter(
				$invitations,
				static function ( array $invitation ) {
					return 'accepted' === ( $invitation['status'] ?? '' );
				}
			)
		);
		$scoped_count   = count(
			array_filter(
				$invitations,
				static function ( array $invitation ) {
					return ! empty( $invitation['has_product_scope'] );
				}
			)
		);
		?>
		<div class="ugcify-my-account-invitations">
			<div class="ugcify-my-account-invitations__header">
				<div>
					<h3 class="ugcify-my-account-invitations__title"><?php esc_html_e( 'Creator Invitations', 'ugcify' ); ?></h3>
					<p class="ugcify-my-account-invitations__description"><?php esc_html_e( 'Track every creator request tied to your account and jump directly into the upload workspace for the invited products.', 'ugcify' ); ?></p>
				</div>
				<div class="ugcify-my-account-invitations__summary">
					<div class="ugcify-my-account-invitations__summary-card">
						<span><?php esc_html_e( 'Pending', 'ugcify' ); ?></span>
						<strong><?php echo esc_html( number_format_i18n( $pending_count ) ); ?></strong>
					</div>
					<div class="ugcify-my-account-invitations__summary-card">
						<span><?php esc_html_e( 'Accepted', 'ugcify' ); ?></span>
						<strong><?php echo esc_html( number_format_i18n( $accepted_count ) ); ?></strong>
					</div>
					<div class="ugcify-my-account-invitations__summary-card">
						<span><?php esc_html_e( 'Product-scoped', 'ugcify' ); ?></span>
						<strong><?php echo esc_html( number_format_i18n( $scoped_count ) ); ?></strong>
					</div>
				</div>
			</div>

			<?php if ( empty( $invitations ) ) : ?>
				<div class="ugcify-my-account-invitations__empty">
					<p><?php esc_html_e( 'There are no creator invitations assigned to this account yet.', 'ugcify' ); ?></p>
				</div>
			<?php else : ?>
				<div class="ugcify-my-account-invitations__table-wrapper">
					<table class="ugcify-my-account-invitations__table shop_table shop_table_responsive">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Status', 'ugcify' ); ?></th>
								<th><?php esc_html_e( 'Expires', 'ugcify' ); ?></th>
								<th><?php esc_html_e( 'Action', 'ugcify' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $invitations as $invitation ) : ?>
								<?php
								$status       = isset( $invitation['status'] ) ? (string) $invitation['status'] : 'pending';
								$status_label = $this->format_status_label( $status );
								$action_url   = $this->build_action_url( $invitation );
								?>
								<tr>
									<td data-title="<?php esc_attr_e( 'Status', 'ugcify' ); ?>">
										<span class="ugcify-my-account-invitations__pill is-<?php echo esc_attr( sanitize_html_class( $status ) ); ?>"><?php echo esc_html( $status_label ); ?></span>
									</td>
									<td data-title="<?php esc_attr_e( 'Expires', 'ugcify' ); ?>">
										<?php echo esc_html( wp_date( get_option( 'date_format', 'M j, Y' ), strtotime( (string) $invitation['expires_at'] ) ) ); ?>
									</td>
									<td data-title="<?php esc_attr_e( 'Action', 'ugcify' ); ?>">
										<?php if ( '' !== $action_url && in_array( $status, array( 'pending', 'accepted' ), true ) ) : ?>
											<a class="button" href="<?php echo esc_url( $action_url ); ?>"><?php esc_html_e( 'Open Workspace', 'ugcify' ); ?></a>
										<?php else : ?>
											<span class="ugcify-my-account-invitations__action-muted"><?php esc_html_e( 'N/A', 'ugcify' ); ?></span>
										<?php endif; ?>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Determine whether the My Account menu item should be visible.
	 *
	 * @return bool
	 */
	private function should_show_menu_item(): bool {
		if ( ! is_user_logged_in() || ! Settings::is_enabled() ) {
			return false;
		}

		$user_id = get_current_user_id();

		if ( $this->user_repository->is_creator( $user_id ) ) {
			return true;
		}

		return ! empty( $this->invitation_service->get_invitations_for_user( $user_id, array(), 1 ) );
	}

	/**
	 * Build the action URL for a creator invitation.
	 *
	 * @param array<string,mixed> $invitation Invitation payload.
	 * @return string
	 */
	private function build_action_url( array $invitation ): string {
		$url = isset( $invitation['portal_url'] ) ? (string) $invitation['portal_url'] : '';

		if ( '' === $url ) {
			return '';
		}

		return preg_replace( '/#.*/', '', $url ) . '#ugcify-portal-upload';
	}

	/**
	 * Render a scoped notice.
	 *
	 * @param string $message Notice message.
	 * @return void
	 */
	private function render_notice( string $message ): void {
		?>
		<div class="ugcify-my-account-invitations">
			<div class="ugcify-my-account-invitations__empty">
				<p><?php echo esc_html( $message ); ?></p>
			</div>
		</div>
		<?php
	}

	/**
	 * Format a human-readable invitation status label.
	 *
	 * @param string $status Invitation status.
	 * @return string
	 */
	private function format_status_label( string $status ): string {
		switch ( sanitize_key( $status ) ) {
			case 'accepted':
				return __( 'Accepted', 'ugcify' );
			case 'expired':
				return __( 'Expired', 'ugcify' );
			case 'revoked':
				return __( 'Revoked', 'ugcify' );
			case 'pending':
			default:
				return __( 'Pending', 'ugcify' );
		}
	}

	/**
	 * Print endpoint styles once.
	 *
	 * @return void
	 */
	private function render_styles(): void {
		static $printed = false;

		if ( $printed ) {
			return;
		}

		$printed = true;
		?>
		<style>
			.ugcify-my-account-invitations {
				margin-top: 1em;
			}
			.ugcify-my-account-invitations__header {
				display: flex;
				justify-content: space-between;
				gap: 1.5em;
				align-items: flex-start;
				margin-bottom: 1.5em;
				flex-wrap: wrap;
			}
			.ugcify-my-account-invitations__title {
				margin: 0 0 0.5em;
				font-size: 1.5em;
				font-weight: 600;
				color: inherit;
			}
			.ugcify-my-account-invitations__description {
				margin: 0;
				max-width: 45em;
				opacity: 0.7;
				font-size: 0.95em;
			}
			.ugcify-my-account-invitations__summary {
				display: flex;
				gap: 0.75em;
				flex-wrap: wrap;
			}
			.ugcify-my-account-invitations__summary-card {
				min-width: 7.5em;
				padding: 1em;
				border: 1px solid rgba(0,0,0,0.1);
				border-radius: 0.5em;
				background: rgba(0,0,0,0.02);
				display: flex;
				flex-direction: column;
				gap: 0.25em;
			}
			.ugcify-my-account-invitations__summary-card span {
				font-size: 0.7em;
				text-transform: uppercase;
				letter-spacing: 0.04em;
				opacity: 0.6;
				color: inherit;
			}
			.ugcify-my-account-invitations__summary-card strong {
				font-size: 1.75em;
				line-height: 1.1;
				color: inherit;
			}
			.ugcify-my-account-invitations__table-wrapper {
				overflow-x: auto;
			}
			.ugcify-my-account-invitations__table {
				width: 100%;
				border-collapse: collapse;
				font-size: 0.9em;
			}
			.ugcify-my-account-invitations__table thead th {
				text-align: left;
				padding: 0.75em 1em;
				font-weight: 600;
				font-size: 0.85em;
				text-transform: uppercase;
				letter-spacing: 0.04em;
				border-bottom: 2px solid rgba(0,0,0,0.15);
				color: inherit;
				background: rgba(0,0,0,0.03);
			}
			.ugcify-my-account-invitations__table tbody td {
				padding: 1em;
				border-bottom: 1px solid rgba(0,0,0,0.08);
				vertical-align: middle;
				color: inherit;
			}
			.ugcify-my-account-invitations__table tbody tr {
				background: transparent;
			}
			.ugcify-my-account-invitations__table tbody tr:hover {
				background: rgba(0,0,0,0.02);
			}
			.ugcify-my-account-invitations__table tbody td strong {
				font-weight: 600;
				color: inherit;
			}
			.ugcify-my-account-invitations__message {
				margin: 0.25em 0 0;
				opacity: 0.7;
				font-size: 0.85em;
				color: inherit;
			}
			.ugcify-my-account-invitations__products-text {
				color: inherit;
			}
			.ugcify-my-account-invitations__pill {
				display: inline-flex;
				align-items: center;
				padding: 0.4em 0.75em;
				border-radius: 999px;
				font-size: 0.75em;
				font-weight: 600;
				white-space: nowrap;
			}
			.ugcify-my-account-invitations__pill.is-pending {
				background: #fff7ed;
				color: #c2410c;
				border: 1px solid #fed7aa;
			}
			.ugcify-my-account-invitations__pill.is-accepted {
				background: #ecfdf5;
				color: #047857;
				border: 1px solid #a7f3d0;
			}
			.ugcify-my-account-invitations__pill.is-expired,
			.ugcify-my-account-invitations__pill.is-revoked {
				background: #f3f4f6;
				color: #6b7280;
				border: 1px solid #d1d5db;
			}
			.ugcify-my-account-invitations__table .button {
				margin: 0;
				white-space: nowrap;
				font-size: 0.9em;
			}
			.ugcify-my-account-invitations__action-muted {
				opacity: 0.5;
				font-size: 0.85em;
				color: inherit;
			}
			.ugcify-my-account-invitations__empty {
				padding: 2em;
				border: 1px solid rgba(0,0,0,0.1);
				border-radius: 0.5em;
				background: rgba(0,0,0,0.02);
				text-align: center;
			}
			.ugcify-my-account-invitations__empty p {
				margin: 0;
				opacity: 0.7;
				color: inherit;
			}
			
			/* Responsive table for mobile */
			@media (max-width: 782px) {
				.ugcify-my-account-invitations__header {
					flex-direction: column;
				}
				.ugcify-my-account-invitations__table {
					font-size: 0.95em;
				}
				.ugcify-my-account-invitations__table thead {
					display: none;
				}
				.ugcify-my-account-invitations__table tbody tr {
					display: block;
					margin-bottom: 1.5em;
					border: 1px solid rgba(0,0,0,0.1);
					border-radius: 0.5em;
					background: rgba(0,0,0,0.02);
				}
				.ugcify-my-account-invitations__table tbody tr:hover {
					background: rgba(0,0,0,0.04);
				}
				.ugcify-my-account-invitations__table tbody td {
					display: block;
					text-align: left;
					padding: 0.75em 1em;
					border-bottom: 1px solid rgba(0,0,0,0.05);
				}
				.ugcify-my-account-invitations__table tbody td:last-child {
					border-bottom: none;
				}
				.ugcify-my-account-invitations__table tbody td::before {
					content: attr(data-title) ": ";
					font-weight: 600;
					display: inline-block;
					margin-right: 0.5em;
					color: inherit;
				}
				.ugcify-my-account-invitations__table tbody td strong {
					display: inline;
				}
				.ugcify-my-account-invitations__table .button {
					width: 100%;
					text-align: center;
				}
			}
		</style>
		<?php
	}
}