<?php
/**
 * Lead Form Generator — Notification Mailer
 *
 * Renders a Q&A transcript for a completed (or partial) lead-form session
 * and sends it to the admin address configured in Lead Capture Settings.
 *
 * @package Niwa_AI
 * @since   0.12.0
 */

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

class Niwa_AI_Lead_Form_Mailer {

	/**
	 * @var Niwa_AI_Lead_Form_Session_Store
	 */
	private $store;

	/**
	 * Constructor.
	 *
	 * @param Niwa_AI_Lead_Form_Session_Store $store Store.
	 */
	public function __construct( $store ) {
		$this->store = $store;
	}

	/**
	 * Send notification email for a given session.
	 *
	 * @param int  $session_row_id Session DB id.
	 * @param bool $is_partial     True if partial capture (email/phone only).
	 * @return bool Delivery outcome.
	 */
	public function send_notification( $session_row_id, $is_partial ) {
		$session_row_id = (int) $session_row_id;
		if ( $session_row_id <= 0 ) {
			return false;
		}

		$to = $this->resolve_recipient();
		if ( '' === $to ) {
			return false;
		}

		$session = $this->load_session_row( $session_row_id );
		if ( ! $session ) {
			return false;
		}

		$answers = $this->store->get_answers( $session_row_id );
		$schema  = Niwa_AI_Lead_Form_Schema::get();

		$subject = $this->build_subject( (bool) $is_partial );
		$html    = $this->render_html( $session, $answers, $schema, (bool) $is_partial );
		$text    = $this->render_plain( $session, $answers, $schema, (bool) $is_partial );

		// Swap Content-Type to HTML for this send, then remove the filter immediately.
		$html_filter = function () {
			return 'text/html; charset=UTF-8';
		};
		add_filter( 'wp_mail_content_type', $html_filter );

		$headers = array(
			'Content-Type: text/html; charset=UTF-8',
		);

		$sent = wp_mail( $to, $subject, $html, $headers, array() );

		remove_filter( 'wp_mail_content_type', $html_filter );

		if ( ! $sent ) {
			// Fallback: plaintext send.
			$sent_plain = wp_mail( $to, $subject, $text );
			if ( ! $sent_plain ) {
				error_log( '[NiwaAI LeadForm] wp_mail failed for session ' . $session_row_id . ' → ' . $to );
				return false;
			}
		}

		$this->store->mark_notified( $session_row_id );
		return true;
	}

	/**
	 * Resolve recipient address from lead capture settings.
	 *
	 * @return string
	 */
	private function resolve_recipient() {
		$opts  = get_option( Niwa_AI_Constants::OPT_LEAD_CAPTURE, array() );
		$email = is_array( $opts ) && isset( $opts['lead_notification_email'] ) ? (string) $opts['lead_notification_email'] : '';
		$email = sanitize_email( trim( $email ) );
		if ( '' === $email || ! is_email( $email ) ) {
			return '';
		}
		return $email;
	}

	/**
	 * Load session row by db id.
	 *
	 * @param int $session_row_id DB id.
	 * @return array|null
	 */
	private function load_session_row( $session_row_id ) {
		global $wpdb;
		$table = $this->store->sessions_table();
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$row = $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d LIMIT 1", (int) $session_row_id ),
			ARRAY_A
		);
		return is_array( $row ) ? $row : null;
	}

	/**
	 * Build localized subject line.
	 *
	 * @param bool $is_partial Partial?
	 * @return string
	 */
	private function build_subject( $is_partial ) {
		$suffix = $is_partial
			? __( '(delimično)', 'niwa-ai' )
			: __( '(kompletno)', 'niwa-ai' );
		/* translators: %s = completion status suffix. */
		return sprintf( __( '[Niwa AI] Novi lead — %s', 'niwa-ai' ), $suffix );
	}

	/**
	 * Render HTML body.
	 *
	 * @param array $session    Session row.
	 * @param array $answers    Answer rows.
	 * @param array $schema     Schema.
	 * @param bool  $is_partial Partial?
	 * @return string
	 */
	private function render_html( array $session, array $answers, array $schema, $is_partial ) {
		$site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
		$site_url  = get_site_url();

		$status_line = $is_partial
			? esc_html__( 'Korisnik je ostavio kontakt, ali nije završio kompletnu anketu.', 'niwa-ai' )
			: esc_html__( 'Korisnik je završio kompletnu anketu.', 'niwa-ai' );

		$step_labels = $this->step_label_map( $schema );

		$rows_html = '';
		if ( empty( $answers ) ) {
			$rows_html = '<tr><td colspan="3" style="padding:8px;border:1px solid #ddd;text-align:center;color:#666;">'
				. esc_html__( 'Nema sačuvanih odgovora.', 'niwa-ai' )
				. '</td></tr>';
		} else {
			foreach ( $answers as $ans ) {
				$step_id    = isset( $ans['step_id'] ) ? (string) $ans['step_id'] : '';
				$step_label = isset( $step_labels[ $step_id ] ) ? $step_labels[ $step_id ] : $step_id;
				$q_label    = isset( $ans['question_label'] ) ? (string) $ans['question_label'] : '';
				$a_text     = $this->format_answer_for_display( isset( $ans['answer_text'] ) ? (string) $ans['answer_text'] : '' );

				$rows_html .= '<tr>'
					. '<td style="padding:8px;border:1px solid #ddd;vertical-align:top;">' . esc_html( $step_label ) . '</td>'
					. '<td style="padding:8px;border:1px solid #ddd;vertical-align:top;"><strong>' . esc_html( $q_label ) . '</strong></td>'
					. '<td style="padding:8px;border:1px solid #ddd;vertical-align:top;">' . nl2br( esc_html( $a_text ) ) . '</td>'
					. '</tr>';
			}
		}

		$meta_lines  = array();
		$meta_lines[] = '<li><strong>' . esc_html__( 'Sesija', 'niwa-ai' ) . ':</strong> ' . esc_html( isset( $session['session_id'] ) ? (string) $session['session_id'] : '' ) . '</li>';
		$meta_lines[] = '<li><strong>' . esc_html__( 'Mod', 'niwa-ai' ) . ':</strong> ' . esc_html( isset( $session['mode'] ) ? (string) $session['mode'] : '' ) . '</li>';
		$meta_lines[] = '<li><strong>' . esc_html__( 'Status', 'niwa-ai' ) . ':</strong> ' . esc_html( isset( $session['status'] ) ? (string) $session['status'] : '' ) . '</li>';
		$meta_lines[] = '<li><strong>' . esc_html__( 'Započeto', 'niwa-ai' ) . ':</strong> ' . esc_html( isset( $session['started_at'] ) ? (string) $session['started_at'] : '' ) . '</li>';
		if ( ! empty( $session['ip'] ) ) {
			$meta_lines[] = '<li><strong>' . esc_html__( 'IP', 'niwa-ai' ) . ':</strong> ' . esc_html( (string) $session['ip'] ) . '</li>';
		}

		$html = '<!DOCTYPE html><html><body style="font-family:Arial,Helvetica,sans-serif;color:#222;">'
			. '<h2 style="margin:0 0 8px;">' . esc_html__( 'Novi lead iz Niwa AI', 'niwa-ai' ) . '</h2>'
			. '<p style="margin:0 0 16px;color:#555;">' . esc_html( $site_name ) . ' &mdash; '
			. '<a href="' . esc_url( $site_url ) . '" style="color:#2271b1;">' . esc_html( $site_url ) . '</a></p>'
			. '<p style="margin:0 0 16px;">' . $status_line . '</p>'
			. '<ul style="margin:0 0 16px;padding-left:18px;color:#333;">' . implode( '', $meta_lines ) . '</ul>'
			. '<table style="border-collapse:collapse;width:100%;font-size:14px;">'
			. '<thead><tr style="background:#f5f5f5;">'
			. '<th style="padding:8px;border:1px solid #ddd;text-align:left;">' . esc_html__( 'Step', 'niwa-ai' ) . '</th>'
			. '<th style="padding:8px;border:1px solid #ddd;text-align:left;">' . esc_html__( 'Pitanje', 'niwa-ai' ) . '</th>'
			. '<th style="padding:8px;border:1px solid #ddd;text-align:left;">' . esc_html__( 'Odgovor', 'niwa-ai' ) . '</th>'
			. '</tr></thead>'
			. '<tbody>' . $rows_html . '</tbody>'
			. '</table>'
			. '</body></html>';

		return $html;
	}

	/**
	 * Render plain-text body as fallback.
	 *
	 * @param array $session    Session row.
	 * @param array $answers    Answer rows.
	 * @param array $schema     Schema.
	 * @param bool  $is_partial Partial?
	 * @return string
	 */
	private function render_plain( array $session, array $answers, array $schema, $is_partial ) {
		$lines = array();
		$lines[] = __( 'Novi lead iz Niwa AI', 'niwa-ai' );
		$lines[] = str_repeat( '-', 40 );
		$lines[] = $is_partial
			? __( 'Korisnik je ostavio kontakt, ali nije završio kompletnu anketu.', 'niwa-ai' )
			: __( 'Korisnik je završio kompletnu anketu.', 'niwa-ai' );
		$lines[] = '';
		$lines[] = __( 'Sesija', 'niwa-ai' ) . ': ' . ( isset( $session['session_id'] ) ? (string) $session['session_id'] : '' );
		$lines[] = __( 'Mod', 'niwa-ai' ) . ': ' . ( isset( $session['mode'] ) ? (string) $session['mode'] : '' );
		$lines[] = __( 'Status', 'niwa-ai' ) . ': ' . ( isset( $session['status'] ) ? (string) $session['status'] : '' );
		$lines[] = __( 'Započeto', 'niwa-ai' ) . ': ' . ( isset( $session['started_at'] ) ? (string) $session['started_at'] : '' );
		$lines[] = '';
		$lines[] = str_repeat( '=', 40 );

		$step_labels = $this->step_label_map( $schema );

		if ( empty( $answers ) ) {
			$lines[] = __( 'Nema sačuvanih odgovora.', 'niwa-ai' );
		} else {
			foreach ( $answers as $ans ) {
				$step_id    = isset( $ans['step_id'] ) ? (string) $ans['step_id'] : '';
				$step_label = isset( $step_labels[ $step_id ] ) ? $step_labels[ $step_id ] : $step_id;
				$q_label    = isset( $ans['question_label'] ) ? (string) $ans['question_label'] : '';
				$a_text     = $this->format_answer_for_display( isset( $ans['answer_text'] ) ? (string) $ans['answer_text'] : '' );

				$lines[] = '[' . $step_label . '] ' . $q_label;
				$lines[] = '  → ' . $a_text;
				$lines[] = '';
			}
		}

		return implode( "\n", $lines );
	}

	/**
	 * Build a step-id → step-label lookup from the schema.
	 *
	 * @param array $schema Schema.
	 * @return array<string,string>
	 */
	private function step_label_map( array $schema ) {
		$map   = array();
		$steps = isset( $schema['steps'] ) && is_array( $schema['steps'] ) ? $schema['steps'] : array();
		foreach ( $steps as $step ) {
			if ( ! is_array( $step ) || empty( $step['id'] ) ) {
				continue;
			}
			$map[ (string) $step['id'] ] = isset( $step['label'] ) ? (string) $step['label'] : (string) $step['id'];
		}
		return $map;
	}

	/**
	 * Decode JSON arrays stored as answer_text for nicer display.
	 *
	 * @param string $raw Raw answer_text.
	 * @return string
	 */
	private function format_answer_for_display( $raw ) {
		$raw = (string) $raw;
		if ( '' === $raw ) {
			return '';
		}
		$decoded = json_decode( $raw, true );
		if ( is_array( $decoded ) ) {
			$flat = array_map( 'strval', $decoded );
			return implode( ', ', $flat );
		}
		return $raw;
	}
}
