<?php

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

class Sabriel_Module_Widget extends Sabriel_Module {

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

	public function register_hooks() {
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_assets' ] );

		add_action( 'wp_footer', [ $this, 'render_markup' ], 5 );
	}

	public static function motore_configurato() {
		if ( ! class_exists( 'Sabriel_Module_AI' ) ) {
			return true;

		}
		$sab_provider = Sabriel_Module_AI::provider_attivo();
		$sab_opzione  = Sabriel_Module_AI::PROVIDERS[ $sab_provider ][1] ?? '';
		if ( '' === $sab_opzione ) {
			return true;
		}
		$sab_grezza = (string) get_option( $sab_opzione, '' );
		if ( '' === $sab_grezza ) {
			return false;
		}
		return class_exists( 'Sabriel_Crypto' )
			? '' !== (string) Sabriel_Crypto::decrypt( $sab_grezza )
			: true;
	}

	private static function widget_da_mostrare() {
		return self::motore_configurato() || current_user_can( 'manage_options' );
	}

	public function enqueue_assets() {

		if ( ! self::widget_da_mostrare() ) {
			return;
		}

		wp_enqueue_style(
			'sabriel-ai-widget',
			SABRIEL_AI_URL . 'public/css/widget.css',
			[],
			SABRIEL_AI_VERSION
		);

		wp_add_inline_style( 'sabriel-ai-widget', '#sar{' . Sabriel_Module_Branding::css_variables() . '}' );


		wp_enqueue_script(
			'sabriel-ai-widget',
			SABRIEL_AI_URL . 'public/js/widget-body.js',
			[],
			SABRIEL_AI_VERSION,
			true
		);

		$sab_lingua_cambiata = self::apri_lingua_bot();

		$sab_i18n = self::stringhe_js();

		self::chiudi_lingua_bot( $sab_lingua_cambiata );

		wp_localize_script( 'sabriel-ai-widget', 'SabrielAI', [

			'i18n'            => $sab_i18n,

			'maxAllegatoByte' => self::max_allegato_byte(),

			'leggePdf'        => class_exists( 'Sabriel_Module_AI' ) ? Sabriel_Module_AI::motore_legge_pdf() : true,
			'notifyEmail'     => ( Sabriel_Module_Settings::get( 'support_email' ) ?: get_option( 'admin_email' ) ),
			'whatsappNumber'  => Sabriel_Module_Settings::get( 'whatsapp_number' ),
			'businessName'    => self::nome_attivita_visibile(),

			'localeJs'           => self::locale_js(),

			'phoneDisplay'    => Sabriel_Module_Settings::get( 'phone_display' ),

			'emailTemporanee' => Sabriel_Helpers::domini_usa_e_getta(),
			'restUrl'         => esc_url_raw( rest_url( 'sabriel/v1' ) ),
			'statistiche'     => Sabriel_Module_Settings::get( 'statistiche_attive' ) ? 1 : 0,
			'botName'         => Sabriel_Module_Branding::get( 'bot_name' ),
			'logoUrl'         => esc_url_raw( Sabriel_Module_Branding::get( 'logo_url' ) ),
		] );
	}

	public static function nome_attivita_visibile() {
		$nome = trim( (string) Sabriel_Module_Settings::get( 'business_name' ) );
		if ( '' !== $nome ) {
			return $nome;
		}
		return class_exists( 'Sabriel_Module_Branding' ) ? Sabriel_Module_Branding::nome_bot_predefinito() : '';
	}

	public function render_markup() {
		if ( ! self::widget_da_mostrare() ) {
			return;
		}
		$partial = SABRIEL_AI_DIR . 'public/partials/widget-markup.php';
		if ( ! file_exists( $partial ) ) {
			return;
		}

		$sab_lingua_cambiata = self::apri_lingua_bot();

		$bot_name      = Sabriel_Module_Branding::get( 'bot_name' );
		$business_name = self::nome_attivita_visibile();
		$logo_url      = Sabriel_Module_Branding::get( 'logo_url' );
		$iniziale      = function_exists( 'mb_substr' ) ? mb_substr( $bot_name, 0, 1 ) : substr( $bot_name, 0, 1 );

		$sab_max_allegato_mb = max( 1, (int) floor( self::max_allegato_byte() / 1048576 ) );

		$sab_legge_pdf = class_exists( 'Sabriel_Module_AI' ) ? Sabriel_Module_AI::motore_legge_pdf() : true;

		include $partial;

		self::chiudi_lingua_bot( $sab_lingua_cambiata );
	}

	private static function stringhe_js() {

		$sab_i18n_legge_pdf = class_exists( 'Sabriel_Module_AI' ) ? Sabriel_Module_AI::motore_legge_pdf() : true;

		return [
			/* translators: %1$s: customer name; %2$s: business name */
			'benvenuto'          => __( 'Hi %1$s! I\'m the assistant at %2$s. How can I help you today?', 'sabriel-ai' ),

			/* translators: %s: business contact email */
			'nonHoCapito'        => __( 'I didn\'t quite get that. Could you rephrase, or write to us at %s', 'sabriel-ai' ),

			/* translators: %s: support contact */
			'emailOggetto'       => __( 'Support %s', 'sabriel-ai' ),

			/* translators: %s: business VAT number */

			/* translators: %s: business contact email */
			'prevConnessioneKo'  => __( 'Connection error. Contact us at %s', 'sabriel-ai' ),

			'scriviPrima'        => __( 'Please write a message before sending.', 'sabriel-ai' ),

			'kwLive'             => __( 'whatsapp|contact|operator|human|person|someone|call|speak.*you|talk.*you|support|email.*you|write.*you|show|let me see|see it|again|where\\s*(is|are|can i find)|(can\'t|cannot|don\'t) (see|find)', 'sabriel-ai' ),

			'datiAggiornati'     => __( 'Details updated.', 'sabriel-ai' ),

			'imgAllegata'        => __( '[image attached]', 'sabriel-ai' ),
			'imgBreve'           => __( '[image]', 'sabriel-ai' ),
			'waUltimiMsg'        => __( 'Latest messages:', 'sabriel-ai' ),
			'mailChatSep'        => __( '--- Chat ---', 'sabriel-ai' ),
			'utenteAnonimo'      => __( 'Anonymous user', 'sabriel-ai' ),
			'limiteGiornaliero'  => __( 'Daily limit reached', 'sabriel-ai' ),
			'compilaModulo'      => __( 'Please fill in the initial form first.', 'sabriel-ai' ),
			'nomeVuoto'          => __( 'First name cannot be empty.', 'sabriel-ai' ),
			'cognomeVuoto'       => __( 'Last name cannot be empty.', 'sabriel-ai' ),
			'emailNonValida'     => __( 'Invalid email address.', 'sabriel-ai' ),
			'emailTemporanea'    => __( 'We don\'t accept temporary or disposable email addresses. Please use an address you check regularly.', 'sabriel-ai' ),
			'servizioOccupato'   => __( 'The service is very busy right now. Please try again in a few seconds.', 'sabriel-ai' ),
			/* translators: %s: business contact email */
			'servizioErrore'     => __( 'The service isn\'t responding correctly right now (technical error on the server side). Try again shortly or write to us at %s', 'sabriel-ai' ),
			'chatInattiva'       => __( 'There\'s been no reply for a while. The chat will close automatically. Just reopen it whenever you want to continue.', 'sabriel-ai' ),
			'allegatoAnteprima'  => __( 'Attachment preview', 'sabriel-ai' ),
			'waChatDa'           => __( 'Chat from:', 'sabriel-ai' ),

			'waBriefingEtichettaRisposta' => __( 'HOW TO REPLY:', 'sabriel-ai' ),
			/* translators: %1$s: business name; %2$s: customer name; %3$s: label of the advice line; %4$s: conversation text */
			'waBriefingPrompt'   => __( "Analyse this conversation and write a briefing in the THIRD PERSON for the team at %1\$s who will reply on WhatsApp. Readable at a glance.\n\nReply ONLY in this format:\n\nThe customer %2\$s got in touch via chat.\n\nWHAT THEY WANT: [what they are looking for]\nWHAT THEY ASKED: [main questions]\nSITUATION: [the customer's sector or type of business, budget, urgency, other relevant details]\nMAIN CONCERN: [their uncertainty or objection]\n%3\$s [tone advice in 1 sentence]\n\nCONVERSATION:\n%4\$s", 'sabriel-ai' ),
			'liveWhatsapp'       => __( 'WhatsApp - quick reply', 'sabriel-ai' ),
			'limiteContattaci'   => __( 'Contact us now', 'sabriel-ai' ),
			'statoOnline'        => __( 'Online', 'sabriel-ai' ),
			'rispondiQui'        => __( "\n\n→ Reply here to continue.", 'sabriel-ai' ),
			'limiteRaggiunto'    => __( 'You\'ve used all the messages available for today. For immediate assistance, contact us directly.', 'sabriel-ai' ),

			'micNegato'          => __( 'Microphone permission denied: check it in your browser settings.', 'sabriel-ai' ),
			'micNonSentito'      => __( 'I didn\'t catch that, please try again.', 'sabriel-ai' ),

			/* translators: %s: maximum attachment size, e.g. "5 MB" */
			'allegatoLimite'     => $sab_i18n_legge_pdf
				? __( 'You can attach 1 image or PDF, up to %s.', 'sabriel-ai' )
				/* translators: %s: maximum attachment size, e.g. "5 MB" */
				: __( 'You can attach 1 image, up to %s.', 'sabriel-ai' ),
			/* translators: %s: maximum attachment size */
			'allegatoTroppoGr'   => __( 'File too large. Maximum %s.', 'sabriel-ai' ),
			'allegatoFormato'    => $sab_i18n_legge_pdf
				? __( 'Unsupported format. Please use JPG, PNG, WebP or PDF.', 'sabriel-ai' )
				: __( 'Unsupported format. Please use JPG, PNG or WebP.', 'sabriel-ai' ),

			'allegatoNientePdf'  => __( 'I can\'t read PDFs. Attach an image instead, or paste the text of the document here and we\'ll go through it together.', 'sabriel-ai' ),
			'allegatoRotto'      => __( 'This image seems damaged or unreadable: please try another one.', 'sabriel-ai' ),

			'cronVuota'          => __( 'No saved conversations', 'sabriel-ai' ),
			'cronNonSalvata'     => __( 'Your browser storage is full: this conversation may not be saved.', 'sabriel-ai' ),
			/* translators: %s: date of the conversation */
			'cronSessioneDel'    => __( 'Session from %s - read only', 'sabriel-ai' ),
			'cronEliminaTutto'   => __( 'Delete the entire history?', 'sabriel-ai' ),
			'cronElimina'        => __( 'Delete', 'sabriel-ai' ),
			'cronNuovaConv'      => __( 'Start a new conversation', 'sabriel-ai' ),
			'invioKo'            => __( 'sending failed', 'sabriel-ai' ),
			'invioOk'            => __( '✓ Message sent! We\'ll get back to you as soon as possible.', 'sabriel-ai' ),
			'invioMessaggio'     => __( '✉ Send message', 'sabriel-ai' ),
			'invioInCorso'       => __( 'Sending...', 'sabriel-ai' ),
			'invioErrore'        => __( 'Sending error. Please try again.', 'sabriel-ai' ),
			'scriviViaEmail'     => __( '📧 Write by email', 'sabriel-ai' ),
			'liveContattaci'     => __( 'Contact us directly:', 'sabriel-ai' ),
			'limiteTitolo'       => __( 'Daily limit reached', 'sabriel-ai' ),
			'limiteEmail'        => __( 'Email', 'sabriel-ai' ),
			'oppureScrivi'       => __( 'Or write your message here...', 'sabriel-ai' ),
			'emailCorpo'         => __( "Hello,\n\nI need some help.\n", 'sabriel-ai' ),
			/* translators: %s: customer name */
			'emailNome'          => __( 'Name: %s', 'sabriel-ai' ),
			/* translators: %s: email address (same msgid used for the customer email and for the business contact email) */
			'emailEmail'         => __( 'Email: %s', 'sabriel-ai' ),

			/* translators: %d: deposit percentage */
			/* translators: %d: percentage due at the midpoint of the work */
			/* translators: %d: percentage due on delivery */
			/* translators: %s: date from which the service is available */
			'limiteDal'          => __( 'Available from %s', 'sabriel-ai' ),
			'limiteDomani'       => __( 'Available tomorrow', 'sabriel-ai' ),
			/* translators: %d: deposit percentage */

		];
	}

	public static function max_allegato_byte() {
		$post_max = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
		$tetto    = 10 * 1024 * 1024;
		if ( $post_max <= 0 ) {
			return $tetto;
		}

		$utile = $post_max - ( 200 * 1024 );
		if ( $utile <= 0 ) {
			return 256 * 1024;
		}
		$max = (int) floor( $utile * 3 / 4 );
		return min( $max, $tetto );
	}

	private static function carica_traduzioni( $locale ) {
		unload_textdomain( 'sabriel-ai' );

		if ( class_exists( 'WP_Translation_Controller' ) ) {
			WP_Translation_Controller::get_instance()->set_locale( $locale );
		}
		$candidati = [
			WP_LANG_DIR . '/plugins/sabriel-ai-' . $locale . '.mo',

			SABRIEL_AI_DIR . 'languages/sabriel-ai-' . $locale . '.mo',

		];
		foreach ( $candidati as $file ) {
			if ( file_exists( $file ) && load_textdomain( 'sabriel-ai', $file, $locale ) ) {
				return;
			}
		}
	}

	private static function apri_lingua_bot() {
		$locale = self::locale_widget();
		if ( $locale === get_locale() ) {
			return '';
		}
		$cambio_wp = switch_to_locale( $locale );
		self::carica_traduzioni( $locale );
		return $cambio_wp ? 'wp' : 'solo-plugin';
	}

	private static function chiudi_lingua_bot( $cambiata ) {
		if ( ! $cambiata ) {
			return;
		}
		if ( 'wp' === $cambiata ) {
			restore_previous_locale();
		}
		self::carica_traduzioni( get_locale() );
	}

	private static function locale_widget() {

		$mappa = class_exists( 'Sabriel_Module_Settings' ) ? Sabriel_Module_Settings::lingue_locali() : [];
		$lingua_bot = class_exists( 'Sabriel_Module_Settings' ) ? Sabriel_Module_Settings::bot_lingua_con_rilevamento() : 'en';
		return $mappa[ $lingua_bot ] ?? 'en_US';
	}

	public static function locale_js() {
		return str_replace( '_', '-', self::locale_widget() );
	}
}
