<?php
/**
 * Admin UI.
 *
 * @package TonItaliaRegistration
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class TON_Reg_Admin
 */
class TON_Reg_Admin {

	/**
	 * Register hooks.
	 */
	public static function register() {
		add_action( 'admin_menu', array( __CLASS__, 'menu' ) );
		add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
		add_action( 'admin_post_ton_reg_save_registration', array( __CLASS__, 'save_registration' ) );
		add_action( 'admin_post_ton_reg_gdpr_export', array( __CLASS__, 'gdpr_export' ) );
		add_action( 'admin_post_ton_reg_gdpr_anonymize', array( __CLASS__, 'gdpr_anonymize' ) );
		add_action( 'admin_post_ton_reg_gdpr_erase', array( __CLASS__, 'gdpr_erase' ) );
		add_action( 'admin_post_ton_reg_upload_document', array( __CLASS__, 'upload_document' ) );
		add_action( 'admin_post_ton_reg_delete_document', array( __CLASS__, 'delete_document' ) );
		add_action( 'admin_post_ton_reg_mailchimp_test', array( __CLASS__, 'mailchimp_test' ) );
		add_action( 'admin_post_ton_reg_mailchimp_retry', array( __CLASS__, 'mailchimp_retry' ) );
	}

	/**
	 * @param string $hook_suffix Current admin page hook.
	 */
	public static function enqueue_assets( $hook_suffix ) {
		$allowed = array(
			'toplevel_page_ton-registrations',
			'ton-registrations_page_ton-reg-settings',
		);
		if ( ! in_array( $hook_suffix, $allowed, true ) ) {
			return;
		}

		wp_enqueue_style(
			'ton-reg-admin',
			TON_REG_PLUGIN_URL . 'assets/css/admin.css',
			array(),
			TON_REG_VERSION
		);
	}

	/**
	 * Admin menu.
	 */
	public static function menu() {
		add_menu_page(
			__( 'TON Iscrizioni', 'ton-italia-registration' ),
			__( 'TON Iscrizioni', 'ton-italia-registration' ),
			'manage_options',
			'ton-registrations',
			array( __CLASS__, 'page_list' ),
			'dashicons-groups',
			58
		);

		add_submenu_page(
			'ton-registrations',
			__( 'Elenco iscrizioni', 'ton-italia-registration' ),
			__( 'Elenco', 'ton-italia-registration' ),
			'manage_options',
			'ton-registrations',
			array( __CLASS__, 'page_list' )
		);

		add_submenu_page(
			'ton-registrations',
			__( 'Impostazioni', 'ton-italia-registration' ),
			__( 'Impostazioni', 'ton-italia-registration' ),
			'manage_options',
			'ton-reg-settings',
			array( __CLASS__, 'page_settings' )
		);
	}

	/**
	 * Register settings.
	 */
	public static function register_settings() {
		$checkboxes = array(
			'ton_reg_captcha_enabled',
			'ton_reg_newsletter_required',
			'ton_reg_delete_users_on_uninstall',
			'ton_reg_mailchimp_enabled',
		);

		$plain_text = array(
			'ton_reg_social_year',
			'ton_reg_membership_fee',
			'ton_reg_beneficiary',
			'ton_reg_iban',
			'ton_reg_admin_email',
			'ton_reg_gdpr_contact',
			'ton_reg_email_admin_subject',
			'ton_reg_email_user_subject',
			'ton_reg_rate_limit_max',
			'ton_reg_rate_limit_window',
			'ton_reg_privacy_version',
			'ton_reg_mailchimp_tags',
		);

		$skip_auto = array(
			'ton_reg_mailchimp_api_key',
			'ton_reg_mailchimp_list_id',
			'ton_reg_mailchimp_permission_ids',
		);

		register_setting(
			'ton_reg_settings',
			'ton_reg_mailchimp_api_key',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( 'TON_Reg_Mailchimp', 'sanitize_api_key' ),
				'show_in_rest'      => false,
				'default'           => '',
			)
		);

		register_setting(
			'ton_reg_settings',
			'ton_reg_mailchimp_list_id',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( 'TON_Reg_Mailchimp', 'sanitize_list_id' ),
				'show_in_rest'      => false,
				'default'           => '',
			)
		);

		$options = array_keys( TON_Reg_Defaults::options() );
		foreach ( $options as $option ) {
			if ( in_array( $option, $skip_auto, true ) ) {
				continue;
			}
			if ( in_array( $option, $checkboxes, true ) ) {
				$sanitize = array( __CLASS__, 'sanitize_checkbox' );
			} elseif ( in_array( $option, $plain_text, true ) ) {
				$sanitize = 'sanitize_text_field';
			} else {
				$sanitize = array( __CLASS__, 'sanitize_setting' );
			}

			register_setting(
				'ton_reg_settings',
				$option,
				array(
					'type'              => 'string',
					'sanitize_callback' => $sanitize,
				)
			);
		}
	}

	/**
	 * @param mixed $value Value.
	 * @return string
	 */
	public static function sanitize_setting( $value ) {
		if ( is_array( $value ) ) {
			return '';
		}
		return wp_kses_post( wp_unslash( (string) $value ) );
	}

	/**
	 * @param string $value Checkbox value.
	 * @return string
	 */
	public static function sanitize_checkbox( $value ) {
		return '1' === (string) $value ? '1' : '0';
	}

	/**
	 * List page.
	 */
	public static function page_list() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( isset( $_GET['action'], $_GET['id'] ) && 'view' === $_GET['action'] ) {
			self::page_detail( (int) $_GET['id'] );
			return;
		}

		$table = new TON_Reg_Registration_List_Table();
		$table->prepare_items();

		$status = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '';
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Iscrizioni socio', 'ton-italia-registration' ); ?></h1>
			<?php if ( isset( $_GET['updated'] ) ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Salvato.', 'ton-italia-registration' ); ?></p></div>
			<?php endif; ?>
			<ul class="subsubsub">
				<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=ton-registrations' ) ); ?>"><?php esc_html_e( 'Tutti', 'ton-italia-registration' ); ?></a> |</li>
				<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=ton-registrations&status=pending' ) ); ?>"><?php esc_html_e( 'In attesa', 'ton-italia-registration' ); ?></a> |</li>
				<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=ton-registrations&status=admitted' ) ); ?>"><?php esc_html_e( 'Ammessi', 'ton-italia-registration' ); ?></a> |</li>
				<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=ton-registrations&status=rejected' ) ); ?>"><?php esc_html_e( 'Non ammessi', 'ton-italia-registration' ); ?></a></li>
			</ul>
			<form method="get" class="ton-reg-list-search">
				<input type="hidden" name="page" value="ton-registrations" />
				<?php if ( $status ) : ?>
					<input type="hidden" name="status" value="<?php echo esc_attr( $status ); ?>" />
				<?php endif; ?>
				<p class="search-box">
					<label class="screen-reader-text" for="ton-reg-search"><?php esc_html_e( 'Cerca', 'ton-italia-registration' ); ?></label>
					<input type="search" id="ton-reg-search" name="s" value="<?php echo isset( $_GET['s'] ) ? esc_attr( sanitize_text_field( wp_unslash( $_GET['s'] ) ) ) : ''; ?>" />
					<input type="submit" class="button" value="<?php esc_attr_e( 'Cerca', 'ton-italia-registration' ); ?>" />
				</p>
			</form>
			<?php $table->display(); ?>
		</div>
		<?php
	}

	/**
	 * @param int $id Registration ID.
	 */
	public static function page_detail( $id ) {
		$row = TON_Reg_Database::get( $id );
		if ( ! $row ) {
			echo '<div class="wrap"><p>' . esc_html__( 'Non trovato.', 'ton-italia-registration' ) . '</p></div>';
			return;
		}
		?>
		<div class="wrap">
			<h1><?php printf( esc_html__( 'Iscrizione #%d', 'ton-italia-registration' ), (int) $id ); ?></h1>
			<p><a href="<?php echo esc_url( admin_url( 'admin.php?page=ton-registrations' ) ); ?>">&larr; <?php esc_html_e( 'Torna all\'elenco', 'ton-italia-registration' ); ?></a></p>

			<?php self::render_admin_notices(); ?>

			<h2><?php esc_html_e( 'Documenti', 'ton-italia-registration' ); ?></h2>
			<p class="description">
				<?php
				printf(
					/* translators: %s: folder path under uploads */
					esc_html__( 'I file vengono salvati in Media, cartella «%s», sottocartella «%s».', 'ton-italia-registration' ),
					esc_html( TON_Reg_Documents::BASE_FOLDER ),
					esc_html( TON_Reg_Documents::member_folder_slug( $row ) )
				);
				?>
			</p>
			<?php foreach ( TON_Reg_Documents::get_types() as $doc_type ) : ?>
				<?php self::render_document_block( $id, $row, $doc_type ); ?>
			<?php endforeach; ?>

			<?php self::render_consents_section( $row ); ?>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<input type="hidden" name="action" value="ton_reg_save_registration" />
				<input type="hidden" name="registration_id" value="<?php echo (int) $id; ?>" />
				<?php wp_nonce_field( 'ton_reg_save_' . $id, 'ton_reg_admin_nonce' ); ?>

				<table class="form-table">
					<?php
					$fields = array(
						'cognome', 'nome', 'luogo_nascita', 'provincia_nascita', 'data_nascita', 'codice_fiscale',
						'comune_residenza', 'provincia_residenza', 'indirizzo', 'numero_civico', 'cap', 'telefono', 'email',
						'registration_ip', 'user_agent', 'created_at',
					);
					foreach ( $fields as $field ) :
						?>
					<tr>
						<th><?php echo esc_html( $field ); ?></th>
						<td><?php echo esc_html( $row->$field ?? '' ); ?></td>
					</tr>
					<?php endforeach; ?>
					<tr>
						<th><?php esc_html_e( 'Stato', 'ton-italia-registration' ); ?></th>
						<td>
							<select name="status">
								<option value="pending" <?php selected( $row->status, 'pending' ); ?>><?php esc_html_e( 'In attesa', 'ton-italia-registration' ); ?></option>
								<option value="admitted" <?php selected( $row->status, 'admitted' ); ?>><?php esc_html_e( 'Ammesso', 'ton-italia-registration' ); ?></option>
								<option value="rejected" <?php selected( $row->status, 'rejected' ); ?>><?php esc_html_e( 'Non ammesso', 'ton-italia-registration' ); ?></option>
							</select>
						</td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Data Libro Associati', 'ton-italia-registration' ); ?></th>
						<td><input type="date" name="libro_associati_date" value="<?php echo esc_attr( $row->libro_associati_date ?? '' ); ?>" /></td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Note admin', 'ton-italia-registration' ); ?></th>
						<td><textarea name="admin_notes" rows="4" class="large-text"><?php echo esc_textarea( $row->admin_notes ?? '' ); ?></textarea></td>
					</tr>
				</table>
				<?php submit_button( __( 'Salva', 'ton-italia-registration' ) ); ?>
			</form>

			<h2><?php esc_html_e( 'GDPR', 'ton-italia-registration' ); ?></h2>
			<p>
				<a class="button" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=ton_reg_gdpr_export&id=' . $id . '&format=json' ), 'ton_reg_gdpr_' . $id ) ); ?>"><?php esc_html_e( 'Esporta JSON', 'ton-italia-registration' ); ?></a>
				<a class="button" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=ton_reg_gdpr_export&id=' . $id . '&format=csv' ), 'ton_reg_gdpr_' . $id ) ); ?>"><?php esc_html_e( 'Esporta CSV', 'ton-italia-registration' ); ?></a>
				<?php if ( ! $row->anonymized_at ) : ?>
				<a class="button" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=ton_reg_gdpr_anonymize&id=' . $id ), 'ton_reg_gdpr_' . $id ) ); ?>" onclick="return confirm('<?php esc_attr_e( 'Anonimizzare i dati?', 'ton-italia-registration' ); ?>');"><?php esc_html_e( 'Anonimizza', 'ton-italia-registration' ); ?></a>
				<?php endif; ?>
				<a class="button button-link-delete" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=ton_reg_gdpr_erase&id=' . $id ), 'ton_reg_gdpr_' . $id ) ); ?>" onclick="return confirm('<?php esc_attr_e( 'Eliminare definitivamente iscrizione e utente WP?', 'ton-italia-registration' ); ?>');"><?php esc_html_e( 'Elimina definitivamente', 'ton-italia-registration' ); ?></a>
			</p>
		</div>
		<?php
	}

	/**
	 * @param object $row Registration row.
	 */
	private static function render_consents_section( $row ) {
		?>
		<h2><?php esc_html_e( 'Consensi e dichiarazioni', 'ton-italia-registration' ); ?></h2>
		<p class="description"><?php esc_html_e( 'Il richiedente ha espresso i consensi spuntando le caselle nel modulo pubblico (sostitutivo della firma).', 'ton-italia-registration' ); ?></p>
		<table class="form-table ton-reg-consents">
			<tr>
				<th scope="row"><?php esc_html_e( 'Dichiarazione statuto e regolamenti', 'ton-italia-registration' ); ?></th>
				<td>
					<?php self::render_consent_status( ! empty( $row->consenso_statuto ) ); ?>
					<?php if ( ! empty( $row->consent_statuto_at ) ) : ?>
						<p class="description"><?php echo esc_html( self::format_consent_datetime( $row->consent_statuto_at ) ); ?></p>
					<?php endif; ?>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Privacy e trattamento dati personali', 'ton-italia-registration' ); ?></th>
				<td>
					<?php self::render_consent_status( ! empty( $row->consenso_privacy ) ); ?>
					<?php if ( ! empty( $row->consent_privacy_at ) ) : ?>
						<p class="description"><?php echo esc_html( self::format_consent_datetime( $row->consent_privacy_at ) ); ?></p>
					<?php endif; ?>
					<?php if ( ! empty( $row->privacy_text_version ) ) : ?>
						<p class="description">
							<?php
							printf(
								/* translators: %s: privacy text version id */
								esc_html__( 'Versione informativa al momento del consenso: %s', 'ton-italia-registration' ),
								esc_html( $row->privacy_text_version )
							);
							?>
						</p>
					<?php endif; ?>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Consenso newsletter', 'ton-italia-registration' ); ?></th>
				<td>
					<?php if ( ! empty( $row->consenso_newsletter ) ) : ?>
						<?php self::render_consent_status( true ); ?>
						<?php self::render_mailchimp_sync_status( $row ); ?>
					<?php else : ?>
						<span class="ton-reg-consent ton-reg-consent--neutral"><?php esc_html_e( 'Non espresso / non richiesto', 'ton-italia-registration' ); ?></span>
					<?php endif; ?>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Bonifico effettuato (dichiarato)', 'ton-italia-registration' ); ?></th>
				<td>
					<?php self::render_consent_status( ! empty( $row->bonifico_effettuato ), false ); ?>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Luogo e data dichiarazione', 'ton-italia-registration' ); ?></th>
				<td>
					<?php
					echo esc_html(
						trim(
							( $row->luogo_dichiarazione ?? '' ) . ( ! empty( $row->data_dichiarazione ) ? ', ' . self::format_date_display( $row->data_dichiarazione ) : '' )
						)
					);
					?>
				</td>
			</tr>
		</table>
		<?php
	}

	/**
	 * @param bool $accepted Whether consent was given.
	 * @param bool $is_consent Whether this is a legal consent (vs operational flag).
	 */
	private static function render_consent_status( $accepted, $is_consent = true ) {
		if ( $accepted ) {
			$class = 'ton-reg-consent ton-reg-consent--yes';
			$text  = $is_consent
				? __( 'Sì — accettato tramite checkbox nel form', 'ton-italia-registration' )
				: __( 'Sì — indicato tramite checkbox nel form', 'ton-italia-registration' );
		} else {
			$class = 'ton-reg-consent ton-reg-consent--no';
			$text  = $is_consent
				? __( 'No — non risulta accettato', 'ton-italia-registration' )
				: __( 'No — non indicato', 'ton-italia-registration' );
		}
		echo '<span class="' . esc_attr( $class ) . '">' . esc_html( $text ) . '</span>';
	}

	/**
	 * @param object $row Registration row.
	 */
	private static function render_mailchimp_sync_status( $row ) {
		$status = isset( $row->mailchimp_status ) ? (string) $row->mailchimp_status : '';

		if ( '' === $status ) {
			if ( TON_Reg_Mailchimp::is_configured() ) {
				echo '<p class="description">' . esc_html__( 'Mailchimp: in attesa di sincronizzazione.', 'ton-italia-registration' ) . '</p>';
			}
			return;
		}

		$labels = array(
			'pending' => __( 'Mailchimp: sincronizzazione in corso', 'ton-italia-registration' ),
			'synced'  => __( 'Mailchimp: iscritto correttamente', 'ton-italia-registration' ),
			'error'   => __( 'Mailchimp: errore di sincronizzazione', 'ton-italia-registration' ),
			'skipped' => __( 'Mailchimp: non sincronizzato (integrazione disattiva)', 'ton-italia-registration' ),
		);

		$label = $labels[ $status ] ?? $status;
		echo '<p class="description"><strong>' . esc_html( $label ) . '</strong></p>';

		if ( ! empty( $row->mailchimp_synced_at ) && 'synced' === $status ) {
			echo '<p class="description">' . esc_html( self::format_consent_datetime( $row->mailchimp_synced_at ) ) . '</p>';
		}

		if ( ! empty( $row->mailchimp_error ) && 'error' === $status ) {
			echo '<p class="description">' . esc_html( $row->mailchimp_error ) . '</p>';
		}

		if ( TON_Reg_Mailchimp::is_configured() && in_array( $status, array( 'error', 'pending' ), true ) ) {
			$retry_url = wp_nonce_url(
				admin_url( 'admin-post.php?action=ton_reg_mailchimp_retry&id=' . (int) $row->id ),
				'ton_reg_mc_retry_' . (int) $row->id
			);
			echo '<p><a class="button button-small" href="' . esc_url( $retry_url ) . '">' . esc_html__( 'Riprova iscrizione Mailchimp', 'ton-italia-registration' ) . '</a></p>';
		}
	}

	/**
	 * @param string $datetime UTC datetime from DB.
	 * @return string
	 */
	private static function format_consent_datetime( $datetime ) {
		$ts = strtotime( $datetime . ' UTC' );
		if ( ! $ts ) {
			return $datetime;
		}
		return sprintf(
			/* translators: %s: formatted date and time */
			__( 'Registrato il %s', 'ton-italia-registration' ),
			wp_date( 'd/m/Y H:i', $ts )
		);
	}

	/**
	 * @param string $date Date Y-m-d.
	 * @return string
	 */
	private static function format_date_display( $date ) {
		$ts = strtotime( $date );
		return $ts ? wp_date( 'd/m/Y', $ts ) : $date;
	}

	/**
	 * Admin notices for document upload / errors.
	 */
	private static function render_admin_notices() {
		if ( isset( $_GET['doc_ok'] ) ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Documento caricato.', 'ton-italia-registration' ) . '</p></div>';
		}
		if ( isset( $_GET['doc_deleted'] ) ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Documento eliminato.', 'ton-italia-registration' ) . '</p></div>';
		}
		if ( ! empty( $_GET['doc_error'] ) ) {
			$msg = sanitize_text_field( wp_unslash( rawurldecode( $_GET['doc_error'] ) ) );
			echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $msg ) . '</p></div>';
		}
		if ( isset( $_GET['mc_ok'] ) ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Sincronizzazione Mailchimp completata.', 'ton-italia-registration' ) . '</p></div>';
		}
		if ( ! empty( $_GET['mc_error'] ) ) {
			$msg = sanitize_text_field( wp_unslash( rawurldecode( $_GET['mc_error'] ) ) );
			echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $msg ) . '</p></div>';
		}
	}

	/**
	 * @param int    $id   Registration ID.
	 * @param object $row  Registration row.
	 * @param string $type Document type.
	 */
	private static function render_document_block( $id, $row, $type ) {
		$column = TON_Reg_Documents::get_column( $type );
		$file   = $column ? TON_Reg_Documents::get_file_info( (int) ( $row->$column ?? 0 ) ) : null;
		?>
		<div class="ton-reg-doc-block">
			<h3><?php echo esc_html( TON_Reg_Documents::type_label( $type ) ); ?></h3>
			<?php if ( $file ) : ?>
				<p class="ton-reg-doc-block__file">
					<a href="<?php echo esc_url( $file['url'] ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $file['name'] ); ?></a>
					<a class="button button-small" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=ton_reg_delete_document&registration_id=' . $id . '&document_type=' . $type ), 'ton_reg_del_doc_' . $id . '_' . $type ) ); ?>" onclick="return confirm('<?php esc_attr_e( 'Eliminare questo documento?', 'ton-italia-registration' ); ?>');"><?php esc_html_e( 'Elimina', 'ton-italia-registration' ); ?></a>
				</p>
			<?php else : ?>
				<p class="description"><?php esc_html_e( 'Nessun file caricato.', 'ton-italia-registration' ); ?></p>
			<?php endif; ?>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data" class="ton-reg-doc-block__upload">
				<input type="hidden" name="action" value="ton_reg_upload_document" />
				<input type="hidden" name="registration_id" value="<?php echo (int) $id; ?>" />
				<input type="hidden" name="document_type" value="<?php echo esc_attr( $type ); ?>" />
				<?php wp_nonce_field( 'ton_reg_doc_' . $id . '_' . $type, 'ton_reg_doc_nonce' ); ?>
				<input type="file" name="ton_reg_document" accept=".pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png" <?php echo $file ? '' : 'required'; ?> />
				<?php submit_button( $file ? __( 'Sostituisci file', 'ton-italia-registration' ) : __( 'Carica file', 'ton-italia-registration' ), 'secondary', 'submit', false ); ?>
			</form>
		</div>
		<?php
	}

	/**
	 * Upload member document.
	 */
	public static function upload_document() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Non autorizzato.', 'ton-italia-registration' ) );
		}

		$id   = isset( $_POST['registration_id'] ) ? (int) $_POST['registration_id'] : 0;
		$type = isset( $_POST['document_type'] ) ? sanitize_text_field( wp_unslash( $_POST['document_type'] ) ) : '';

		check_admin_referer( 'ton_reg_doc_' . $id . '_' . $type, 'ton_reg_doc_nonce' );

		$file = isset( $_FILES['ton_reg_document'] ) ? $_FILES['ton_reg_document'] : null;
		$result = TON_Reg_Documents::upload( $id, $type, $file );

		$redirect = admin_url( 'admin.php?page=ton-registrations&action=view&id=' . $id );

		if ( is_wp_error( $result ) ) {
			wp_safe_redirect(
				add_query_arg(
					array( 'doc_error' => rawurlencode( $result->get_error_message() ) ),
					$redirect
				)
			);
			exit;
		}

		wp_safe_redirect( add_query_arg( 'doc_ok', '1', $redirect ) );
		exit;
	}

	/**
	 * Delete member document.
	 */
	public static function delete_document() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Non autorizzato.', 'ton-italia-registration' ) );
		}

		$id   = isset( $_GET['registration_id'] ) ? (int) $_GET['registration_id'] : 0;
		$type = isset( $_GET['document_type'] ) ? sanitize_text_field( wp_unslash( $_GET['document_type'] ) ) : '';

		check_admin_referer( 'ton_reg_del_doc_' . $id . '_' . $type );

		TON_Reg_Documents::delete_document( $id, $type );

		wp_safe_redirect(
			add_query_arg(
				'doc_deleted',
				'1',
				admin_url( 'admin.php?page=ton-registrations&action=view&id=' . $id )
			)
		);
		exit;
	}

	/**
	 * Settings page.
	 */
	public static function page_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Impostazioni TON Iscrizioni', 'ton-italia-registration' ); ?></h1>

			<?php if ( isset( $_GET['mc_test_ok'] ) ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Connessione Mailchimp riuscita.', 'ton-italia-registration' ); ?></p></div>
			<?php endif; ?>
			<?php if ( ! empty( $_GET['mc_test_error'] ) ) : ?>
				<div class="notice notice-error is-dismissible"><p><?php echo esc_html( sanitize_text_field( wp_unslash( rawurldecode( $_GET['mc_test_error'] ) ) ) ); ?></p></div>
			<?php endif; ?>

			<div class="ton-reg-shortcode-box">
				<h2 class="ton-reg-shortcode-box__title"><?php esc_html_e( 'Inserire il form in una pagina', 'ton-italia-registration' ); ?></h2>
				<p class="ton-reg-shortcode-box__text">
					<?php esc_html_e( 'Crea o modifica una pagina WordPress (es. «Iscrizione socio»), poi incolla lo shortcode nel contenuto — in un blocco «Shortcode» dell’editor o direttamente nel testo. Pubblica la pagina: il modulo di iscrizione apparirà automaticamente.', 'ton-italia-registration' ); ?>
				</p>
				<p class="ton-reg-shortcode-box__code"><code>[ton_registration_form]</code></p>
				<p class="description ton-reg-shortcode-box__hint">
					<?php esc_html_e( 'Opzionale: aggiungi una classe CSS al contenitore, ad esempio', 'ton-italia-registration' ); ?>
					<code>[ton_registration_form class="mia-classe"]</code>
				</p>
			</div>

			<form method="post" action="options.php">
				<?php
				settings_fields( 'ton_reg_settings' );
				$textareas = array(
					'ton_reg_payment_instructions' => __( 'Istruzioni bonifico', 'ton-italia-registration' ),
					'ton_reg_statuto_declaration'  => __( 'Dichiarazione statuto (checkbox 1)', 'ton-italia-registration' ),
					'ton_reg_privacy_notice'        => __( 'Informativa privacy', 'ton-italia-registration' ),
					'ton_reg_newsletter_label'      => __( 'Label consenso newsletter', 'ton-italia-registration' ),
					'ton_reg_minor_notice'          => __( 'Avviso minorenni', 'ton-italia-registration' ),
					'ton_reg_success_message'       => __( 'Messaggio successo', 'ton-italia-registration' ),
					'ton_reg_email_admin_body'      => __( 'Email admin (testo)', 'ton-italia-registration' ),
					'ton_reg_email_user_body'       => __( 'Email utente (testo)', 'ton-italia-registration' ),
				);
				?>
				<table class="form-table">
					<tr><th><?php esc_html_e( 'Anno sociale', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_social_year" value="<?php echo esc_attr( get_option( 'ton_reg_social_year' ) ); ?>" /></td></tr>
					<tr><th><?php esc_html_e( 'Quota €', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_membership_fee" value="<?php echo esc_attr( get_option( 'ton_reg_membership_fee' ) ); ?>" /></td></tr>
					<tr><th><?php esc_html_e( 'Beneficiario', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_beneficiary" class="regular-text" value="<?php echo esc_attr( get_option( 'ton_reg_beneficiary' ) ); ?>" /></td></tr>
					<tr><th>IBAN</th><td><input name="ton_reg_iban" class="regular-text" value="<?php echo esc_attr( get_option( 'ton_reg_iban' ) ); ?>" /></td></tr>
					<tr><th><?php esc_html_e( 'Email admin', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_admin_email" type="email" class="regular-text" value="<?php echo esc_attr( get_option( 'ton_reg_admin_email' ) ); ?>" /></td></tr>
					<tr><th><?php esc_html_e( 'Contatto GDPR', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_gdpr_contact" type="email" class="regular-text" value="<?php echo esc_attr( get_option( 'ton_reg_gdpr_contact' ) ); ?>" /></td></tr>
					<tr><th><?php esc_html_e( 'CAPTCHA attivo', 'ton-italia-registration' ); ?></th><td><input type="hidden" name="ton_reg_captcha_enabled" value="0" /><input type="checkbox" name="ton_reg_captcha_enabled" value="1" <?php checked( get_option( 'ton_reg_captcha_enabled' ), '1' ); ?> /></td></tr>
					<tr><th><?php esc_html_e( 'Newsletter obbligatoria', 'ton-italia-registration' ); ?></th><td><input type="hidden" name="ton_reg_newsletter_required" value="0" /><input type="checkbox" name="ton_reg_newsletter_required" value="1" <?php checked( get_option( 'ton_reg_newsletter_required' ), '1' ); ?> /></td></tr>
					<tr><th><?php esc_html_e( 'Elimina utenti alla disinstallazione', 'ton-italia-registration' ); ?></th><td><input type="hidden" name="ton_reg_delete_users_on_uninstall" value="0" /><input type="checkbox" name="ton_reg_delete_users_on_uninstall" value="1" <?php checked( get_option( 'ton_reg_delete_users_on_uninstall' ), '1' ); ?> /></td></tr>
				</table>

				<h2><?php esc_html_e( 'Integrazione Mailchimp', 'ton-italia-registration' ); ?></h2>
				<p class="description"><?php esc_html_e( 'Iscrive automaticamente a Mailchimp i richiedenti che spuntano il consenso newsletter. L\'iscrizione socio non viene mai bloccata da errori Mailchimp.', 'ton-italia-registration' ); ?></p>
				<table class="form-table">
					<tr>
						<th><?php esc_html_e( 'Integrazione attiva', 'ton-italia-registration' ); ?></th>
						<td><input type="hidden" name="ton_reg_mailchimp_enabled" value="0" /><input type="checkbox" name="ton_reg_mailchimp_enabled" value="1" <?php checked( get_option( 'ton_reg_mailchimp_enabled' ), '1' ); ?> /></td>
					</tr>
					<tr>
						<th><label for="ton_reg_mailchimp_api_key"><?php esc_html_e( 'API key', 'ton-italia-registration' ); ?></label></th>
						<td>
							<input type="password" id="ton_reg_mailchimp_api_key" name="ton_reg_mailchimp_api_key" class="regular-text" value="" autocomplete="new-password" placeholder="<?php echo esc_attr( get_option( 'ton_reg_mailchimp_api_key' ) ? '••••••••••••' : '' ); ?>" />
							<p class="description"><?php esc_html_e( 'Mailchimp → Account → Extras → API keys. Lasciare vuoto per non modificare la chiave salvata.', 'ton-italia-registration' ); ?></p>
						</td>
					</tr>
					<tr>
						<th><label for="ton_reg_mailchimp_list_id"><?php esc_html_e( 'List ID (Audience)', 'ton-italia-registration' ); ?></label></th>
						<td>
							<input type="text" id="ton_reg_mailchimp_list_id" name="ton_reg_mailchimp_list_id" class="regular-text" value="<?php echo esc_attr( get_option( 'ton_reg_mailchimp_list_id' ) ); ?>" />
							<p class="description"><?php esc_html_e( 'Audience → Settings → Audience name and defaults → Audience ID.', 'ton-italia-registration' ); ?></p>
						</td>
					</tr>
					<tr>
						<th><label for="ton_reg_mailchimp_tags"><?php esc_html_e( 'Tag', 'ton-italia-registration' ); ?></label></th>
						<td>
							<input type="text" id="ton_reg_mailchimp_tags" name="ton_reg_mailchimp_tags" class="regular-text" value="<?php echo esc_attr( get_option( 'ton_reg_mailchimp_tags', 'Socio TON ITALIA' ) ); ?>" />
							<p class="description"><?php esc_html_e( 'Separati da virgola (max 5).', 'ton-italia-registration' ); ?></p>
						</td>
					</tr>
				</table>

				<table class="form-table">
					<tr><th><?php esc_html_e( 'Rate limit (max tentativi)', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_rate_limit_max" type="number" min="1" value="<?php echo esc_attr( get_option( 'ton_reg_rate_limit_max', '5' ) ); ?>" /></td></tr>
					<tr><th><?php esc_html_e( 'Finestra rate limit (secondi)', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_rate_limit_window" type="number" min="60" value="<?php echo esc_attr( get_option( 'ton_reg_rate_limit_window', '900' ) ); ?>" /></td></tr>
					<?php foreach ( $textareas as $key => $label ) : ?>
					<tr>
						<th><?php echo esc_html( $label ); ?></th>
						<td><textarea name="<?php echo esc_attr( $key ); ?>" rows="6" class="large-text"><?php echo esc_textarea( get_option( $key ) ); ?></textarea></td>
					</tr>
					<?php endforeach; ?>
					<tr><th><?php esc_html_e( 'Oggetto email admin', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_email_admin_subject" class="large-text" value="<?php echo esc_attr( get_option( 'ton_reg_email_admin_subject' ) ); ?>" /></td></tr>
					<tr><th><?php esc_html_e( 'Oggetto email utente', 'ton-italia-registration' ); ?></th><td><input name="ton_reg_email_user_subject" class="large-text" value="<?php echo esc_attr( get_option( 'ton_reg_email_user_subject' ) ); ?>" /></td></tr>
				</table>
				<p class="description"><?php esc_html_e( 'Placeholder email: {nome}, {cognome}, {email}, {codice_fiscale}, {ip}, {login_url}, {gdpr_contact}, {admin_url}', 'ton-italia-registration' ); ?></p>
				<?php submit_button(); ?>
			</form>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ton-reg-mailchimp-test-form">
				<input type="hidden" name="action" value="ton_reg_mailchimp_test" />
				<?php wp_nonce_field( 'ton_reg_mc_test', 'ton_reg_mc_test_nonce' ); ?>
				<h2><?php esc_html_e( 'Test connessione Mailchimp', 'ton-italia-registration' ); ?></h2>
				<p class="description"><?php esc_html_e( 'Verifica API key e List ID senza salvare le altre impostazioni. Lascia vuota la API key per usare quella già salvata.', 'ton-italia-registration' ); ?></p>
				<table class="form-table">
					<tr>
						<th><label for="ton_reg_mailchimp_test_api_key"><?php esc_html_e( 'API key (test)', 'ton-italia-registration' ); ?></label></th>
						<td>
							<input type="password" id="ton_reg_mailchimp_test_api_key" name="ton_reg_mailchimp_api_key" class="regular-text" value="" autocomplete="new-password" />
						</td>
					</tr>
					<tr>
						<th><label for="ton_reg_mailchimp_test_list_id"><?php esc_html_e( 'List ID (test)', 'ton-italia-registration' ); ?></label></th>
						<td>
							<input type="text" id="ton_reg_mailchimp_test_list_id" name="ton_reg_mailchimp_list_id" class="regular-text" value="<?php echo esc_attr( get_option( 'ton_reg_mailchimp_list_id' ) ); ?>" />
						</td>
					</tr>
				</table>
				<?php submit_button( __( 'Test connessione Mailchimp', 'ton-italia-registration' ), 'secondary', 'submit', false ); ?>
			</form>
		</div>
		<?php
	}

	/**
	 * Save registration admin fields.
	 */
	public static function save_registration() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Non autorizzato.', 'ton-italia-registration' ) );
		}

		$id = isset( $_POST['registration_id'] ) ? (int) $_POST['registration_id'] : 0;
		check_admin_referer( 'ton_reg_save_' . $id, 'ton_reg_admin_nonce' );

		TON_Reg_Database::update(
			$id,
			array(
				'status'               => sanitize_text_field( wp_unslash( $_POST['status'] ?? 'pending' ) ),
				'libro_associati_date' => sanitize_text_field( wp_unslash( $_POST['libro_associati_date'] ?? '' ) ) ?: null,
				'admin_notes'          => sanitize_textarea_field( wp_unslash( $_POST['admin_notes'] ?? '' ) ),
			)
		);

		wp_safe_redirect( admin_url( 'admin.php?page=ton-registrations&action=view&id=' . $id . '&updated=1' ) );
		exit;
	}

	/**
	 * GDPR export download.
	 */
	public static function gdpr_export() {
		$id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'ton_reg_gdpr_' . $id ) ) {
			wp_die( esc_html__( 'Non autorizzato.', 'ton-italia-registration' ) );
		}

		$data = TON_Reg_Gdpr::export( $id );
		if ( ! $data ) {
			wp_die( esc_html__( 'Non trovato.', 'ton-italia-registration' ) );
		}

		$format = isset( $_GET['format'] ) ? sanitize_text_field( wp_unslash( $_GET['format'] ) ) : 'json';

		if ( 'csv' === $format ) {
			header( 'Content-Type: text/csv; charset=utf-8' );
			header( 'Content-Disposition: attachment; filename=ton-registration-' . $id . '.csv' );
			$out = fopen( 'php://output', 'w' );
			foreach ( $data as $key => $value ) {
				if ( is_array( $value ) ) {
					$value = wp_json_encode( $value, JSON_UNESCAPED_UNICODE );
				}
				fputcsv( $out, array( (string) $key, (string) $value ) );
			}
			fclose( $out );
			exit;
		}

		header( 'Content-Type: application/json; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=ton-registration-' . $id . '.json' );
		echo wp_json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
		exit;
	}

	/**
	 * GDPR anonymize.
	 */
	public static function gdpr_anonymize() {
		$id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'ton_reg_gdpr_' . $id ) ) {
			wp_die( esc_html__( 'Non autorizzato.', 'ton-italia-registration' ) );
		}

		TON_Reg_Gdpr::anonymize( $id, 'admin action' );
		wp_safe_redirect( admin_url( 'admin.php?page=ton-registrations&action=view&id=' . $id . '&updated=1' ) );
		exit;
	}

	/**
	 * GDPR erase.
	 */
	public static function gdpr_erase() {
		$id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'ton_reg_gdpr_' . $id ) ) {
			wp_die( esc_html__( 'Non autorizzato.', 'ton-italia-registration' ) );
		}

		TON_Reg_Gdpr::erase( $id, 'admin action' );
		wp_safe_redirect( admin_url( 'admin.php?page=ton-registrations&updated=1' ) );
		exit;
	}

	/**
	 * Test Mailchimp API connection from settings.
	 */
	public static function mailchimp_test() {
		$redirect = admin_url( 'admin.php?page=ton-reg-settings' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_safe_redirect(
				add_query_arg(
					'mc_test_error',
					rawurlencode( __( 'Non autorizzato.', 'ton-italia-registration' ) ),
					$redirect
				)
			);
			exit;
		}

		$nonce = isset( $_POST['ton_reg_mc_test_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ton_reg_mc_test_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'ton_reg_mc_test' ) ) {
			wp_safe_redirect(
				add_query_arg(
					'mc_test_error',
					rawurlencode( __( 'Sessione scaduta. Ricarica la pagina e riprova.', 'ton-italia-registration' ) ),
					$redirect
				)
			);
			exit;
		}

		$api_key_post = isset( $_POST['ton_reg_mailchimp_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['ton_reg_mailchimp_api_key'] ) ) : '';
		$list_id_post = isset( $_POST['ton_reg_mailchimp_list_id'] ) ? sanitize_text_field( wp_unslash( $_POST['ton_reg_mailchimp_list_id'] ) ) : '';

		if ( ! class_exists( 'TON_Reg_Mailchimp' ) ) {
			wp_safe_redirect(
				add_query_arg(
					'mc_test_error',
					rawurlencode( __( 'Modulo Mailchimp non caricato. Reinstalla o aggiorna il plugin.', 'ton-italia-registration' ) ),
					$redirect
				)
			);
			exit;
		}

		$result = TON_Reg_Mailchimp::test_connection( $api_key_post, $list_id_post );

		if ( is_wp_error( $result ) ) {
			wp_safe_redirect(
				add_query_arg(
					'mc_test_error',
					rawurlencode( $result->get_error_message() ),
					$redirect
				)
			);
			exit;
		}

		wp_safe_redirect( add_query_arg( 'mc_test_ok', '1', $redirect ) );
		exit;
	}

	/**
	 * Retry Mailchimp sync for a single registration.
	 */
	public static function mailchimp_retry() {
		$id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;

		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'ton_reg_mc_retry_' . $id ) ) {
			wp_die( esc_html__( 'Non autorizzato.', 'ton-italia-registration' ) );
		}

		$row = TON_Reg_Database::get( $id );
		if ( ! $row || empty( $row->consenso_newsletter ) ) {
			wp_safe_redirect(
				add_query_arg(
					'mc_error',
					rawurlencode( __( 'Consenso newsletter assente.', 'ton-italia-registration' ) ),
					admin_url( 'admin.php?page=ton-registrations&action=view&id=' . $id )
				)
			);
			exit;
		}

		if ( ! TON_Reg_Mailchimp::is_configured() ) {
			wp_safe_redirect(
				add_query_arg(
					'mc_error',
					rawurlencode( __( 'Integrazione Mailchimp non configurata.', 'ton-italia-registration' ) ),
					admin_url( 'admin.php?page=ton-registrations&action=view&id=' . $id )
				)
			);
			exit;
		}

		$ok = TON_Reg_Mailchimp::sync_registration( $id );
		$redirect = admin_url( 'admin.php?page=ton-registrations&action=view&id=' . $id );

		if ( $ok ) {
			wp_safe_redirect( add_query_arg( 'mc_ok', '1', $redirect ) );
			exit;
		}

		$row = TON_Reg_Database::get( $id );
		$error = ! empty( $row->mailchimp_error ) ? $row->mailchimp_error : __( 'Sincronizzazione Mailchimp non riuscita.', 'ton-italia-registration' );

		wp_safe_redirect(
			add_query_arg(
				'mc_error',
				rawurlencode( $error ),
				$redirect
			)
		);
		exit;
	}
}
