<?php

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

class Sabriel_Module_Contatto extends Sabriel_Module {

	const TR_MAX_MESSAGGI  = 200;
	const TR_MAX_CARATTERI = 4000;

	const TR_MAX_PER_DESTINATARIO = 3;

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

	public function register_hooks() {
		add_action( 'rest_api_init', [ $this, 'register_routes' ] );
	}

	public function register_routes() {
		register_rest_route( 'sabriel/v1', '/transcript', [
			'methods' => 'POST', 'callback' => [ $this, 'rest_send_transcript' ], 'permission_callback' => '__return_true',
		] );
		register_rest_route( 'sabriel/v1', '/quick-message', [
			'methods' => 'POST', 'callback' => [ $this, 'rest_quick_message' ], 'permission_callback' => '__return_true',
		] );
	}

	public function rest_send_transcript( WP_REST_Request $req ) {

		$ip_tr    = Sabriel_Helpers::get_client_ip();
		$rl_tr_k  = 'sabriel_ai_tr_rl_' . md5( $ip_tr );
		$rl_tr_n  = (int) get_transient( $rl_tr_k );
		if ( $rl_tr_n >= 30 ) {
			Sabriel_Module_Traffico::registra_blocco_sicurezza( 'transcript_rate_limit' );
			return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Too many requests, please try again shortly.', 'sabriel-ai' ) ], 429 );
		}
		set_transient( $rl_tr_k, $rl_tr_n + 1, HOUR_IN_SECONDS );

		$body     = json_decode( (string) $req->get_body(), true );
		$name     = mb_substr( sanitize_text_field( $body['name'] ?? '' ), 0, 100 );
		$email    = Sabriel_Helpers::email_pulita(  $body['email'] ?? '' );
		$date     = mb_substr( sanitize_text_field( $body['date'] ?? '' ), 0, 60 );
		$messages = is_array( $body['messages'] ?? null ) ? $body['messages'] : [];
		$token_tr = sanitize_text_field( $body['token'] ?? '' );

		if ( $email ) {
			$em_tr     = strtolower( trim( $email ) );
			$prova_ok  = (bool) get_transient( Sabriel_Module_Chat::TRASCRIZIONE_PROVA . md5( $em_tr ) );
			$gettone_ok = $token_tr && Sabriel_Helpers::firma_token_valida( 'transcript|' . $em_tr, $token_tr );

			if ( ! $prova_ok || ! $gettone_ok ) {
				Sabriel_Module_Traffico::registra_blocco_sicurezza( 'transcript_senza_conversazione' );
				return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Invalid request.', 'sabriel-ai' ) ], 403 );
			}

			$rl_dest_k = 'sabriel_ai_tr_dest_' . md5( $em_tr );
			$rl_dest_n = (int) get_transient( $rl_dest_k );
			if ( $rl_dest_n >= self::TR_MAX_PER_DESTINATARIO ) {
				Sabriel_Module_Traffico::registra_blocco_sicurezza( 'transcript_troppe_al_destinatario' );
				return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Too many requests, please try again shortly.', 'sabriel-ai' ) ], 429 );
			}
			set_transient( $rl_dest_k, $rl_dest_n + 1, HOUR_IN_SECONDS );
		}

		if ( count( $messages ) > self::TR_MAX_MESSAGGI ) {
			$messages = array_slice( $messages, - self::TR_MAX_MESSAGGI );
		}

		if ( ! $email || ! is_email( $email ) ) {
			return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Invalid email', 'sabriel-ai' ) ], 400 );
		}

		if ( Sabriel_Helpers::email_temporanea( $email ) ) {
			return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Please use a permanent email address, not a temporary one.', 'sabriel-ai' ) ], 400 );
		}

		$support_email = ( Sabriel_Module_Settings::get( 'support_email' ) ?: get_option( 'admin_email' ) );
		$business_name = Sabriel_Module_Settings::get( 'business_name' );
		$tagline       = Sabriel_Module_Settings::get( 'tagline' );
		$phone_display = Sabriel_Module_Settings::get( 'phone_display' );
		$whatsapp      = Sabriel_Module_Settings::get( 'whatsapp_number' );

		$righe_trascrizione = [];

		$bubbles = '';
		foreach ( $messages as $msg ) {
			$from    = mb_substr( sanitize_text_field( $msg['from'] ?? '' ), 0, 100 );
			$text    = mb_substr( sanitize_textarea_field( $msg['text'] ?? '' ), 0, self::TR_MAX_CARATTERI );
			$is_user = ! empty( $msg['isUser'] );
			$righe_trascrizione[] = $from . ': ' . $text;
			if ( $is_user ) {
				$bubbles .= '<div style="text-align:right;margin:8px 0"><span style="display:inline-block;background:' . esc_attr( Sabriel_Module_Branding::colore_email_sfondo() ) . ';color:' . esc_attr( Sabriel_Module_Branding::colore_email_testo_intestazione() ) . ';padding:10px 15px;border-radius:14px 14px 4px 14px;font-size:14px;max-width:75%;text-align:left;line-height:1.5">' . nl2br( esc_html( $text ) ) . '</span><div style="font-size:11px;color:#999;margin-top:3px">' . esc_html( $from ) . '</div></div>';
			} else {
				$bubbles .= '<div style="text-align:left;margin:8px 0"><span style="display:inline-block;background:#f5f5f5;color:#1a1a1a;border-left:3px solid ' . esc_attr( Sabriel_Module_Branding::colore_email_accento() ) . ';padding:10px 15px;border-radius:4px 14px 14px 14px;font-size:14px;max-width:75%;text-align:left;line-height:1.5">' . nl2br( esc_html( $text ) ) . '</span><div style="font-size:11px;color:#999;margin-top:3px">' . esc_html( $business_name ) . '</div></div>';
			}
		}

		if ( $righe_trascrizione ) {
			$team_subj = sprintf(
				/* translators: %s: business name */
				__( 'Chat %s', 'sabriel-ai' ),
				$business_name
			) . ' – ' . $name . ' <' . $email . '>';
			$team_html = '<pre style="font-family:monospace;font-size:13px;line-height:1.6">' . esc_html( implode( "\n", $righe_trascrizione ) ) . '</pre>';
			$team_head = [ 'Content-Type: text/html; charset=UTF-8', Sabriel_Helpers::intestazione_mittente( $business_name, $support_email ) ];
			wp_mail( $support_email, $team_subj, $team_html, $team_head );
		}

		$righe_contatto = [];
		if ( $support_email ) {
			$righe_contatto[] = esc_html__( 'Email', 'sabriel-ai' ) . ': <a href="mailto:' . esc_attr( $support_email ) . '" style="color:' . esc_attr( Sabriel_Module_Branding::colore_email_accento() ) . ';text-decoration:none">' . esc_html( $support_email ) . '</a>';
		}
		if ( $phone_display ) {
			$righe_contatto[] = esc_html__( 'Phone', 'sabriel-ai' ) . ': <a href="tel:' . esc_attr( preg_replace( '/[^0-9+]/', '', $phone_display ) ) . '" style="color:' . esc_attr( Sabriel_Module_Branding::colore_email_accento() ) . ';text-decoration:none">' . esc_html( $phone_display ) . '</a>';
		}
		if ( $whatsapp ) {
			$righe_contatto[] = 'WhatsApp: <a href="https://wa.me/' . esc_attr( preg_replace( '/[^0-9]/', '', $whatsapp ) ) . '" style="color:#25D366;text-decoration:none">WhatsApp</a>';
		}
		$contatti_html = $righe_contatto
			? '<tr><td style="padding:24px 30px 30px"><div style="border-top:1px solid #ebebeb;padding-top:20px"><p style="margin:0 0 8px;font-size:13px;color:#555;font-weight:600">' . esc_html__( 'Any other questions? We\'re here:', 'sabriel-ai' ) . '</p><p style="margin:0;font-size:13px;color:#777;line-height:1.8">' . implode( '<br>', $righe_contatto ) . '</p></div></td></tr>'
			: '';

		$nota_html = '<tr><td style="padding:0 30px 26px"><p style="margin:0;font-size:11.5px;color:#9a9a9a;line-height:1.6">'
			. sprintf(
				/* translators: %s: website name */
				esc_html__( 'You received this message because this address was given in the chat of %s to receive a copy of the conversation. If it wasn\'t you, you can ignore it: no account was created and you will not receive anything else.', 'sabriel-ai' ),
				esc_html( wp_parse_url( home_url(), PHP_URL_HOST ) )
			)
			. '</p></td></tr>';

		$html = '<!DOCTYPE html><html lang="' . esc_attr( Sabriel_Helpers::lingua_html() ) . '"><head><meta charset="UTF-8"></head><body style="margin:0;padding:0;background:#f0f0f0;font-family:-apple-system,BlinkMacSystemFont,Arial,sans-serif"><table width="100%" cellpadding="0" cellspacing="0" style="background:#f0f0f0;padding:30px 0"><tr><td align="center"><table width="600" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:12px;overflow:hidden;max-width:600px"><tr><td style="background:' . esc_attr( Sabriel_Module_Branding::colore_email_sfondo() ) . ';padding:24px 30px;text-align:center"><div style="color:' . esc_attr( Sabriel_Module_Branding::colore_email_testo_intestazione() ) . ';font-size:20px;font-weight:700">' . esc_html( $business_name ) . '</div>' . ( $tagline ? '<div style="color:' . esc_attr( Sabriel_Module_Branding::colore_email_testo_intestazione() ) . ';opacity:0.65;font-size:12px;margin-top:4px">' . esc_html( $tagline ) . '</div>' : '' ) . '</td></tr><tr><td style="padding:30px 30px 10px"><p style="margin:0 0 6px;font-size:16px;font-weight:600;color:#111">' . sprintf( /* translators: %s: person's name */ esc_html__( 'Hi %s,', 'sabriel-ai' ), esc_html( $name ) ) . '</p><p style="margin:0 0 24px;font-size:14px;color:#555;line-height:1.6">' . esc_html__( 'here\'s the summary of your conversation with our digital assistant.', 'sabriel-ai' ) . '<br><span style="color:#999;font-size:12px">' . esc_html( $date ) . '</span></p></td></tr><tr><td style="padding:0 30px 10px"><div style="background:#f8f8f8;border-radius:10px;padding:20px">' . $bubbles . '</div></td></tr>' . $contatti_html . $nota_html . '</table></td></tr></table></body></html>';

		$headers = [ 'Content-Type: text/html; charset=UTF-8', Sabriel_Helpers::intestazione_mittente( $business_name, $support_email ) ];
		$sent    = wp_mail( $email, sprintf( /* translators: %s: business name */ __( 'The summary of your chat with %s', 'sabriel-ai' ), $business_name ), $html, $headers );
		return new WP_REST_Response( [ 'ok' => $sent ], $sent ? 200 : 500 );
	}

	public function rest_quick_message( WP_REST_Request $req ) {
		$body    = json_decode( (string) $req->get_body(), true );
		$nome    = mb_substr( sanitize_text_field( $body['nome'] ?? '' ), 0, 100 );
		$email   = Sabriel_Helpers::email_pulita(  $body['email'] ?? '' );
		$tel     = mb_substr( sanitize_text_field( $body['telefono'] ?? '' ), 0, 40 );
		$testo   = mb_substr( sanitize_textarea_field( $body['messaggio'] ?? '' ), 0, self::TR_MAX_CARATTERI );

		if ( ! $testo ) {
			return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Empty message', 'sabriel-ai' ) ], 400 );
		}

		if ( $email && Sabriel_Helpers::email_temporanea( $email ) ) {
			return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Please use a permanent email address, not a temporary one.', 'sabriel-ai' ) ], 400 );
		}

		$ip     = Sabriel_Helpers::get_client_ip();
		$rl_key = 'sabriel_ai_qm_rl_' . md5( $ip );
		$count  = (int) get_transient( $rl_key );
		if ( $count >= 5 ) {
			/* ⚠ Anche questo blocco va contato: senza, sotto un'ondata di spam il
			   proprietario in Analitica non vede NIENTE e crede che non arrivi
			   nessuno, mentre le richieste vengono respinte a raffica. Lo fa gia'
			   /transcript: qui mancava. */
			Sabriel_Module_Traffico::registra_blocco_sicurezza( 'quick_message_rate_limit' );
			return new WP_REST_Response( [ 'ok' => false, 'error' => __( 'Too many messages, please try again later', 'sabriel-ai' ) ], 429 );
		}
		set_transient( $rl_key, $count + 1, HOUR_IN_SECONDS );

		$support_email = ( Sabriel_Module_Settings::get( 'support_email' ) ?: get_option( 'admin_email' ) );
		$business_name = Sabriel_Module_Settings::get( 'business_name' );

		/* translators: %s: name of the person who wrote from the chat, or "Visitor". */
		$oggetto = sprintf( __( 'Chat message - %s', 'sabriel-ai' ), $nome ?: __( 'Visitor', 'sabriel-ai' ) );
		$html    = '<p><strong>' . esc_html__( 'Name', 'sabriel-ai' ) . ':</strong> ' . esc_html( $nome ?: '—' ) . '</p>'
			. '<p><strong>' . esc_html__( 'Email', 'sabriel-ai' ) . ':</strong> ' . esc_html( $email ?: '—' ) . '</p>'
			. '<p><strong>' . esc_html__( 'Phone', 'sabriel-ai' ) . ':</strong> ' . esc_html( $tel ?: '—' ) . '</p>'
			. '<p><strong>' . esc_html__( 'Message', 'sabriel-ai' ) . ':</strong><br>' . nl2br( esc_html( $testo ) ) . '</p>';
		$headers = [ 'Content-Type: text/html; charset=UTF-8', Sabriel_Helpers::intestazione_mittente( $business_name, $support_email ) ];
		if ( $email && is_email( $email ) ) {
			$headers[] = 'Reply-To: ' . $email;
		}

		$sent = wp_mail( $support_email, $oggetto, $html, $headers );
		return new WP_REST_Response( [ 'ok' => $sent ], $sent ? 200 : 500 );
	}
}
