<?php
/**
 * Tools Settings Tab
 *
 * @package AmbassadorHub\Admin\Settings\Tabs
 */

namespace AmbassadorHub\Admin\Settings\Tabs;

use AmbassadorHub\Admin\InlineAssets;
use AmbassadorHub\Admin\Settings\AbstractTab;
use AmbassadorHub\Admin\Setup\PageInstaller;
use function get_current_user_id;
use function get_userdata;
use function __;
use function _n;
use function admin_url;
use function do_action;
use function esc_attr;
use function esc_html;
use function esc_html__;
use function esc_url;
use function get_edit_post_link;
use function get_permalink;
use function implode;
use function settings_fields;
use function sprintf;
use function submit_button;
use function wp_nonce_field;

/**
 * Tools settings tab.
 *
 * Contains tools and technical platform settings.
 */
final class ToolsTab extends AbstractTab {
	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->id       = 'tools';
		$this->label    = __( 'Tools', 'ambassadorhub' );
		$this->priority = 80;

		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Enqueue this tab's inline CSS.
	 *
	 * Hooked to admin_enqueue_scripts (from the constructor, which runs early
	 * enough via Registry::get_tabs()) so wp_add_inline_style() is attached
	 * before admin_print_styles fires — by the time render() runs later, that
	 * hook has already passed.
	 *
	 * @return void
	 */
	public function enqueue_assets(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only page/tab check.
		$page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';
		if ( 'ambassadorhub-settings' !== $page ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only tab-selection check.
		$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';
		if ( $this->id !== $tab ) {
			return;
		}

		InlineAssets::style(
			'.ambh-export-list {
				border: 1px solid #dcdcde;
				border-radius: 6px;
				margin-top: 1em;
				max-width: 720px;
				background: #fff;
			}

			.ambh-export-row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				gap: 16px;
				padding: 14px 18px;
				border-bottom: 1px solid #dcdcde;
			}

			.ambh-export-row:last-child {
				border-bottom: none;
			}

			.ambh-export-row__name {
				display: block;
				font-size: 14px;
			}

			.ambh-export-row__description {
				margin: 2px 0 0;
				color: #646970;
				font-size: 12.5px;
			}

			.ambh-export-row__action {
				flex-shrink: 0;
				margin: 0;
			}

			@media screen and (max-width: 600px) {
				.ambh-export-row {
					flex-direction: column;
					align-items: flex-start;
				}

				.ambh-export-row__action {
					width: 100%;
				}

				.ambh-export-row__action .button {
					width: 100%;
					text-align: center;
				}
			}'
		);
	}

	/**
	 * Render the Tools tab content.
	 *
	 * @return void
	 */
	public function render(): void {

		// Test mail result notice.
		if ( isset( $_GET['ambh_test_mail'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display of redirect result.
			$result = sanitize_key( $_GET['ambh_test_mail'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( 'sent' === $result ) {
				?>
				<div class="notice notice-success is-dismissible inline">
					<p><?php esc_html_e( 'Test email sent successfully. Please check your inbox.', 'ambassadorhub' ); ?></p>
				</div>
				<?php
			} elseif ( 'failed' === $result ) {
				?>
				<div class="notice notice-error is-dismissible inline">
					<p><?php esc_html_e( 'Test email could not be sent. Check your WordPress mail configuration.', 'ambassadorhub' ); ?></p>
				</div>
				<?php
			} elseif ( 'invalid' === $result ) {
				?>
				<div class="notice notice-error is-dismissible inline">
					<p><?php esc_html_e( 'Invalid email address.', 'ambassadorhub' ); ?></p>
				</div>
				<?php
			}
			InlineAssets::script(
				"( function() {
					var url = new URL( window.location.href );
					url.searchParams.delete( 'ambh_test_mail' );
					history.replaceState( null, '', url.toString() );
				} )();"
			);
		}

		if ( isset( $_GET['ambh_cache_cleared'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display of redirect result.
			?>
			<div class="notice notice-success is-dismissible inline">
				<p><?php echo esc_html__( 'All caches cleared.', 'ambassadorhub' ); ?></p>
			</div>
			<?php
			InlineAssets::script(
				"( function() {
					var url = new URL( window.location.href );
					url.searchParams.delete( 'ambh_cache_cleared' );
					history.replaceState( null, '', url.toString() );
				} )();"
			);
		}

		// Display result notice when returning from the page-creation action.
		if ( isset( $_GET['ambh_pages_created'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display of redirect result.
			$created = isset( $_GET['ambh_pages_created'] ) ? absint( wp_unslash( $_GET['ambh_pages_created'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$skipped = isset( $_GET['ambh_pages_skipped'] ) ? absint( wp_unslash( $_GET['ambh_pages_skipped'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$synced  = isset( $_GET['ambh_pages_synced'] ) ? absint( wp_unslash( $_GET['ambh_pages_synced'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$errors  = isset( $_GET['ambh_pages_errors'] ) ? absint( wp_unslash( $_GET['ambh_pages_errors'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$type    = $errors > 0 ? 'error' : ( $created > 0 || $synced > 0 ? 'success' : 'info' );
			$parts   = array();
			if ( $created > 0 ) {
				/* translators: %d: number of pages created */
				$parts[] = sprintf( _n( '%d page created.', '%d pages created.', $created, 'ambassadorhub' ), $created );
			}
			if ( $synced > 0 ) {
				/* translators: %d: number of pages whose content was updated */
				$parts[] = sprintf( _n( '%d page content updated.', '%d page contents updated.', $synced, 'ambassadorhub' ), $synced );
			}
			if ( $skipped > 0 ) {
				/* translators: %d: number of pages skipped */
				$parts[] = sprintf( _n( '%d page already up to date.', '%d pages already up to date.', $skipped, 'ambassadorhub' ), $skipped );
			}
			if ( $errors > 0 ) {
				/* translators: %d: number of pages that could not be created */
				$parts[] = sprintf( _n( '%d page could not be created.', '%d pages could not be created.', $errors, 'ambassadorhub' ), $errors );
			}
			$message_text = implode( ' ', $parts );
			$message      = $message_text ? $message_text : __( 'No changes made.', 'ambassadorhub' );
			?>
			<div class="notice notice-<?php echo esc_attr( $type ); ?> is-dismissible inline">
				<p><?php echo esc_html( $message ); ?></p>
			</div>
			<?php
			InlineAssets::script(
				"( function() {
					var url = new URL( window.location.href );
					url.searchParams.delete( 'ambh_pages_created' );
					url.searchParams.delete( 'ambh_pages_skipped' );
					url.searchParams.delete( 'ambh_pages_synced' );
					url.searchParams.delete( 'ambh_pages_errors' );
					history.replaceState( null, '', url.toString() );
				} )();"
			);
		}
		?>

		<?php
		ob_start();
		/**
		 * Fires in the Tools settings tab.
		 *
		 * Modules and feature plugins can add fields here.
		 *
		 * @since 0.1.0
		 */
		do_action( 'ambh_settings_tools_fields' );
		$tools_fields = ob_get_clean();

		if ( $tools_fields ) :
			?>
		<form method="post" action="options.php">
			<?php settings_fields( 'ambh_tools' ); ?>

			<h3><?php echo esc_html__( 'Tools', 'ambassadorhub' ); ?></h3>

			<table class="form-table" role="presentation">
				<tbody>
					<?php echo $tools_fields; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped by each field renderer. ?>
				</tbody>
			</table>

			<?php submit_button(); ?>
		</form>

		<hr />
		<?php endif; ?>

		<h3><?php echo esc_html__( 'Pages', 'ambassadorhub' ); ?></h3>
		<p class="description"><?php echo esc_html__( 'AmbassadorHub requires dedicated WordPress pages for the ambassador portal, login/signup, and post-payment confirmation. Create missing pages here — pages that are already configured will be skipped.', 'ambassadorhub' ); ?></p>

		<table class="wp-list-table widefat fixed striped" style="margin-top: 1em;">
			<thead>
				<tr>
					<th scope="col"><?php echo esc_html__( 'Page', 'ambassadorhub' ); ?></th>
					<th scope="col"><?php echo esc_html__( 'Status', 'ambassadorhub' ); ?></th>
					<th scope="col"><?php echo esc_html__( 'Actions', 'ambassadorhub' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( PageInstaller::get_statuses() as $status ) : ?>
				<tr>
					<td><strong><?php echo esc_html( $status['definition']['label'] ); ?></strong></td>
					<td>
						<?php if ( false === $status['block_ok'] ) : ?>
							<span style="color: #d46b00;">&#9888; <?php echo esc_html__( 'Required block not found on this page.', 'ambassadorhub' ); ?></span>
						<?php elseif ( $status['page_exists'] ) : ?>
							<span style="color: #46b450;">&#10003; <?php echo esc_html__( 'Configured', 'ambassadorhub' ); ?></span>
						<?php elseif ( $status['option_set'] ) : ?>
							<span style="color: #d63638;">&#10007; <?php echo esc_html__( 'Page missing', 'ambassadorhub' ); ?></span>
						<?php else : ?>
							<span style="color: #999;">&#8212; <?php echo esc_html__( 'Not configured', 'ambassadorhub' ); ?></span>
						<?php endif; ?>
					</td>
					<td>
						<?php if ( $status['page_exists'] ) : ?>
							<a href="<?php echo esc_url( get_edit_post_link( $status['page_id'] ) ?? '' ); ?>"><?php echo esc_html__( 'Edit', 'ambassadorhub' ); ?></a>
							&nbsp;&middot;&nbsp;
							<a href="<?php echo esc_url( (string) get_permalink( $status['page_id'] ) ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__( 'View', 'ambassadorhub' ); ?></a>
						<?php else : ?>
							&mdash;
						<?php endif; ?>
					</td>
				</tr>
				<?php endforeach; ?>
			</tbody>
		</table>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top: 1em;">
			<?php wp_nonce_field( 'ambh_create_pages', 'ambh_create_pages_nonce' ); ?>
			<input type="hidden" name="action" value="ambh_create_pages">
			<?php submit_button( __( 'Create missing pages', 'ambassadorhub' ), 'secondary', 'ambh_create_pages_submit', false ); ?>
		</form>

		<hr />

		<h3><?php esc_html_e( 'Email', 'ambassadorhub' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Send a test email to verify that the AmbassadorHub mail service and template are working correctly.', 'ambassadorhub' ); ?></p>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top: 1em;">
			<?php wp_nonce_field( 'ambh_send_test_mail', 'ambh_send_test_mail_nonce' ); ?>
			<input type="hidden" name="action" value="ambh_send_test_mail">
			<table class="form-table" role="presentation">
				<tbody>
					<tr>
						<th scope="row"><label for="ambh_test_mail_to"><?php esc_html_e( 'Send to', 'ambassadorhub' ); ?></label></th>
						<td>
							<?php
							$current_user  = get_userdata( get_current_user_id() );
							$default_email = $current_user ? $current_user->user_email : '';
							?>
							<input type="email" id="ambh_test_mail_to" name="ambh_test_mail_to"
								value="<?php echo esc_attr( $default_email ); ?>"
								class="regular-text"
								required>
						</td>
					</tr>
				</tbody>
			</table>
			<?php submit_button( __( 'Send test email', 'ambassadorhub' ), 'secondary', 'ambh_send_test_mail_submit', false ); ?>
		</form>

		<hr />

		<h3><?php echo esc_html__( 'Cache', 'ambassadorhub' ); ?></h3>
		<p class="description"><?php echo esc_html__( 'Bump the global cache index to immediately invalidate all AmbassadorHub transients. Use this if data appears stale after an import, migration, or direct database change.', 'ambassadorhub' ); ?></p>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top: 1em;">
			<?php wp_nonce_field( 'ambh_clear_cache', 'ambh_clear_cache_nonce' ); ?>
			<input type="hidden" name="action" value="ambh_clear_cache">
			<?php submit_button( __( 'Clear all caches', 'ambassadorhub' ), 'secondary', 'ambh_clear_cache_submit', false ); ?>
		</form>

		<hr />

		<h3><?php esc_html_e( 'Export data', 'ambassadorhub' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Download a CSV export of your data.', 'ambassadorhub' ); ?></p>

		<?php
		$exports = array(
			array(
				'action'      => 'ambh_export_donors',
				'label'       => __( 'Donors', 'ambassadorhub' ),
				'description' => __( 'Contact details and address for every donor profile.', 'ambassadorhub' ),
			),
			array(
				'action'      => 'ambh_export_donations',
				'label'       => __( 'Donations', 'ambassadorhub' ),
				'description' => __( 'Every donation with the linked donor, amount, status, and any configured custom fields.', 'ambassadorhub' ),
			),
			array(
				'action'      => 'ambh_export_ambassadors',
				'label'       => __( 'Ambassadors', 'ambassadorhub' ),
				'description' => __( 'Every user with the Ambassador role, including profile and address fields.', 'ambassadorhub' ),
			),
			array(
				'action'      => 'ambh_export_consent_records',
				'label'       => __( 'Consent records', 'ambassadorhub' ),
				'description' => __( 'All recorded consent, including marketing opt-ins and withdrawals.', 'ambassadorhub' ),
			),
		);
		?>

		<div class="ambh-export-list">
			<?php foreach ( $exports as $export ) : ?>
			<div class="ambh-export-row">
				<div class="ambh-export-row__info">
					<strong class="ambh-export-row__name"><?php echo esc_html( $export['label'] ); ?></strong>
					<p class="ambh-export-row__description"><?php echo esc_html( $export['description'] ); ?></p>
				</div>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ambh-export-row__action">
					<?php wp_nonce_field( $export['action'], $export['action'] . '_nonce' ); ?>
					<input type="hidden" name="action" value="<?php echo esc_attr( $export['action'] ); ?>">
					<?php submit_button( __( 'Download CSV', 'ambassadorhub' ), 'secondary', '', false ); ?>
				</form>
			</div>
			<?php endforeach; ?>
		</div>
		<?php
	}
}
