<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Sabriel_Module_Status extends Sabriel_Module {

	const OPT_ERRORE_EMAIL = 'sabriel_ai_ultimo_errore_email';
	const OPT_PROVA_EMAIL  = 'sabriel_ai_ultima_prova_email';

	public function get_id() {
		return 'status';
	}

	public function register_hooks() {

		add_action( 'admin_menu', [ $this, 'add_submenu' ], 35 );
		add_action( 'admin_menu', [ $this, 'add_warning_badge' ], 99 );

		add_action( 'wp_mail_failed', [ $this, 'registra_errore_email' ] );
	}

	public function registra_errore_email( $errore ) {
		if ( ! is_wp_error( $errore ) ) {
			return;
		}
		$dati = $errore->get_error_data();
		$a    = '';
		if ( is_array( $dati ) && ! empty( $dati['to'] ) ) {
			$a = is_array( $dati['to'] ) ? implode( ', ', $dati['to'] ) : (string) $dati['to'];
		}
		update_option( self::OPT_ERRORE_EMAIL, [
			'quando'  => Sabriel_Helpers::now()->format( 'Y-m-d H:i:s' ),
			'errore'  => mb_substr( (string) $errore->get_error_message(), 0, 500 ),

			'a'       => $a ? preg_replace( '/^.*@/', '…@', $a ) : '',
			'oggetto' => ( is_array( $dati ) && ! empty( $dati['subject'] ) ) ? mb_substr( (string) $dati['subject'], 0, 120 ) : '',
		], false );
	}

	public function add_submenu() {
		add_submenu_page(
			'sabriel-ai',
			__( 'System status', 'sabriel-ai' ),
			__( 'System status', 'sabriel-ai' ),
			'manage_options',
			'sabriel-ai-status',
			[ $this, 'render_page' ]
		);
	}

	private function testo_diagnostica() {

		$out  = str_repeat( '=', 62 ) . "\n";
		$out .= "SABRIEL AI: RIEPILOGO COMPLETO DELL'INSTALLAZIONE\n";
		$out .= str_repeat( '=', 62 ) . "\n";
		$out .= 'Sito:        ' . home_url( '/' ) . "\n";
		$out .= 'Generato il: ' . Sabriel_Helpers::now()->format( 'Y-m-d H:i' ) . ' (' . wp_timezone_string() . ")\n";

		$out .= $this->sezione_diagnostica( '1. AMBIENTE TECNICO', $this->diagnostica_ambiente() );
		$out .= $this->sezione_diagnostica( '2. MOTORE AI', $this->diagnostica_motore() );
		$out .= $this->sezione_diagnostica( '3. LINGUE', $this->diagnostica_lingue() );
		$out .= $this->sezione_diagnostica( "4. IDENTITA' E CONTATTI", $this->diagnostica_identita() );
		$out .= $this->sezione_diagnostica( '5. COMPORTAMENTO DEL BOT', $this->diagnostica_comportamento() );
		$out .= $this->sezione_diagnostica( '6. LISTINO SERVIZI', $this->diagnostica_listino() );
		$out .= $this->sezione_diagnostica( '7. PREZZI, IVA E PAGAMENTI', $this->diagnostica_prezzi() );
		$out .= $this->sezione_diagnostica( '8. ORARI DI APERTURA', $this->diagnostica_orari() );
		$out .= $this->sezione_diagnostica( '9. PAGINE COLLEGATE', $this->diagnostica_pagine() );
		$out .= $this->sezione_diagnostica( '10. WIDGET E ASPETTO', $this->diagnostica_widget() );
		$out .= $this->sezione_diagnostica( '11. LIMITI, STATISTICHE E DATI', $this->diagnostica_limiti() );
		$out .= $this->sezione_diagnostica( '12. INVIO EMAIL', $this->diagnostica_email() );

		return $out;
	}

	private function sezione_diagnostica( $titolo, $righe ) {
		$out = "\n" . $titolo . "\n" . str_repeat( '-', 62 ) . "\n";
		if ( empty( $righe ) ) {
			return $out . "(niente da mostrare)\n";
		}
		$largh = 0;
		foreach ( $righe as $etichetta => $valore ) {
			if ( ! is_int( $etichetta ) ) {
				$largh = max( $largh, strlen( $etichetta ) );
			}
		}
		foreach ( $righe as $etichetta => $valore ) {
			$valore = (string) $valore;
			if ( is_int( $etichetta ) ) {
				$out .= $valore . "\n";
				continue;
			}
			if ( false !== strpos( $valore, "\n" ) || strlen( $valore ) > 60 ) {
				$out .= $etichetta . ":\n";
				foreach ( explode( "\n", $valore ) as $riga ) {
					$out .= '    ' . $riga . "\n";
				}
				continue;
			}
			$out .= str_pad( $etichetta . ':', $largh + 2 ) . $valore . "\n";
		}
		return $out;
	}

	private function valore_diagnostica( $valore, $vuoto = '(non impostato)' ) {
		$valore = trim( (string) $valore );
		return '' === $valore ? $vuoto : $valore;
	}

	private function sino_diagnostica( $valore ) {
		return $valore ? 'si' : 'no';
	}

	private function stato_chiave_diagnostica( $opzione ) {
		$grezza = (string) get_option( $opzione, '' );
		if ( '' === $grezza ) {
			return 'ASSENTE';
		}
		$leggibile = class_exists( 'Sabriel_Crypto' ) ? ( '' !== (string) Sabriel_Crypto::decrypt( $grezza ) ) : true;
		if ( ! $leggibile ) {
			return 'presente ma ILLEGGIBILE';
		}
		return 0 === strpos( $grezza, 'sabc1:' ) ? 'presente e cifrata' : 'presente ma IN CHIARO';
	}

	private function diagnostica_ambiente() {
		$fuori = $this->classi_dichiarate_fuori();
		return [
			'Versione plugin'         => defined( 'SABRIEL_AI_VERSION' ) ? SABRIEL_AI_VERSION : '?',
			'Canale'                  => 'wordpress.org',
			'Versione PHP'            => PHP_VERSION,
			'Versione WordPress'      => get_bloginfo( 'version' ),
			'Tema attivo'             => wp_get_theme()->get( 'Name' ) . ' ' . wp_get_theme()->get( 'Version' ),
			'Fuso orario sito'        => wp_timezone_string(),
			'Multisite'               => $this->sino_diagnostica( is_multisite() ),
			'WooCommerce'             => $this->sino_diagnostica( class_exists( 'WooCommerce' ) ),
			'WP_DEBUG'                => ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? 'acceso' : 'spento',
			'Cifratura disponibile'   => ( class_exists( 'Sabriel_Crypto' ) && Sabriel_Crypto::cifratura_disponibile() ) ? 'si' : 'NO (OpenSSL mancante)',
			'Cron pulizia'            => $this->is_cron_scheduled( Sabriel_Module_Core::CLEANUP_HOOK ) ? 'programmato' : 'NON programmato',
			'Codice fuori dal plugin' => $fuori ? 'SI: ' . implode( ', ', $fuori ) : 'no',
		];
	}

	private function diagnostica_motore() {
		$provider = Sabriel_Module_AI::provider_attivo();
		$righe    = [
			'Motore attivo'  => ( Sabriel_Module_AI::PROVIDERS[ $provider ][0] ?? $provider ) . ' (' . $provider . ')',
			'Modello in uso' => $this->valore_diagnostica( Sabriel_Module_AI::modello_provider( $provider ), '(non determinato)' ),
		];
		foreach ( Sabriel_Module_AI::PROVIDERS as $sab_slug => $sab_info ) {
			$righe[ 'Chiave ' . $sab_slug ] = $this->stato_chiave_diagnostica( $sab_info[1] )
				. ( $sab_slug === $provider ? ' (in uso)' : '' );
		}
		return $righe;
	}

	private function diagnostica_lingue() {
		$locale_utente = get_user_locale();
		return [
			'Locale del sito'     => get_locale(),
			'Locale del pannello' => $locale_utente,
			'Pannello tradotto'   => file_exists( SABRIEL_AI_DIR . 'languages/sabriel-ai-' . $locale_utente . '.mo' ) ? 'si' : 'no (il pannello resta in inglese)',
			'Lingua del bot'      => Sabriel_Module_Settings::bot_lingua_con_rilevamento(),
			'Modalita lingua bot' => Sabriel_Module_Settings::get( 'bot_lingua_fissa' )
				? 'fissa (risponde sempre in quella lingua)'
				: 'adattiva (segue la lingua del cliente)',
		];
	}

	private function diagnostica_identita() {
		return [
			'Nome attivita'     => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'business_name' ) ),
			'Motto'             => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'tagline' ) ),
			'Descrizione'       => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'descrizione_attivita' ) ),
			'Titolare'          => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'founder_name' ) ),
			'Attiva dal'        => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'since_year' ) ),
			'Zona servita'      => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'service_area' ) ),
			'Indirizzo'         => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'address' ) ),
			'Partita IVA'       => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'piva' ) ),
			'Sito web'          => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'website_url' ) ),
			'Email supporto'    => $this->valore_diagnostica(
				Sabriel_Module_Settings::get( 'support_email' ),
				'(vuota: si usa quella amministratore)'
			),
			'Telefono mostrato' => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'phone_display' ) ),
			'WhatsApp'          => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'whatsapp_number' ) ),
		];
	}

	private function diagnostica_comportamento() {
		$tono = trim( (string) Sabriel_Module_Settings::get( 'comportamento_tono' ) );
		return [
			'Wizard iniziale'      => Sabriel_Module_Settings::get( 'wizard_completato' ) ? 'completato' : 'NON completato',
			'Argomenti fuori tema' => Sabriel_Module_Settings::get( 'permetti_fuori_tema' )
				? 'PERMESSI (il bot puo parlare anche di altro)'
				: 'bloccati (impostazione predefinita)',
			'Tono e comportamento scritti dal cliente' => '' === $tono
				? '(campo vuoto: vale solo il comportamento di base del plugin)'
				: $tono,
		];
	}

	private function diagnostica_listino() {
		$righe = Sabriel_Module_Settings::get( 'listino_servizi' );
		if ( is_string( $righe ) ) {
			return [ 'Listino (vecchio formato testo)' => $this->valore_diagnostica( $righe, '(vuoto)' ) ];
		}
		$voci = [];
		foreach ( (array) $righe as $sab_r ) {
			$nome   = trim( (string) ( $sab_r['nome'] ?? '' ) );
			$prezzo = trim( (string) ( $sab_r['prezzo'] ?? '' ) );
			$desc   = trim( (string) ( $sab_r['descrizione'] ?? '' ) );
			if ( '' === $nome && '' === $prezzo && '' === $desc ) {
				continue;
			}
			$voci[] = '- ' . ( '' !== $nome ? $nome : '(senza nome)' )
				. ' = ' . ( '' !== $prezzo ? $prezzo : '(senza prezzo)' )
				. ( '' !== $desc ? "\n    " . $desc : '' );
		}
		if ( ! $voci ) {
			return [ 'Voci nel listino' => '0 (il bot dice che il listino non e disponibile)' ];
		}
		array_unshift( $voci, 'Voci nel listino: ' . count( $voci ) );
		return $voci;
	}

	private function diagnostica_prezzi() {
		$valuta = Sabriel_Module_Settings::valuta();
		$regime = Sabriel_Module_Settings::get( 'prezzi_regime_iva' );
		$paese  = (string) Sabriel_Module_Settings::get( 'aliquota_iva_paese' );
		$paesi  = Sabriel_Module_Settings::IVA_PAESI;
		return [
			'Valuta'               => $valuta['codice'] . ' (' . $valuta['simbolo'] . ', simbolo '
				. ( 'prima' === $valuta['posizione'] ? 'prima' : 'dopo' ) . " dell'importo)",
			'Regime IVA'           => 'inclusa' === $regime ? 'prezzi IVA inclusa' : 'prezzi IVA esclusa',
			'Paese IVA'            => '' === $paese
				? 'nessuno (la riga IVA non viene mostrata)'
				: ( isset( $paesi[ $paese ] ) ? $paesi[ $paese ][0] : $paese ),
			'Aliquota mostrata'    => Sabriel_Module_Settings::get( 'aliquota_iva' )
				? Sabriel_Module_Settings::get( 'aliquota_iva' ) . '%'
				: 'non mostrata',
			'Struttura pagamento'  => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'pagamento_struttura' ), 'non impostata' ),
			'Acconto'              => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'pagamento_acconto_pct' ), 'non impostato' ),
			'Pagamento intermedio' => $this->valore_diagnostica( Sabriel_Module_Settings::get( 'pagamento_meta_pct' ), 'non impostato' ),
			'Pagamento a rate'     => Sabriel_Module_Settings::get( 'rate_abilitate' )
				? 'ATTIVO sopra ' . $this->valore_diagnostica( Sabriel_Module_Settings::get( 'rate_soglia' ), '(soglia non impostata)' )
				: 'disattivo',
		];
	}

	private function diagnostica_orari() {
		if ( ! Sabriel_Orari::orari_sono_configurati() ) {
			return [ 'Orari' => 'non configurati (il bot non sa dire se siete aperti)' ];
		}
		$nomi  = [
			1 => 'Lunedi',
			2 => 'Martedi',
			3 => 'Mercoledi',
			4 => 'Giovedi',
			5 => 'Venerdi',
			6 => 'Sabato',
			7 => 'Domenica',
		];
		$righe = [];
		foreach ( $nomi as $sab_dow => $sab_nome ) {
			$g = Sabriel_Orari::orari_del_giorno( $sab_dow );
			if ( empty( $g['aperto'] ) || empty( $g['fasce'] ) ) {
				$righe[ $sab_nome ] = 'chiuso';
				continue;
			}
			$fasce = [];
			foreach ( $g['fasce'] as $sab_f ) {
				$fasce[] = $sab_f['dalle'] . ' - ' . $sab_f['alle'];
			}
			$righe[ $sab_nome ] = implode( ', ', $fasce );
		}
		$righe['Aperto in questo momento'] = $this->sino_diagnostica( Sabriel_Orari::aperto_adesso() );
		return $righe;
	}

	/**
	 * Stessa guardia di campo_riga() in Impostazioni: un campo che e' diventato
	 * un ELENCO, cast a stringa, da' «Array» e un avviso PHP dentro la pagina
	 * Stato — proprio quella che si copia e si manda all'assistenza.
	 */
	private static function campo_riga_diag( $riga, $campo ) {
		if ( ! is_array( $riga ) || ! isset( $riga[ $campo ] ) || ! is_scalar( $riga[ $campo ] ) ) {
			return '';
		}
		return trim( (string) $riga[ $campo ] );
	}

	private function diagnostica_pagine() {
		$righe = Sabriel_Module_Settings::get( 'pagine_link' );
		if ( is_string( $righe ) ) {
			return [ 'Pagine (vecchio formato testo)' => $this->valore_diagnostica( $righe, '(vuoto)' ) ];
		}
		$voci = [];
		foreach ( (array) $righe as $sab_r ) {
			$etichetta = self::campo_riga_diag( $sab_r, 'etichetta' );
			$url       = self::campo_riga_diag( $sab_r, 'url' );
			if ( '' === $etichetta && '' === $url ) {
				continue;
			}
			$voci[] = '- ' . ( '' !== $etichetta ? $etichetta : '(senza etichetta)' )
				. ': ' . ( '' !== $url ? $url : '(senza link)' );
		}
		if ( ! $voci ) {
			return [ 'Pagine collegate' => 'nessuna' ];
		}
		array_unshift( $voci, 'Pagine collegate: ' . count( $voci ) );
		return $voci;
	}

	private function diagnostica_widget() {
		$righe = [
			'Nome del bot' => $this->valore_diagnostica( Sabriel_Module_Branding::get( 'bot_name' ) ),
			'Logo'         => $this->valore_diagnostica( Sabriel_Module_Branding::get( 'logo_url' ), "nessuno (si usa l'iniziale del nome)" ),
		];
		$cambiati = [];
		foreach ( Sabriel_Module_Branding::FIELDS as $sab_campo => $sab_predefinito ) {
			if ( 'bot_name' === $sab_campo || 'logo_url' === $sab_campo ) {
				continue;
			}
			$valore = (string) Sabriel_Module_Branding::get( $sab_campo );
			if ( $valore !== (string) $sab_predefinito ) {
				$cambiati[] = $sab_campo . ' = ' . $valore . ' (predefinito ' . $sab_predefinito . ')';
			}
		}
		$righe['Colori cambiati'] = $cambiati
			? implode( "\n", $cambiati )
			: 'nessuno, tutti ai valori predefiniti';
		return $righe;
	}

	private function diagnostica_limiti() {
		$traffico = Sabriel_Module_Traffico::statistiche( 7 );
		$scelto   = (int) Sabriel_Base::get( 'limite_msg_giornalieri' );
		return [
			'Limite messaggi per visitatore / 24h' => Sabriel_Module_Chat::limite_configurato()
				. ( $scelto > 0 ? ' (scelto dal cliente)' : ' (predefinito)' ),
			'Statistiche di visita'                => Sabriel_Module_Settings::get( 'statistiche_attive' ) ? 'attive' : 'disattivate',
			'Visite ultimi 7 giorni'               => $traffico['ha_dati'] ? (string) $traffico['visite_totali'] : 'nessun dato',
			'Chat aperte ultimi 7 giorni'          => (string) $traffico['chat_aperte'],
			'Blocchi di sicurezza ultimi 7 giorni' => (string) $traffico['blocchi_sicurezza'],
			'Elimina dati alla disinstallazione'   => $this->sino_diagnostica( Sabriel_Base::get( 'elimina_dati_alla_disinstallazione' ) ),
		];
	}

	private function diagnostica_email() {
		return [
			'Email amministratore'  => (string) get_option( 'admin_email' ),
			'Ultimo invio fallito'  => $this->riga_diagnostica_email(),
			'Ultima prova di invio' => $this->riga_diagnostica_prova(),
		];
	}

	private function riga_diagnostica_email() {
		$e = get_option( self::OPT_ERRORE_EMAIL );
		if ( empty( $e ) ) {
			return 'nessuno registrato';
		}
		$out = ( $e['quando'] ?? '?' );
		if ( ! empty( $e['errore'] ) ) {
			$out .= ': ' . $e['errore'];
		}
		return $out;
	}

	private function riga_diagnostica_prova() {
		$p = get_option( self::OPT_PROVA_EMAIL );
		if ( empty( $p ) ) {
			return 'mai fatta';
		}
		$out = ( ! empty( $p['ok'] ) ? 'riuscita' : 'FALLITA' ) . ' il ' . ( $p['quando'] ?? '?' );
		if ( empty( $p['ok'] ) && ! empty( $p['errore'] ) ) {
			$out .= ': ' . $p['errore'];
		}
		return $out;
	}

	private function gestisci_segnalazione() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return [ 'ok' => false, 'messaggio' => __( 'Permission denied.', 'sabriel-ai' ) ];
		}

		check_admin_referer( 'sab_feedback_action', 'sab_feedback_nonce' );

		$rl_key = 'sabriel_ai_fb_rl_' . get_current_user_id();
		if ( (int) get_transient( $rl_key ) >= 5 ) {
			return [
				'ok'        => false,
				'messaggio' => sprintf(
					/* translators: %s: support email address */
					__( 'You\'ve already sent several reports. Try again in an hour, or write to us directly at %s', 'sabriel-ai' ),
					self::email_segnalazioni()
				),
			];
		}

		if ( empty( $_POST['sab_fb_conferma'] ) ) {
			return [ 'ok' => false, 'messaggio' => __( 'Check the confirmation before sending.', 'sabriel-ai' ) ];
		}
		$testo = sanitize_textarea_field( wp_unslash( $_POST['sab_fb_testo'] ?? '' ) );
		$email = Sabriel_Helpers::email_pulita( wp_unslash( $_POST['sab_fb_email'] ?? '' ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- email_pulita() applica sanitize_email().
		if ( '' === trim( $testo ) ) {
			return [ 'ok' => false, 'messaggio' => __( 'Describe what happened before sending.', 'sabriel-ai' ) ];
		}
		if ( ! $email || ! is_email( $email ) ) {
			return [ 'ok' => false, 'messaggio' => __( 'A valid email address is needed so we can reply to you.', 'sabriel-ai' ) ];
		}
		$testo = mb_substr( $testo, 0, 5000 );

		$allegati = [];
		$tmp_da_pulire = '';
		$errore_file = isset( $_FILES['sab_fb_img']['error'] ) ? (int) $_FILES['sab_fb_img']['error'] : UPLOAD_ERR_NO_FILE;
		if ( UPLOAD_ERR_OK === $errore_file && ! empty( $_FILES['sab_fb_img']['tmp_name'] ) ) {
			$tmp  = sanitize_text_field( wp_unslash( $_FILES['sab_fb_img']['tmp_name'] ) );
			$size = isset( $_FILES['sab_fb_img']['size'] ) ? (int) $_FILES['sab_fb_img']['size'] : 0;
			if ( $size > 5 * 1024 * 1024 ) {
				return [ 'ok' => false, 'messaggio' => __( 'The screenshot exceeds 5 MB. Crop or shrink it and try again.', 'sabriel-ai' ) ];
			}

			$info    = @getimagesize( $tmp );
			$mime_ok = [ 'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp' ];
			if ( ! $info || ! isset( $mime_ok[ $info['mime'] ] ) ) {
				return [ 'ok' => false, 'messaggio' => __( 'The screenshot doesn\'t seem to be a valid image (we accept PNG, JPG or WebP).', 'sabriel-ai' ) ];
			}

			if ( ! function_exists( 'wp_handle_upload' ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
			}
			$caricato = wp_handle_upload(
				$_FILES['sab_fb_img'], // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- wp_handle_upload valida e ripulisce il file per conto suo.
				[
					'test_form' => false,
					'mimes'     => [ 'png' => 'image/png', 'jpg|jpeg' => 'image/jpeg', 'webp' => 'image/webp' ],
				]
			);
			if ( is_array( $caricato ) && empty( $caricato['error'] ) && ! empty( $caricato['file'] ) ) {
				$allegati[]    = $caricato['file'];
				$tmp_da_pulire = $caricato['file'];
			}
		}

		$corpo  = "SEGNALAZIONE DA UN'INSTALLAZIONE DI SABRIEL AI\n";
		$corpo .= str_repeat( '=', 46 ) . "\n\n";
		$corpo .= "Da:   " . $email . "\n";
		$corpo .= "Sito: " . home_url( '/' ) . "\n\n";
		$corpo .= "PROBLEMA SEGNALATO\n" . str_repeat( '-', 46 ) . "\n" . $testo . "\n\n";
		$corpo .= $this->testo_diagnostica();

		$oggetto = 'Sabriel AI: segnalazione da ' . wp_parse_url( home_url(), PHP_URL_HOST );
		$inviata = wp_mail( self::email_segnalazioni(), $oggetto, $corpo, [ 'Reply-To: ' . $email ], $allegati );

		if ( $tmp_da_pulire && file_exists( $tmp_da_pulire ) ) {
			wp_delete_file( $tmp_da_pulire );
		}

		if ( ! $inviata ) {

			return [
				'ok'        => false,
				'messaggio' => sprintf(

					/* translators: %s: error message returned by WordPress */ __( 'This site couldn\'t send the email (often it\'s WordPress\'s SMTP configuration, not the plugin). The report was NOT sent: write to us directly at %s. You can copy the technical summary with the button above.', 'sabriel-ai' ),
					self::email_segnalazioni()
				),
			];
		}
		set_transient( $rl_key, (int) get_transient( $rl_key ) + 1, HOUR_IN_SECONDS );
		return [ 'ok' => true, 'messaggio' => __( 'Report sent, thank you. We\'ll reply to the address you provided.', 'sabriel-ai' ) ];
	}

	private function gestisci_prova_email() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return [ 'ok' => false, 'messaggio' => __( 'Permission denied.', 'sabriel-ai' ) ];
		}

		$rl = 'sabriel_ai_prova_mail_' . get_current_user_id();
		if ( (int) get_transient( $rl ) >= 5 ) {
			return [ 'ok' => false, 'messaggio' => __( 'You\'ve already run several tests. Try again in an hour.', 'sabriel-ai' ) ];
		}
		set_transient( $rl, (int) get_transient( $rl ) + 1, HOUR_IN_SECONDS );

		$destinatario = get_option( 'admin_email' );
		if ( ! $destinatario || ! is_email( $destinatario ) ) {
			return [ 'ok' => false, 'messaggio' => __( 'This site doesn\'t have a valid administrator email address (Settings → General).', 'sabriel-ai' ) ];
		}

		$errore_vero = '';
		$cattura = function ( $err ) use ( &$errore_vero ) {
			if ( is_wp_error( $err ) ) {
				$errore_vero = (string) $err->get_error_message();
			}
		};
		add_action( 'wp_mail_failed', $cattura, 1 );

		$sito    = wp_parse_url( home_url(), PHP_URL_HOST );
		$oggetto = sprintf(

			/* translators: %s: site domain name */
			__( 'Sabriel AI: send test from %s', 'sabriel-ai' ),
			$sito
		);
		$corpo = __( "This is a test email sent from the Sabriel AI panel.\n\nIf you are reading it, your site can send email: the chat summaries and the messages visitors leave you will reach their destination.\n\nThere is no need to reply to this message.", 'sabriel-ai' );

		$inviata = wp_mail( $destinatario, $oggetto, $corpo );
		remove_action( 'wp_mail_failed', $cattura, 1 );

		$esito = [
			'quando'  => Sabriel_Helpers::now()->format( 'Y-m-d H:i:s' ),
			'ok'      => (bool) $inviata,
			'errore'  => mb_substr( $errore_vero, 0, 500 ),
		];
		update_option( self::OPT_PROVA_EMAIL, $esito, false );

		if ( ! $inviata ) {
			return [
				'ok'        => false,
				'messaggio' => $errore_vero
					? sprintf(

						/* translators: %1$s: destination email address; %2$s: error message from the mail server */
						__( 'This site CANNOT send email. Test failed to %1$s. The mail server replied: “%2$s”. This isn\'t a plugin problem: it\'s WordPress\'s email sending configuration. The most common fix is to install an SMTP plugin (e.g. WP Mail SMTP) and connect it to your domain\'s mailbox, or ask your host why sending is blocked.', 'sabriel-ai' ),
						$destinatario,
						$errore_vero
					)
					: sprintf(

						/* translators: %s: destination email address */
						__( 'This site CANNOT send email (test failed to %s), and it didn\'t even return a reason. That usually means sending is disabled by the host. The most common fix is to install an SMTP plugin (e.g. WP Mail SMTP) and connect it to your domain\'s mailbox.', 'sabriel-ai' ),
						$destinatario
					),
			];
		}
		return [
			'ok'        => true,

			'messaggio' => sprintf(

				/* translators: %s: destination email address */
				__( 'Test email sent to %s. Check that mailbox (spam too): if it doesn\'t arrive within a few minutes, your site hands off to the mail server but something discards it later. Usually SPF/DKIM are missing, and you need an SMTP plugin connected to your domain\'s mailbox.', 'sabriel-ai' ),
				$destinatario
			),
		];
	}

	public function has_critical_issues() {
		$campo   = Sabriel_Module_AI::PROVIDERS[ Sabriel_Module_AI::provider_attivo() ][1];
		$grezza  = (string) get_option( $campo, '' );
		if ( '' === $grezza ) {
			return true;

		}
		if ( class_exists( 'Sabriel_Crypto' ) && '' === (string) Sabriel_Crypto::decrypt( $grezza ) ) {
			return true;

		}
		return false;
	}

	public function add_warning_badge() {
		global $submenu;

		if ( ! isset( $submenu['sabriel-ai'] ) || ! $this->has_critical_issues() ) {
			return;
		}
		foreach ( $submenu['sabriel-ai'] as $key => $item ) {
			if ( isset( $item[2] ) && 'sabriel-ai-status' === $item[2] ) {
				// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- si aggiunge il pallino alla sola voce di questo plugin.
				$submenu['sabriel-ai'][ $key ][0] .= ' <span style="display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;background:#d63638;color:#fff;border-radius:50%;font-size:11px;font-weight:800;margin-left:4px">!</span>';
			}
		}
	}

	private function is_cron_scheduled( $hook ) {
		return (bool) wp_next_scheduled( $hook );
	}

	private function classi_dichiarate_fuori() {
		$fuori = [];
		$mie   = [ 'Sabriel_Base', 'Sabriel_Helpers', 'Sabriel_Crypto', 'Sabriel_Orari', 'Sabriel_Loader', 'Sabriel_Module' ];
		foreach ( get_declared_classes() as $classe ) {
			if ( 0 !== strpos( $classe, 'Sabriel_' ) && ! in_array( $classe, $mie, true ) ) {
				continue;
			}
			try {
				$rc  = new ReflectionClass( $classe );
				$src = $rc->getFileName();
			} catch ( Exception $e ) {
				continue;
			}
			if ( $src && 0 !== strpos( wp_normalize_path( $src ), wp_normalize_path( SABRIEL_AI_DIR ) ) ) {
				$fuori[] = $classe;
			}
		}
		return $fuori;
	}

	const EMAIL_SEGNALAZIONI = 'supporto@sabrielagency.com';

	const OPT_BACKUP_PRE_IMPORT = 'sabriel_ai_config_prima_import';

	public static function email_segnalazioni() {
		$email = apply_filters( 'sabriel_ai_email_segnalazioni', self::EMAIL_SEGNALAZIONI );
		return is_email( $email ) ? $email : self::EMAIL_SEGNALAZIONI;
	}

	private static function sanitizza_import( $in ) {
		if ( ! is_array( $in ) ) {
			return [];
		}
		$defaults = Sabriel_Base::get_defaults();
		/*
		 * ⚠ DELL'ASPETTO SI IMPORTA SOLO QUELLO CHE QUESTA EDIZIONE SA GESTIRE.
		 * Un file esportato dall'edizione completa contiene tutti i colori del widget,
		 * anche i venticinque che qui non hanno nessun comando. Scrivendoli tutti,
		 * il proprietario si ritrovava colori che vedeva ma non poteva piu' cambiare
		 * da nessuna parte, e bastava far girare un file per avere qui dentro una
		 * personalizzazione che questa edizione non offre. I valori gia' presenti sul
		 * sito NON si toccano: si salta la chiave e basta.
		 */
		$sab_aspetto = class_exists( 'Sabriel_Module_Branding' ) ? Sabriel_Module_Branding::FIELDS : [];
		$sab_gestiti = class_exists( 'Sabriel_Module_Branding' ) ? Sabriel_Module_Branding::CAMPI_GESTITI : [];
		$out      = [];
		foreach ( $defaults as $chiave => $def ) {
			if ( ! array_key_exists( $chiave, $in ) ) {
				continue;
			}
			if ( array_key_exists( $chiave, $sab_aspetto ) && ! in_array( $chiave, $sab_gestiti, true ) ) {
				continue;
			}
			$val = $in[ $chiave ];
			if ( is_bool( $def ) ) {
				$out[ $chiave ] = (bool) $val;
			} elseif ( is_int( $def ) ) {
				$out[ $chiave ] = (int) $val;
			} elseif ( is_float( $def ) ) {
				$out[ $chiave ] = (float) $val;
			} elseif ( is_array( $def ) ) {
				$out[ $chiave ] = is_array( $val ) ? self::sanitizza_ricorsivo( $val ) : $def;
			} else {

				$sab_multiriga = [ 'comportamento_tono', 'descrizione_attivita' ];
				$sab_testo = is_scalar( $val )
					? ( in_array( $chiave, $sab_multiriga, true )
						? sanitize_textarea_field( (string) $val )
						: sanitize_text_field( (string) $val ) )
					: $def;
				if ( is_string( $sab_testo ) && class_exists( 'Sabriel_Module_Settings' ) && strlen( $sab_testo ) > 5000 ) {
					$sab_testo = function_exists( 'mb_substr' ) ? mb_substr( $sab_testo, 0, 5000 ) : substr( $sab_testo, 0, 5000 );
				}
				$out[ $chiave ] = $sab_testo;
			}
		}
		return $out;
	}

	private static function sanitizza_ricorsivo( $arr ) {
		$out = [];
		foreach ( (array) $arr as $k => $v ) {
			$ck = is_int( $k ) ? $k : sanitize_text_field( (string) $k );
			if ( is_array( $v ) ) {
				$out[ $ck ] = self::sanitizza_ricorsivo( $v );
			} elseif ( is_bool( $v ) ) {
				$out[ $ck ] = $v;
			} elseif ( is_scalar( $v ) ) {
				$out[ $ck ] = sanitize_textarea_field( (string) $v );
			}
		}
		return $out;
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Access denied', 'sabriel-ai' ) );
		}

		$sab_fb_msg = '';
		$sab_fb_err = '';
		if ( Sabriel_Helpers::e_una_post() && isset( $_POST['sab_feedback_nonce'] ) && check_admin_referer( 'sab_feedback_action', 'sab_feedback_nonce' ) ) {
			$sab_fb_msg_res = $this->gestisci_segnalazione();
			$sab_fb_msg     = $sab_fb_msg_res['ok'] ? $sab_fb_msg_res['messaggio'] : '';
			$sab_fb_err     = $sab_fb_msg_res['ok'] ? '' : $sab_fb_msg_res['messaggio'];
		}

		$sab_mail_msg = '';
		$sab_mail_err = '';
		if ( Sabriel_Helpers::e_una_post() && isset( $_POST['sab_prova_mail_nonce'] ) && check_admin_referer( 'sab_prova_mail_action', 'sab_prova_mail_nonce' ) ) {
			$sab_mail_res = $this->gestisci_prova_email();
			$sab_mail_msg = $sab_mail_res['ok'] ? $sab_mail_res['messaggio'] : '';
			$sab_mail_err = $sab_mail_res['ok'] ? '' : $sab_mail_res['messaggio'];
		}

		$import_msg = '';
		$import_err = '';
		if ( Sabriel_Helpers::e_una_post() && isset( $_POST['sab_import_nonce'] ) && check_admin_referer( 'sab_import_action', 'sab_import_nonce' ) ) {
			$sab_tmp_import = isset( $_FILES['sab_import_file']['tmp_name'] ) ? sanitize_text_field( $_FILES['sab_import_file']['tmp_name'] ) : '';

			$sab_err_import  = isset( $_FILES['sab_import_file']['error'] ) ? (int) $_FILES['sab_import_file']['error'] : UPLOAD_ERR_NO_FILE;
			$sab_size_import = isset( $_FILES['sab_import_file']['size'] ) ? (int) $_FILES['sab_import_file']['size'] : 0;
			if ( '' === $sab_tmp_import || UPLOAD_ERR_OK !== $sab_err_import || ! is_uploaded_file( $sab_tmp_import ) ) {
				$import_err = __( 'No valid file uploaded.', 'sabriel-ai' );
			} elseif ( $sab_size_import > 2 * 1024 * 1024 ) {

				$import_err = __( 'The file is too large to be a configuration for this plugin.', 'sabriel-ai' );
			} else {
				$contenuto = file_get_contents( $sab_tmp_import ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- file appena caricato e verificato con is_uploaded_file().
				$decodificato = json_decode( $contenuto, true );
				if ( ! is_array( $decodificato ) || json_last_error() !== JSON_ERROR_NONE ) {
					$import_err = __( 'The file isn\'t a valid configuration (unrecognized JSON).', 'sabriel-ai' );
				} else {

					$pulito = self::sanitizza_import( $decodificato );
					if ( empty( $pulito ) ) {
						$import_err = __( 'This file contains no Sabriel AI settings, so it was not imported: your configuration has stayed as it was. Check that you picked the right file (it must be the one created by the «Export configuration» button).', 'sabriel-ai' );
					} else {
						$precedente = get_option( Sabriel_Base::OPTION_KEY, [] );
						update_option( self::OPT_BACKUP_PRE_IMPORT, [
							'quando' => Sabriel_Helpers::now()->format( 'Y-m-d H:i:s' ),
							'dati'   => is_array( $precedente ) ? $precedente : [],
						], false );
						update_option( Sabriel_Base::OPTION_KEY, $pulito );
						Sabriel_Base::svuota_cache();
						$import_msg = sprintf(
							/* translators: %d: number of settings imported from the file */
							__( 'Configuration imported: %d settings applied. The previous configuration has been set aside, you can restore it with the button below. Check the main pages again to make sure everything is as expected.', 'sabriel-ai' ),
							count( $pulito )
						);
					}
				}
			}
		}

		if ( Sabriel_Helpers::e_una_post() && isset( $_POST['sab_ripristina_nonce'] ) && check_admin_referer( 'sab_ripristina_action', 'sab_ripristina_nonce' ) ) {
			$copia = get_option( self::OPT_BACKUP_PRE_IMPORT );
			if ( empty( $copia['dati'] ) || ! is_array( $copia['dati'] ) ) {
				$import_err = __( 'There is no previous configuration to restore.', 'sabriel-ai' );
			} else {
				update_option( Sabriel_Base::OPTION_KEY, $copia['dati'] );
				Sabriel_Base::svuota_cache();
				delete_option( self::OPT_BACKUP_PRE_IMPORT );
				$import_msg = __( 'Previous configuration restored.', 'sabriel-ai' );
			}
		}

		$cron_pulizia   = $this->is_cron_scheduled( 'sabriel_ai_pulizia_transient' );
		$provider_attivo = Sabriel_Module_AI::provider_attivo();
		$provider_nome   = Sabriel_Module_AI::PROVIDERS[ $provider_attivo ][0];
		$apikey_grezza   = get_option( Sabriel_Module_AI::PROVIDERS[ $provider_attivo ][1], '' );

		$apikey_decifrata = class_exists( 'Sabriel_Crypto' ) ? Sabriel_Crypto::decrypt( $apikey_grezza ) : $apikey_grezza;
		$apikey_presente  = ( '' !== (string) $apikey_grezza );
		$apikey_salvata   = ( '' !== (string) $apikey_decifrata );

		$apikey_cifrata  = ( 0 === strpos( (string) $apikey_grezza, 'sabc1:' ) ) && $apikey_salvata;

		$apikey_illeggibile = $apikey_presente && ! $apikey_salvata;
		$cifratura_disponibile = class_exists( 'Sabriel_Crypto' ) ? Sabriel_Crypto::cifratura_disponibile() : false;
		$business_name  = Sabriel_Module_Settings::get( 'business_name' );
		$bot_name       = Sabriel_Module_Branding::get( 'bot_name' );
		$aspetto_personalizzato = ( Sabriel_Module_Branding::get( 'primary_color' ) !== Sabriel_Module_Branding::FIELDS['primary_color'] )
			|| ( Sabriel_Module_Branding::get( 'secondary_color' ) !== Sabriel_Module_Branding::FIELDS['secondary_color'] )
			|| ( Sabriel_Module_Branding::get( 'bg_color' ) !== Sabriel_Module_Branding::FIELDS['bg_color'] )
			|| ( Sabriel_Module_Branding::get( 'logo_url' ) !== '' )
			|| ( Sabriel_Module_Branding::get( 'bot_name' ) !== Sabriel_Module_Branding::FIELDS['bot_name'] );

		$sab_listino_utile = ( '' !== trim( (string) Sabriel_Module_Settings::listino_come_testo() ) );
		$identita_bot_personalizzata = ( '' !== trim( (string) Sabriel_Module_Settings::get( 'business_name' ) ) )
			&& $sab_listino_utile;
		$comportamento_impostato = ( '' !== trim( (string) Sabriel_Module_Settings::get( 'comportamento_tono' ) ) );
		$config_essenziale_ok    = $identita_bot_personalizzata && $comportamento_impostato;
		?>
		<div class="wrap">
			<h1 style="display:flex;align-items:center;gap:8px"><?php esc_html_e( 'System status', 'sabriel-ai' ); ?></h1>
			<p style="color:#666;max-width:640px"><?php esc_html_e( 'A quick look at how the plugin is doing: version, environment, and automatic checks on what needs to work for everything else to work.', 'sabriel-ai' ); ?></p>

			<h2 style="margin-top:28px;font-size:16px"><?php esc_html_e( 'Information', 'sabriel-ai' ); ?></h2>
			<table class="widefat striped" style="max-width:560px">
				<tbody>
					<tr><td><?php esc_html_e( 'Plugin version', 'sabriel-ai' ); ?></td><td><?php echo esc_html( SABRIEL_AI_VERSION ); ?></td></tr>
					<tr><td><?php esc_html_e( 'PHP version', 'sabriel-ai' ); ?></td><td><?php echo esc_html( PHP_VERSION ); ?></td></tr>
					<tr><td><?php esc_html_e( 'WordPress version', 'sabriel-ai' ); ?></td><td><?php echo esc_html( get_bloginfo( 'version' ) ); ?></td></tr>
					<tr><td><?php esc_html_e( 'Site timezone', 'sabriel-ai' ); ?></td><td><?php echo esc_html( wp_timezone_string() ); ?></td></tr>
					<tr><td><?php esc_html_e( 'WooCommerce detected', 'sabriel-ai' ); ?></td><td><?php echo class_exists( 'WooCommerce' ) ? esc_html__( 'yes', 'sabriel-ai' ) : esc_html__( 'no', 'sabriel-ai' ); ?></td></tr>
					<tr><td><?php esc_html_e( 'Business name set', 'sabriel-ai' ); ?></td><td><?php echo esc_html( $business_name ); ?></td></tr>
					<tr><td><?php esc_html_e( 'Bot name', 'sabriel-ai' ); ?></td><td><?php echo esc_html( $bot_name ); ?></td></tr>
				<?php $sab_traffico_stato = Sabriel_Module_Traffico::statistiche( 7 ); ?>
				<tr><td><?php esc_html_e( 'Site traffic tracking', 'sabriel-ai' ); ?></td><td><?php echo $sab_traffico_stato['ha_dati'] ? esc_html( sprintf( /* translators: %d: number of visits */ __( 'active, %d visits in the last 7 days', 'sabriel-ai' ), $sab_traffico_stato['visite_totali'] ) ) : esc_html__( 'active, no data recorded yet', 'sabriel-ai' ); ?></td></tr>
				</tbody>
			</table>

			<h2 style="margin-top:28px;font-size:16px"><?php esc_html_e( 'Automatic checks', 'sabriel-ai' ); ?></h2>
			<table class="widefat striped" style="max-width:560px">
				<tbody>
					<tr>
						<td><?php esc_html_e( 'Automatic cleanup of expired data', 'sabriel-ai' ); ?></td>
						<td><?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $cron_pulizia, $cron_pulizia ? __( 'Scheduled (default)', 'sabriel-ai' ) : __( 'Not scheduled', 'sabriel-ai' ) ); ?></td>
					</tr>
					<tr>
						<td><?php esc_html_e( 'Active AI engine', 'sabriel-ai' ); ?></td>
						<td><?php echo esc_html( $provider_nome ); ?></td>
					</tr>
					<tr>
						<td><?php echo esc_html( sprintf( /* translators: %s: status of the API key */ __( '%s API key', 'sabriel-ai' ), $provider_nome ) ); ?></td>
						<td>
							<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $apikey_salvata, $apikey_salvata ? __( 'Present', 'sabriel-ai' ) : ( $apikey_illeggibile ? __( 'Present but unreadable', 'sabriel-ai' ) : __( 'Missing', 'sabriel-ai' ) ) ); ?>
							<?php if ( $apikey_illeggibile ) : ?>
								<span style="color:#b45309;font-size:12px;margin-left:6px"><?php esc_html_e( '(the key is saved but can no longer be decrypted: this usually happens after changing the security keys in wp-config.php or migrating the site. The bot can\'t work until you re-enter it under AI Engine.)', 'sabriel-ai' ); ?></span>
							<?php endif; ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=sabriel-ai-motore' ) ); ?>" style="margin-left:8px;font-size:12.5px"><?php esc_html_e( 'Go to AI Engine →', 'sabriel-ai' ); ?></a>
						</td>
					</tr>
					<?php if ( $apikey_salvata ) : ?>
					<tr>
						<td><?php esc_html_e( 'Key saved encrypted', 'sabriel-ai' ); ?></td>
						<td>
							<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $apikey_cifrata, $apikey_cifrata ? __( 'Yes, encrypted', 'sabriel-ai' ) : __( 'No, still in plain text', 'sabriel-ai' ) ); ?>
							<?php

							if ( ! $apikey_cifrata ) :
								if ( ! $cifratura_disponibile ) :
									?>
									<span style="color:#b91c1c;font-size:12px;margin-left:6px;font-weight:600"><?php esc_html_e( '(this server cannot encrypt: the key stays in plain text in the database and will not encrypt itself. See the «Encryption available» row below.)', 'sabriel-ai' ); ?></span>
									<?php
								else :
									?>
									<span style="color:#888;font-size:12px;margin-left:6px"><?php esc_html_e( '(it still works: it will encrypt itself on the next save from AI Engine)', 'sabriel-ai' ); ?></span>
									<?php
								endif;
							endif;
							?>
						</td>
					</tr>
					<?php endif; ?>
					<tr>
						<td><?php esc_html_e( 'Key encryption available', 'sabriel-ai' ); ?></td>
						<td>
							<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $cifratura_disponibile, $cifratura_disponibile ? __( 'Yes (OpenSSL active)', 'sabriel-ai' ) : __( 'No: the API keys stay in plain text', 'sabriel-ai' ) ); ?>
							<?php if ( ! $cifratura_disponibile ) : ?>
								<p style="background:#fef2f2;border:1px solid #f5a3a3;color:#b91c1c;font-size:12px;padding:8px 11px;border-radius:6px;margin:8px 0 0;max-width:480px">
									<?php esc_html_e( 'This server is missing the PHP OpenSSL extension, so the AI engine keys are saved in the database exactly as they are, unprotected. Anyone able to read the database (a backup left in the wrong place, another plugin, a stolen login) sees them in plain text and can use them at your expense. Ask your host to enable the PHP OpenSSL extension: as soon as it is active, save the key again from AI Engine and it will be protected.', 'sabriel-ai' ); ?>
								</p>
							<?php endif; ?>
						</td>
					</tr>
					<?php

					$sab_email_supporto = trim( (string) Sabriel_Module_Settings::get( 'support_email' ) );
					?>
					<tr>
						<td><?php esc_html_e( 'Support email', 'sabriel-ai' ); ?></td>
						<td>
							<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( '' !== $sab_email_supporto, '' !== $sab_email_supporto ? $sab_email_supporto : (string) get_option( 'admin_email' ) ); ?>
							<?php if ( '' === $sab_email_supporto ) : ?>
								<p style="background:#fffbeb;border:1px solid #f59e0b;color:#92400e;font-size:12px;padding:8px 11px;border-radius:6px;margin:8px 0 0;max-width:520px">
									<?php esc_html_e( 'You have not set a support email: in its place the plugin uses the WordPress administrator\'s one shown above, and publishes it in the chat, in the emails it sends to customers and in the code of every page of the site. Set one of your own in the Settings.', 'sabriel-ai' ); ?>
								</p>
							<?php endif; ?>
						</td>
					</tr>
					<?php
					$sab_classi_fuori = $this->classi_dichiarate_fuori();
					if ( $sab_classi_fuori ) :
						?>
						<tr>
							<td><?php esc_html_e( 'Duplicate copies of the plugin', 'sabriel-ai' ); ?></td>
							<td>
								<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( false, __( 'Sabriel AI code found outside the plugin', 'sabriel-ai' ) ); ?>
								<p style="background:#fef2f2;border:1px solid #f5a3a3;color:#b91c1c;font-size:12px;padding:8px 11px;border-radius:6px;margin:8px 0 0;max-width:520px">
									<?php esc_html_e( 'There is still Sabriel AI code on the site that does not come from the plugin: usually old snippets pasted into a plugin such as WPCode or into the theme\'s functions.php file, left switched on after installation. Two copies of the same thing can fight each other and throw the site into an error. Disable the old snippets and keep only the plugin.', 'sabriel-ai' ); ?>
									<br><span style="color:#78350f;font-size:11.5px"><?php echo esc_html( implode( ', ', $sab_classi_fuori ) ); ?></span>
								</p>
							</td>
						</tr>
					<?php endif; ?>
					<tr>
						<td><?php esc_html_e( 'Customized settings', 'sabriel-ai' ); ?></td>
						<td>
							<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $config_essenziale_ok, $config_essenziale_ok ? _x( 'Configured', 'essential business information', 'sabriel-ai' ) : __( 'Still to be completed (identity, price list, behaviour)', 'sabriel-ai' ) ); ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=sabriel-ai-settings' ) ); ?>" style="margin-left:8px;font-size:12.5px"><?php esc_html_e( 'Go to settings →', 'sabriel-ai' ); ?></a>
						</td>
					</tr>
					<tr>
						<td><?php esc_html_e( 'Customized appearance', 'sabriel-ai' ); ?></td>
						<td>
							<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $aspetto_personalizzato, $aspetto_personalizzato ? __( 'Custom', 'sabriel-ai' ) : __( 'Default values', 'sabriel-ai' ) ); ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=sabriel-ai-branding' ) ); ?>" style="margin-left:8px;font-size:12.5px"><?php esc_html_e( 'Go to customization →', 'sabriel-ai' ); ?></a>
						</td>
					</tr>
					<tr>
						<td><?php esc_html_e( 'Identity and price list in the bot\'s prompt', 'sabriel-ai' ); ?></td>
						<td>
							<?php echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $identita_bot_personalizzata, $identita_bot_personalizzata ? __( 'Customised', 'sabriel-ai' ) : __( 'Still empty/sample values', 'sabriel-ai' ) ); ?>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=sabriel-ai-settings' ) ); ?>" style="margin-left:8px;font-size:12.5px"><?php esc_html_e( 'Go to settings →', 'sabriel-ai' ); ?></a>
						</td>
					</tr>
					<tr>
						<td><?php esc_html_e( 'Opening hours', 'sabriel-ai' ); ?></td>
						<td>
							<?php

							$sab_orari_personalizzati = Sabriel_Orari::orari_sono_configurati();
							$sab_orari_desc_stato     = Sabriel_Orari::descrizione_orari_per_prompt();
							echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( $sab_orari_personalizzati, $sab_orari_personalizzati ? _x( 'Configured', 'opening hours', 'sabriel-ai' ) : __( 'Not set up yet: the bot cannot tell customers whether you are open right now', 'sabriel-ai' ) );
							?>
							<span style="font-size:11.5px;color:#888;margin-left:6px"><?php echo esc_html( $sab_orari_desc_stato ); ?></span>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=sabriel-ai-settings&tab=comportamento' ) ); ?>" style="margin-left:8px;font-size:12.5px"><?php esc_html_e( 'Go to settings →', 'sabriel-ai' ); ?></a>
						</td>
					</tr>
				</tbody>
			</table>
			<p style="color:#888;font-size:12.5px;max-width:560px;margin-top:6px"><?php esc_html_e( 'Business name, owner, contacts, price list and page links inside the bot\'s prompt all come from here instead of being hardcoded: if this row is still red, the bot doesn\'t have an identity and price list set up yet, and will talk about them generically without knowing which business it is.', 'sabriel-ai' ); ?></p>

			<h2 style="margin-top:28px;font-size:16px"><?php esc_html_e( 'Email sending', 'sabriel-ai' ); ?></h2>
			<p style="max-width:640px;color:#666;font-size:13px"><?php esc_html_e( 'Sabriel AI sends email at two points: the conversation summary, which goes to the visitor and in copy to you, and the messages from the "leave a message" form. If this site cannot send, both fail without warning anyone: the panel keeps working and your customers simply receive nothing. This check exists to find out before that happens.', 'sabriel-ai' ); ?></p>
			<?php
			$sab_ultimo_errore = get_option( self::OPT_ERRORE_EMAIL );
			$sab_ultima_prova  = get_option( self::OPT_PROVA_EMAIL );
			?>
			<table class="widefat striped" style="max-width:760px;margin-top:10px">
				<tbody>
					<tr>
						<td style="width:280px"><?php esc_html_e( 'Last recorded send failure', 'sabriel-ai' ); ?></td>
						<td>
							<?php
							if ( empty( $sab_ultimo_errore ) ) {

								echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( true, __( 'None so far', 'sabriel-ai' ) );
								echo '<span style="margin-left:8px;color:#888;font-size:12.5px">' . esc_html__( '(no failure seen, this isn\'t proof that sending works yet: use the button below)', 'sabriel-ai' ) . '</span>';
							} else {
								echo /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() fa esc_html() sul testo. */ $this->badge( false, $sab_ultimo_errore['quando'] ?? '' );
								echo '<div style="margin-top:6px;color:#a33;font-size:12.5px">';
								if ( ! empty( $sab_ultimo_errore['errore'] ) ) {
									echo '<code style="background:#fff3f3;padding:2px 5px">' . esc_html( $sab_ultimo_errore['errore'] ) . '</code>';
								}
								if ( ! empty( $sab_ultimo_errore['oggetto'] ) ) {
									/* translators: %s: subject of the email that failed to send */
									echo '<br><span style="color:#888">' . esc_html( sprintf( __( 'Message not sent: “%s”', 'sabriel-ai' ), $sab_ultimo_errore['oggetto'] ) ) . '</span>';
								}
								echo '</div>';
							}
							?>
						</td>
					</tr>
					<?php if ( ! empty( $sab_ultima_prova ) ) : ?>
					<tr>
						<td><?php esc_html_e( 'Last send test', 'sabriel-ai' ); ?></td>
						<td>
							<?php
							$sab_quando_prova = $sab_ultima_prova['quando'] ?? '';
							$sab_prova_ok     = ! empty( $sab_ultima_prova['ok'] );
							$sab_testo_prova  = $sab_prova_ok
								/* translators: %s: date and time of the test */
								? sprintf( __( 'Sent on %s', 'sabriel-ai' ), $sab_quando_prova )
								/* translators: %s: date and time of the test */
								: sprintf( __( 'Failed on %s', 'sabriel-ai' ), $sab_quando_prova );
							echo $this->badge( $sab_prova_ok, $sab_testo_prova ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge() esegue esc_html() sul testo.
							?>
						</td>
					</tr>
					<?php endif; ?>
				</tbody>
			</table>

			<?php if ( $sab_mail_msg ) : ?>
				<div class="notice notice-success sab-avviso" style="max-width:760px;margin:12px 0"><p><?php echo esc_html( $sab_mail_msg ); ?></p></div>
			<?php endif; ?>
			<?php if ( $sab_mail_err ) : ?>
				<div class="notice notice-error sab-avviso" style="max-width:760px;margin:12px 0"><p><?php echo esc_html( $sab_mail_err ); ?></p></div>
			<?php endif; ?>

			<form method="post" style="margin-top:12px">
				<?php wp_nonce_field( 'sab_prova_mail_action', 'sab_prova_mail_nonce' ); ?>
				<button type="submit" class="button"><?php esc_html_e( 'Send a test email', 'sabriel-ai' ); ?></button>
				<span style="margin-left:10px;color:#888;font-size:12.5px">
					<?php
					echo esc_html( sprintf(

						/* translators: %s: administrator email address */
						__( 'It will be sent to %s (the site administrator\'s address).', 'sabriel-ai' ),
						get_option( 'admin_email' )
					) );
					?>
				</span>
			</form>

			<h2 style="margin-top:28px;font-size:16px"><?php esc_html_e( 'Live key test', 'sabriel-ai' ); ?></h2>
			<p style="max-width:560px;color:#666;font-size:13px"><?php esc_html_e( 'The live test of each key (a real, very short call, not just a check that the field isn\'t empty) is now done from the AI Engine page, where you can also switch engine and manage all 3 keys together.', 'sabriel-ai' ); ?></p>
			<p style="max-width:560px"><a href="<?php echo esc_url( admin_url( 'admin.php?page=sabriel-ai-motore' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Go to AI Engine', 'sabriel-ai' ); ?></a></p>

			<h2 style="margin-top:28px;font-size:16px"><?php esc_html_e( 'Support', 'sabriel-ai' ); ?></h2>
			<p style="max-width:560px;color:#666;font-size:13px"><?php esc_html_e( 'If something isn\'t working and you need to contact support, this button copies a complete summary of the installation: the technical data plus the assistant\'s whole configuration. Paste it into your message, so whoever helps you already has all the information without having to ask for it one piece at a time.', 'sabriel-ai' ); ?></p>
			<?php

			$testo_diagnostica = $this->testo_diagnostica();
			?>
			<textarea id="sab-diagnostica-testo" style="position:absolute;left:-9999px" readonly><?php echo esc_textarea( $testo_diagnostica ); ?></textarea>
			<p style="max-width:560px">
				<button type="button" id="sab-copia-diagnostica" class="button"><?php esc_html_e( '📋 Copy technical info for support', 'sabriel-ai' ); ?></button>
				<span id="sab-copia-conferma" style="display:none;margin-left:10px;color:#1a7d3a;font-weight:600;font-size:12.5px"><?php esc_html_e( '✓ Copied', 'sabriel-ai' ); ?></span>
			</p>

			<h3 style="font-size:14px;margin:26px 0 6px"><?php esc_html_e( 'Found a problem? Report it', 'sabriel-ai' ); ?></h3>
			<p style="max-width:560px;color:#666;font-size:13px"><?php esc_html_e( 'Describe what happened and what you expected. The complete summary above is attached automatically, you don\'t need to copy it.', 'sabriel-ai' ); ?></p>
			<p style="max-width:560px;color:#888;font-size:12px;margin-top:-4px">
				<?php
				printf(
					/* translators: %s: email address of the plugin developer */
					esc_html__( 'The report is sent from this site to the plugin\'s developer, at the address %s. Along with your text it carries this site\'s address, the email you write below and the complete summary (technical data and the assistant\'s configuration).', 'sabriel-ai' ),
					esc_html( self::email_segnalazioni() )
				);
				?>
			</p>

			<?php if ( $sab_fb_msg ) : ?>
				<div style="background:#eff9f0;border:1.5px solid #86d29a;color:#1a7d3a;padding:12px 18px;border-radius:8px;margin:12px 0;max-width:560px"><?php echo esc_html( $sab_fb_msg ); ?></div>
			<?php endif; ?>
			<?php if ( $sab_fb_err ) : ?>
				<div style="background:#fef2f2;border:1.5px solid #f5a3a3;color:#b91c1c;padding:12px 18px;border-radius:8px;margin:12px 0;max-width:560px"><?php echo esc_html( $sab_fb_err ); ?></div>
			<?php endif; ?>

			<form method="post" enctype="multipart/form-data" style="max-width:560px;background:#fff;border:1px solid #e5e5e5;border-radius:10px;padding:16px 18px">
				<?php wp_nonce_field( 'sab_feedback_action', 'sab_feedback_nonce' ); ?>
				<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'What happened?', 'sabriel-ai' ); ?></label>
				<textarea name="sab_fb_testo" rows="5" required style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box;font-size:13px" placeholder="<?php esc_attr_e( 'E.g. I set Saturday as an open day, but the assistant keeps telling customers we are closed.', 'sabriel-ai' ); ?>"></textarea>

				<label style="font-weight:600;font-size:13px;display:block;margin:14px 0 5px"><?php esc_html_e( 'Your email (for the reply)', 'sabriel-ai' ); ?></label>
				<input type="email" name="sab_fb_email" required value="<?php echo esc_attr( wp_get_current_user()->user_email ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box;font-size:13px">

				<label style="font-weight:600;font-size:13px;display:block;margin:14px 0 5px"><?php esc_html_e( 'Screenshot (optional)', 'sabriel-ai' ); ?></label>
				<input type="file" name="sab_fb_img" accept="image/png,image/jpeg,image/webp" style="font-size:13px">
				<p style="color:#92400e;background:#fffbeb;border:1px solid #f59e0b;border-radius:6px;padding:10px 12px;font-size:11.5px;margin:10px 0 0;line-height:1.6">
					<strong><?php esc_html_e( 'Before attaching: cover your clients\' data.', 'sabriel-ai' ); ?></strong><br>
					<?php esc_html_e( 'Names, emails, phone numbers, the content of conversations: these are personal data of people who have not authorised anyone to share them. We do not need them to understand a bug: the description is usually enough. If a screenshot contains them, black them out first, or do not attach it at all.', 'sabriel-ai' ); ?>
				</p>
				<label style="display:flex;align-items:flex-start;gap:8px;margin:12px 0 0;font-size:11.5px;color:#555;line-height:1.6;cursor:pointer">
					<input type="checkbox" name="sab_fb_conferma" value="1" required style="margin-top:2px;flex-shrink:0">
					<span><?php esc_html_e( 'I confirm that I\'ve checked that what I\'m sending doesn\'t contain third parties\' personal data, and that I\'m sharing it on my own initiative. I take responsibility for the content of the report.', 'sabriel-ai' ); ?></span>
				</label>

				<p style="margin:16px 0 0"><button type="submit" class="button button-primary"><?php esc_html_e( 'Send report', 'sabriel-ai' ); ?></button></p>
			</form>

			<h2 style="font-size:16px;margin:30px 0 6px;border-top:1px solid #e5e5e5;padding-top:22px"><?php esc_html_e( 'Configuration backup', 'sabriel-ai' ); ?></h2>
			<p style="color:#666;max-width:560px;font-size:13px"><?php esc_html_e( 'Download a file with the whole configuration (identity, price list, colours, opening hours, everything except the AI keys: those stay on this site only) to keep it safe or to copy it to another installation.', 'sabriel-ai' ); ?></p>

			<?php if ( $import_msg ) : ?>
				<div style="background:#eff9f0;border:1.5px solid #86d29a;color:#1a7d3a;padding:12px 18px;border-radius:8px;margin:12px 0;max-width:560px"><?php echo esc_html( $import_msg ); ?></div>
			<?php endif; ?>
			<?php if ( $import_err ) : ?>
				<div style="background:#fef2f2;border:1.5px solid #f5a3a3;color:#b91c1c;padding:12px 18px;border-radius:8px;margin:12px 0;max-width:560px"><?php echo esc_html( $import_err ); ?></div>
			<?php endif; ?>

			<p style="max-width:560px">
				<button type="button" id="sab-export-config" class="button"><?php esc_html_e( '⬇ Export configuration (.json)', 'sabriel-ai' ); ?></button>
			</p>
			<form method="post" enctype="multipart/form-data" style="max-width:560px;margin-top:10px">
				<?php wp_nonce_field( 'sab_import_action', 'sab_import_nonce' ); ?>
				<label style="font-weight:600;font-size:13px;display:block;margin-bottom:6px"><?php esc_html_e( 'Import configuration', 'sabriel-ai' ); ?></label>
				<p style="color:#b91c1c;font-size:12px;margin:0 0 8px"><?php esc_html_e( 'Warning: replaces the WHOLE current configuration with the one in the file. The present configuration is set aside, so you can restore it if you pick the wrong file.', 'sabriel-ai' ); ?></p>
				<input type="file" name="sab_import_file" accept="application/json,.json" required style="margin-bottom:10px">
				<br>
				<button type="submit" class="button" onclick="return confirm('<?php echo esc_js( __( 'Are you sure? This overwrites your entire current configuration.', 'sabriel-ai' ) ); ?>');"><?php esc_html_e( 'Import and replace', 'sabriel-ai' ); ?></button>
			</form>

			<?php
			$sab_copia_pre_import = get_option( self::OPT_BACKUP_PRE_IMPORT );
			if ( ! empty( $sab_copia_pre_import['dati'] ) ) :
				?>
				<form method="post" style="max-width:560px;margin-top:14px;background:#fffbeb;border:1px solid #f59e0b;border-radius:8px;padding:12px 14px">
					<?php wp_nonce_field( 'sab_ripristina_action', 'sab_ripristina_nonce' ); ?>
					<p style="margin:0 0 8px;font-size:12.5px;color:#78350f">
						<?php
						echo esc_html( sprintf(
							/* translators: %s: date and time of the backup */
							__( 'There is a configuration set aside before the last import (%s). If the imported file was not the right one, you can restore the previous one.', 'sabriel-ai' ),
							$sab_copia_pre_import['quando'] ?? ''
						) );
						?>
					</p>
					<button type="submit" class="button"><?php esc_html_e( '↩ Restore the previous configuration', 'sabriel-ai' ); ?></button>
				</form>
			<?php endif; ?>
			<script>
			document.getElementById('sab-export-config').addEventListener('click', function(){
				var dati = <?php echo wp_json_encode( Sabriel_Base::get_all() ); ?>;
				var blob = new Blob([JSON.stringify(dati, null, 2)], {type:'application/json'});
				var url = URL.createObjectURL(blob);
				var a = document.createElement('a');
				a.href = url;
				a.download = 'sabriel-ai-config-<?php echo esc_js( wp_date( 'Y-m-d' ) ); ?>.json';
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);
				URL.revokeObjectURL(url);
			});
			</script>
			<script>
			document.getElementById('sab-copia-diagnostica').addEventListener('click', function(){
				var testo = document.getElementById('sab-diagnostica-testo').value;
				var conferma = document.getElementById('sab-copia-conferma');
				function mostraConferma(){
					conferma.style.display = 'inline';
					setTimeout(function(){ conferma.style.display = 'none'; }, 2500);
				}
				if (navigator.clipboard && navigator.clipboard.writeText) {
					navigator.clipboard.writeText(testo).then(mostraConferma);
				} else {
					var ta = document.getElementById('sab-diagnostica-testo');
					ta.style.left = '0'; ta.select();
					document.execCommand('copy');
					ta.style.left = '-9999px';
					mostraConferma();
				}
			});
			</script>
		</div>
		<?php
	}

	private function badge( $ok, $testo ) {
		$colore = $ok ? '#1a7d3a' : '#b91c1c';
		$sfondo = $ok ? '#eff9f0' : '#fef2f2';
		$simbolo = $ok ? '✓' : '✗';
		return '<span style="display:inline-block;padding:3px 10px;border-radius:12px;font-weight:600;font-size:12.5px;color:' . $colore . ';background:' . $sfondo . '">' . $simbolo . ' ' . esc_html( $testo ) . '</span>';
	}
}
