<?php
/**
 * Brevo email transport for TradeSchool Manager.
 *
 * Routes every wp_mail() send through Brevo's transactional HTTP API
 * (https://api.brevo.com/v3/smtp/email) when enabled. Includes:
 *   - Per-day send counter with configurable cap (Free plan = 300/day)
 *   - Auto-fallback to native wp_mail() when the daily cap is reached or
 *     Brevo returns a quota/rate-limit error (402 / 429)
 *   - Connection test, test-send, and rolling activity log
 *   - "About / Plans" tab explaining the Brevo free tier and upgrade options
 *
 * Brevo's free plan (no credit card) ships with 300 transactional emails per
 * day. We track sends locally and consult /v3/account on demand so the user
 * always knows where they stand.
 *
 * @package TradeSchoolManager
 */

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

class TSMP_Brevo {

	const OPTION         = 'tsmp_brevo_settings';
	const LOG_OPTION     = 'tsmp_brevo_log';
	const COUNTER_OPTION = 'tsmp_brevo_daily_counter';
	const ACCOUNT_CACHE  = 'tsmp_brevo_account_cache';
	const LOG_MAX        = 100;
	const API_BASE       = 'https://api.brevo.com/v3';
	const FREE_DAILY_CAP = 300;

	/** @var bool Re-entry guard so wp_mail() filter doesn't recurse. */
	private static $sending = false;

	public static function init() {
		add_filter( 'wp_mail_from',      array( __CLASS__, 'filter_from_email' ), 99 );
		add_filter( 'wp_mail_from_name', array( __CLASS__, 'filter_from_name' ), 99 );
		add_filter( 'pre_wp_mail',       array( __CLASS__, 'intercept_wp_mail' ), 10, 2 );

		// One-shot migration from the legacy Postmark settings  -  only carry over
		// the From/Reply-To identity. Tokens are not transferable.
		add_action( 'admin_init', array( __CLASS__, 'maybe_migrate_from_postmark' ) );
	}

	public static function defaults() {
		return array(
			'enabled'        => 0,
			'api_key'        => '',
			'from_email'     => get_bloginfo( 'admin_email' ),
			'from_name'      => get_bloginfo( 'name' ),
			'reply_to'       => '',
			'tag_prefix'     => 'tsm',
			// Daily cap. 0 = unlimited (let Brevo's API gate it).
			// Defaults to the free-plan limit so unconfigured installs stay safe.
			'daily_cap'      => self::FREE_DAILY_CAP,
			'fallback_wp_mail' => 1,
			'log_enabled'    => 1,
		);
	}

	public static function get_all() {
		return wp_parse_args( get_option( self::OPTION, array() ), self::defaults() );
	}

	public static function update( $data ) {
		$existing = self::get_all();
		$merged   = array_merge( $existing, $data );
		update_option( self::OPTION, $merged );
		return $merged;
	}

	public static function is_configured() {
		$s = self::get_all();
		return ! empty( $s['enabled'] ) && ! empty( $s['api_key'] ) && ! empty( $s['from_email'] );
	}

	public static function maybe_migrate_from_postmark() {
		if ( get_option( 'tsmp_brevo_migrated_from_postmark' ) ) {
			return;
		}
		$legacy = get_option( 'tsmp_postmark_settings' );
		if ( is_array( $legacy ) ) {
			$carry = array();
			if ( ! empty( $legacy['from_email'] ) ) { $carry['from_email'] = $legacy['from_email']; }
			if ( ! empty( $legacy['from_name'] ) )  { $carry['from_name']  = $legacy['from_name']; }
			if ( ! empty( $legacy['reply_to'] ) )   { $carry['reply_to']   = $legacy['reply_to']; }
			if ( ! empty( $legacy['tag_prefix'] ) ) { $carry['tag_prefix'] = $legacy['tag_prefix']; }
			if ( $carry ) {
				self::update( $carry );
			}
		}
		// Clean up legacy options so the dashboard isn't littered.
		delete_option( 'tsmp_postmark_settings' );
		delete_option( 'tsmp_postmark_log' );
		update_option( 'tsmp_brevo_migrated_from_postmark', 1, false );
	}

	/* -----------------------------------------------------------------
	 * wp_mail() integration
	 * ----------------------------------------------------------------- */

	public static function filter_from_email( $email ) {
		if ( self::$sending ) return $email;
		$s = self::get_all();
		return ! empty( $s['from_email'] ) ? $s['from_email'] : $email;
	}
	public static function filter_from_name( $name ) {
		if ( self::$sending ) return $name;
		$s = self::get_all();
		return ! empty( $s['from_name'] ) ? $s['from_name'] : $name;
	}

	public static function intercept_wp_mail( $pre, $atts ) {
		if ( null !== $pre ) return $pre;
		if ( self::$sending ) return $pre;
		if ( ! self::is_configured() ) return $pre;

		$s = self::get_all();

		// Daily cap check  -  if reached, return null so wp_mail() proceeds
		// with its native PHPMailer/SMTP path (the "fallback").
		if ( self::cap_reached() ) {
			self::log( $atts['to'] ?? '', $atts['subject'] ?? '', false,
				__( 'Daily cap reached  -  falling back to wp_mail()', 'tradeschool-manager' ) );
			return empty( $s['fallback_wp_mail'] ) ? false : null;
		}

		self::$sending = true;
		try {
			$result = self::send_via_api( $atts );
		} catch ( Exception $e ) {
			self::log( $atts['to'] ?? '', $atts['subject'] ?? '', false, '[exception] ' . $e->getMessage() );
			$result = false;
		}
		self::$sending = false;

		// If Brevo signalled a quota/rate-limit failure and fallback is on,
		// return null so wp_mail() handles the send natively.
		if ( false === $result && ! empty( $s['fallback_wp_mail'] ) && self::$last_was_quota_error ) {
			self::$last_was_quota_error = false;
			return null;
		}
		return (bool) $result;
	}

	/* -----------------------------------------------------------------
	 * Daily counter helpers
	 * ----------------------------------------------------------------- */

	private static $last_was_quota_error = false;

	private static function today_key() {
		return gmdate( 'Y-m-d' );
	}

	public static function get_counter() {
		$c = get_option( self::COUNTER_OPTION, array() );
		if ( ! is_array( $c ) || ( $c['date'] ?? '' ) !== self::today_key() ) {
			$c = array( 'date' => self::today_key(), 'sent' => 0 );
		}
		return $c;
	}

	private static function bump_counter() {
		$c = self::get_counter();
		$c['sent']++;
		update_option( self::COUNTER_OPTION, $c, false );
	}

	public static function cap_reached() {
		$s = self::get_all();
		$cap = (int) $s['daily_cap'];
		if ( $cap <= 0 ) return false;
		$c = self::get_counter();
		return $c['sent'] >= $cap;
	}

	/* -----------------------------------------------------------------
	 * Core API send
	 * ----------------------------------------------------------------- */

	private static function send_via_api( $atts ) {
		$s = self::get_all();

		$to_raw      = isset( $atts['to'] ) ? $atts['to'] : '';
		$subject     = isset( $atts['subject'] ) ? $atts['subject'] : '';
		$message     = isset( $atts['message'] ) ? $atts['message'] : '';
		$headers_in  = isset( $atts['headers'] ) ? $atts['headers'] : array();
		$attachments = isset( $atts['attachments'] ) ? $atts['attachments'] : array();

		$parsed = self::parse_headers( $headers_in );
		$is_html = ( stripos( $parsed['content_type'], 'text/html' ) !== false ) || self::looks_like_html( $message );

		$from_email = ! empty( $parsed['from_email'] ) ? $parsed['from_email'] : $s['from_email'];
		$from_name  = ! empty( $parsed['from_name'] )  ? $parsed['from_name']  : $s['from_name'];
		$reply_to   = ! empty( $parsed['reply_to'] )   ? $parsed['reply_to']   : $s['reply_to'];

		$tag = ! empty( $parsed['x_tsm_tag'] ) ? $parsed['x_tsm_tag'] : 'general';
		if ( ! empty( $s['tag_prefix'] ) ) { $tag = $s['tag_prefix'] . '-' . $tag; }

		$body = array(
			'sender'  => array( 'email' => $from_email ) + ( $from_name ? array( 'name' => $from_name ) : array() ),
			'to'      => self::emails_to_brevo( $to_raw ),
			'subject' => (string) $subject,
			'tags'    => array( $tag ),
		);
		if ( $is_html ) {
			$body['htmlContent'] = $message;
			$body['textContent'] = self::html_to_text( $message );
		} else {
			$body['textContent'] = $message;
		}
		if ( $reply_to )            { $body['replyTo'] = array( 'email' => $reply_to ); }
		if ( ! empty( $parsed['cc'] ) )  { $body['cc']  = self::emails_to_brevo( $parsed['cc'] ); }
		if ( ! empty( $parsed['bcc'] ) ) { $body['bcc'] = self::emails_to_brevo( $parsed['bcc'] ); }
		if ( ! empty( $attachments ) ) {
			$body['attachment'] = self::build_attachments( (array) $attachments );
		}

		$resp = wp_remote_post( self::API_BASE . '/smtp/email', array(
			'timeout' => 20,
			'headers' => array(
				'accept'       => 'application/json',
				'content-type' => 'application/json',
				'api-key'      => $s['api_key'],
			),
			'body'    => wp_json_encode( $body ),
		) );

		if ( is_wp_error( $resp ) ) {
			self::log( $to_raw, $subject, false, $resp->get_error_message() );
			return false;
		}
		$code = wp_remote_retrieve_response_code( $resp );
		$json = json_decode( wp_remote_retrieve_body( $resp ), true );
		$ok   = ( $code >= 200 && $code < 300 );
		$msg  = $ok
			? ( $json['messageId'] ?? 'sent' )
			: sprintf( 'HTTP %d: %s', $code, ( $json['message'] ?? ( $json['code'] ?? 'unknown error' ) ) );

		if ( $ok ) {
			self::bump_counter();
		} elseif ( 402 === (int) $code || 429 === (int) $code ) {
			self::$last_was_quota_error = true;
		}

		self::log( $to_raw, $subject, $ok, $msg );
		return $ok;
	}

	/* -----------------------------------------------------------------
	 * Helpers
	 * ----------------------------------------------------------------- */

	private static function emails_to_brevo( $value ) {
		if ( is_array( $value ) ) {
			$items = $value;
		} else {
			$items = array_map( 'trim', preg_split( '/[,;]/', (string) $value ) );
		}
		$out = array();
		foreach ( $items as $entry ) {
			if ( ! $entry ) continue;
			$name = '';
			$email = $entry;
			if ( preg_match( '/(.*)<(.+)>/', $entry, $m ) ) {
				$name  = trim( $m[1], " \"'\t" );
				$email = trim( $m[2] );
			}
			if ( ! is_email( $email ) ) continue;
			$o = array( 'email' => $email );
			if ( $name ) $o['name'] = $name;
			$out[] = $o;
		}
		return $out;
	}

	private static function parse_headers( $headers ) {
		$out = array(
			'content_type' => 'text/plain', 'from_email' => '', 'from_name' => '',
			'cc' => '', 'bcc' => '', 'reply_to' => '', 'x_tsm_tag' => '',
		);
		if ( empty( $headers ) ) return $out;
		if ( ! is_array( $headers ) ) {
			$headers = preg_split( "/\r\n|\n|\r/", (string) $headers );
		}
		foreach ( $headers as $h ) {
			if ( strpos( $h, ':' ) === false ) continue;
			list( $k, $v ) = array_map( 'trim', explode( ':', $h, 2 ) );
			switch ( strtolower( $k ) ) {
				case 'content-type': $out['content_type'] = $v; break;
				case 'from':
					if ( preg_match( '/(.*)<(.+)>/', $v, $m ) ) {
						$out['from_name']  = trim( $m[1], " \"'\t" );
						$out['from_email'] = trim( $m[2] );
					} else { $out['from_email'] = trim( $v ); }
					break;
				case 'cc':       $out['cc']       = $v; break;
				case 'bcc':      $out['bcc']      = $v; break;
				case 'reply-to': $out['reply_to'] = $v; break;
				case 'x-tsm-tag': $out['x_tsm_tag'] = $v; break;
			}
		}
		return $out;
	}

	private static function looks_like_html( $msg ) {
		return is_string( $msg ) && preg_match( '/<\s*(html|body|p|div|table|a|br|img|h[1-6])\b/i', $msg );
	}

	private static function html_to_text( $html ) {
		$t = preg_replace( '#<br\s*/?>#i', "\n", $html );
		$t = preg_replace( '#</p>#i', "\n\n", $t );
		$t = wp_strip_all_tags( $t );
		$t = html_entity_decode( $t, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
		return trim( preg_replace( "/\n{3,}/", "\n\n", $t ) );
	}

	private static function build_attachments( $files ) {
		$out = array();
		foreach ( $files as $path ) {
			if ( ! is_string( $path ) || ! file_exists( $path ) ) continue;
			$content = @file_get_contents( $path );
			if ( false === $content ) continue;
			$out[] = array(
				'name'    => basename( $path ),
				'content' => base64_encode( $content ),
			);
		}
		return $out;
	}

	private static function log( $to, $subject, $ok, $detail ) {
		$s = self::get_all();
		if ( empty( $s['log_enabled'] ) ) return;
		$log = get_option( self::LOG_OPTION, array() );
		if ( ! is_array( $log ) ) $log = array();
		array_unshift( $log, array(
			'time'    => current_time( 'mysql' ),
			'to'      => is_string( $to ) ? $to : wp_json_encode( $to ),
			'subject' => (string) $subject,
			'ok'      => $ok ? 1 : 0,
			'detail'  => mb_substr( (string) $detail, 0, 300 ),
		) );
		if ( count( $log ) > self::LOG_MAX ) $log = array_slice( $log, 0, self::LOG_MAX );
		update_option( self::LOG_OPTION, $log, false );
	}

	public static function clear_log() { delete_option( self::LOG_OPTION ); }

	/* -----------------------------------------------------------------
	 * Brevo account info (plan + remaining credits)
	 * ----------------------------------------------------------------- */

	public static function fetch_account( $key = '', $force = false ) {
		$s = self::get_all();
		$key = $key ?: $s['api_key'];
		if ( ! $key ) return new WP_Error( 'no_key', __( 'Brevo API key is required.', 'tradeschool-manager' ) );

		if ( ! $force ) {
			$cached = get_transient( self::ACCOUNT_CACHE );
			if ( is_array( $cached ) ) return $cached;
		}

		$resp = wp_remote_get( self::API_BASE . '/account', array(
			'timeout' => 15,
			'headers' => array( 'accept' => 'application/json', 'api-key' => $key ),
		) );
		if ( is_wp_error( $resp ) ) return $resp;
		$code = wp_remote_retrieve_response_code( $resp );
		$json = json_decode( wp_remote_retrieve_body( $resp ), true );
		if ( $code !== 200 || ! is_array( $json ) ) {
			return new WP_Error( 'bad_key', sprintf(
				/* translators: 1: HTTP status code, 2: Brevo error message */
				__( 'Brevo rejected the API key (HTTP %1$d): %2$s', 'tradeschool-manager' ),
				$code, $json['message'] ?? ''
			) );
		}
		set_transient( self::ACCOUNT_CACHE, $json, 5 * MINUTE_IN_SECONDS );
		return $json;
	}

	public static function send_test_email( $to ) {
		if ( ! is_email( $to ) ) return new WP_Error( 'bad_email', __( 'Invalid recipient email.', 'tradeschool-manager' ) );
		/* translators: %s: site name */
		$subject = sprintf( __( '[Test] %s  -  Brevo integration is working', 'tradeschool-manager' ), get_bloginfo( 'name' ) );
		$html = '<p>This is a test email sent from your TradeSchool Manager plugin via the Brevo API.</p>'
		      . '<p>If you received it, your transactional email pipeline is working correctly.</p>'
		      . '<p> -  ' . esc_html( get_bloginfo( 'name' ) ) . '</p>';
		$ok = wp_mail( $to, $subject, $html, array(
			'Content-Type: text/html; charset=UTF-8',
			'X-TSM-Tag: test',
		) );
		return $ok ? true : new WP_Error( 'send_fail', __( 'wp_mail() returned false. Check the log below for the Brevo error message.', 'tradeschool-manager' ) );
	}

	/* -----------------------------------------------------------------
	 * Admin screen
	 * ----------------------------------------------------------------- */

	public static function render_admin() {
		if ( ! current_user_can( 'manage_options' ) ) return;

		$tab = isset( $_GET['btab'] ) ? sanitize_key( wp_unslash( $_GET['btab'] ) ) : 'standard';

		// -------- Standard Mail (wp_mail) POST handlers --------
		if ( class_exists( 'TSMP_Mail' ) ) {
			if ( isset( $_POST['tsm_mail_save_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsm_mail_save_nonce'] ) ), 'tsm_mail_save' ) ) {
				TSMP_Mail::update( array(
					'from_name'    => sanitize_text_field( wp_unslash( $_POST['from_name'] ?? '' ) ),
					'from_email'   => sanitize_email( wp_unslash( $_POST['from_email'] ?? '' ) ),
					'reply_to'     => sanitize_email( wp_unslash( $_POST['reply_to'] ?? '' ) ),
					'force_sender' => ! empty( $_POST['force_sender'] ) ? 1 : 0,
					'log_enabled'  => ! empty( $_POST['log_enabled'] ) ? 1 : 0,
				) );
				echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Standard Mail settings saved.', 'tradeschool-manager' ) . '</p></div>';
			}
			if ( isset( $_POST['tsm_mail_test_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsm_mail_test_nonce'] ) ), 'tsm_mail_test' ) ) {
				$to  = sanitize_email( wp_unslash( $_POST['test_to'] ?? '' ) );
				$res = TSMP_Mail::send_test( $to );
				if ( is_wp_error( $res ) ) {
					echo '<div class="notice notice-error"><p>' . esc_html( $res->get_error_message() ) . '</p></div>';
				} else {
					/* translators: %s: recipient email */
					echo '<div class="notice notice-success"><p>' . esc_html( sprintf( __( 'Test email sent to %s. See log below.', 'tradeschool-manager' ), $to ) ) . '</p></div>';
				}
			}
			if ( isset( $_POST['tsm_mail_clear_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsm_mail_clear_nonce'] ) ), 'tsm_mail_clear' ) ) {
				TSMP_Mail::clear_log();
				echo '<div class="notice notice-success"><p>' . esc_html__( 'wp_mail log cleared.', 'tradeschool-manager' ) . '</p></div>';
			}
		}

		// Save settings.
		if ( isset( $_POST['tsmp_brevo_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsmp_brevo_nonce'] ) ), 'tsmp_brevo' ) ) {
			$payload = array(
				'enabled'          => ! empty( $_POST['enabled'] ) ? 1 : 0,
				'api_key'          => sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) ),
				'from_email'       => sanitize_email( wp_unslash( $_POST['from_email'] ?? '' ) ),
				'from_name'        => sanitize_text_field( wp_unslash( $_POST['from_name'] ?? '' ) ),
				'reply_to'         => sanitize_email( wp_unslash( $_POST['reply_to'] ?? '' ) ),
				'tag_prefix'       => sanitize_key( wp_unslash( $_POST['tag_prefix'] ?? 'tsm' ) ),
				'daily_cap'        => max( 0, absint( $_POST['daily_cap'] ?? self::FREE_DAILY_CAP ) ),
				'fallback_wp_mail' => ! empty( $_POST['fallback_wp_mail'] ) ? 1 : 0,
				'log_enabled'      => ! empty( $_POST['log_enabled'] ) ? 1 : 0,
			);
			self::update( $payload );
			delete_transient( self::ACCOUNT_CACHE );
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Brevo settings saved.', 'tradeschool-manager' ) . '</p></div>';
		}

		if ( isset( $_POST['tsmp_brevo_test_conn_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsmp_brevo_test_conn_nonce'] ) ), 'tsmp_brevo_test_conn' ) ) {
			$res = self::fetch_account( '', true );
			if ( is_wp_error( $res ) ) {
				echo '<div class="notice notice-error"><p>' . esc_html( $res->get_error_message() ) . '</p></div>';
			} else {
				$label = trim( ( $res['firstName'] ?? '' ) . ' ' . ( $res['lastName'] ?? '' ) ) ?: ( $res['email'] ?? '?' );
				/* translators: %s: Brevo account label (name or email) */
				echo '<div class="notice notice-success"><p>' . esc_html( sprintf( __( 'Connected to Brevo account: %s', 'tradeschool-manager' ), $label ) ) . '</p></div>';
			}
		}

		if ( isset( $_POST['tsmp_brevo_test_send_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsmp_brevo_test_send_nonce'] ) ), 'tsmp_brevo_test_send' ) ) {
			$to  = sanitize_email( wp_unslash( $_POST['test_to'] ?? '' ) );
			$res = self::send_test_email( $to );
			if ( is_wp_error( $res ) ) {
				echo '<div class="notice notice-error"><p>' . esc_html( $res->get_error_message() ) . '</p></div>';
			} else {
				/* translators: %s: recipient email address */
				echo '<div class="notice notice-success"><p>' . esc_html( sprintf( __( 'Test email queued to %s. Check the log below for confirmation.', 'tradeschool-manager' ), $to ) ) . '</p></div>';
			}
		}

		if ( isset( $_POST['tsmp_brevo_clear_log_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsmp_brevo_clear_log_nonce'] ) ), 'tsmp_brevo_clear_log' ) ) {
			self::clear_log();
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Log cleared.', 'tradeschool-manager' ) . '</p></div>';
		}

		TSM_Inline_Assets::style(
			'tsmp-brevo-admin',
			'.tsm-bv-card{background:#fff;border:1px solid #c3c4c7;border-radius:8px;padding:18px 22px;margin:16px 0;box-shadow:0 1px 1px rgba(0,0,0,.04);}.tsm-bv-card h3{margin-top:0;}.tsm-bv-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;}.tsm-bv-status{display:inline-block;padding:3px 10px;border-radius:999px;font-size:12px;font-weight:600;}.tsm-bv-status.ok{background:#d1fae5;color:#065f46;}.tsm-bv-status.off{background:#fee2e2;color:#991b1b;}.tsm-bv-status.warn{background:#fef3c7;color:#92400e;}.tsm-bv-log{width:100%;border-collapse:collapse;font-size:13px;}.tsm-bv-log th,.tsm-bv-log td{border-bottom:1px solid #eee;padding:8px 10px;text-align:left;vertical-align:top;}.tsm-bv-log .ok{color:#065f46;font-weight:600;}.tsm-bv-log .err{color:#991b1b;font-weight:600;}.tsm-bv-meter{height:10px;background:#eef2f6;border-radius:999px;overflow:hidden;margin:6px 0 4px;}.tsm-bv-meter span{display:block;height:100%;background:linear-gradient(90deg,#3b82f6,#06b6d4);}.tsm-bv-meter.warn span{background:linear-gradient(90deg,#f59e0b,#ef4444);}.tsm-bv-tabs{margin:8px 0 0;border-bottom:1px solid #c3c4c7;}.tsm-bv-tabs a{display:inline-block;padding:8px 16px;text-decoration:none;color:#1d2327;border:1px solid transparent;border-bottom:none;border-radius:6px 6px 0 0;margin-right:4px;}.tsm-bv-tabs a.active{background:#fff;border-color:#c3c4c7;font-weight:600;}.tsm-bv-plans{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px;}.tsm-bv-plan{border:1px solid #e5e7eb;border-radius:8px;padding:16px;background:#fafbfc;}.tsm-bv-plan h4{margin:0 0 4px;font-size:15px;}.tsm-bv-plan .price{font-size:22px;font-weight:700;margin:6px 0;}.tsm-bv-plan ul{margin:8px 0 0 18px;padding:0;font-size:13px;color:#3c434a;}@media (max-width: 900px){ .tsm-bv-grid{grid-template-columns:1fr;} }'
		);

		?>
		<h2 class="tsm-bv-tabs">
			<a class="<?php echo 'standard' === $tab ? 'active' : ''; ?>" href="<?php echo esc_url( add_query_arg( 'btab', 'standard' ) ); ?>"><?php esc_html_e( 'Standard Mail', 'tradeschool-manager' ); ?></a>
			<a class="<?php echo 'settings' === $tab ? 'active' : ''; ?>" href="<?php echo esc_url( add_query_arg( 'btab', 'settings' ) ); ?>"><?php esc_html_e( 'Brevo', 'tradeschool-manager' ); ?></a>
			<a class="<?php echo 'about' === $tab ? 'active' : ''; ?>"    href="<?php echo esc_url( add_query_arg( 'btab', 'about' ) ); ?>"><?php esc_html_e( 'About Brevo & Plans', 'tradeschool-manager' ); ?></a>
		</h2>

		<?php
		if ( 'about' === $tab ) {
			self::render_about_tab();
		} elseif ( 'settings' === $tab ) {
			self::render_settings_tab();
		} else {
			self::render_standard_tab();
		}
	}

	/* -----------------------------------------------------------------
	 * Standard Mail tab (wp_mail identity, force sender, activity log)
	 * ----------------------------------------------------------------- */
	private static function render_standard_tab() {
		if ( ! class_exists( 'TSMP_Mail' ) ) {
			echo '<div class="tsm-bv-card"><p>' . esc_html__( 'Standard Mail module unavailable.', 'tradeschool-manager' ) . '</p></div>';
			return;
		}
		$m            = TSMP_Mail::get_all();
		$brevo_active = self::is_configured();
		?>
		<div class="tsm-bv-card">
			<h3>
				<?php esc_html_e( 'wp_mail()  -  Native WordPress Delivery', 'tradeschool-manager' ); ?>
				<span class="tsm-bv-status <?php echo $brevo_active ? 'warn' : 'ok'; ?>" style="margin-left:8px;">
					<?php echo $brevo_active ? esc_html__( 'Standby (Brevo active)', 'tradeschool-manager' ) : esc_html__( 'Active', 'tradeschool-manager' ); ?>
				</span>
			</h3>
			<p class="description">
				<?php esc_html_e( 'Configure how WordPress sends mail via the native wp_mail() function. These identity settings work with any SMTP plugin you already run. If Brevo is enabled on the next tab, Brevo handles delivery instead  -  but these values are still used as fallback defaults.', 'tradeschool-manager' ); ?>
			</p>
			<form method="post">
				<?php wp_nonce_field( 'tsm_mail_save', 'tsm_mail_save_nonce' ); ?>
				<table class="form-table">
					<tr><th><?php esc_html_e( 'From Name', 'tradeschool-manager' ); ?></th>
						<td><input class="regular-text" name="from_name" value="<?php echo esc_attr( $m['from_name'] ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'From Email', 'tradeschool-manager' ); ?></th>
						<td><input type="email" class="regular-text" name="from_email" value="<?php echo esc_attr( $m['from_email'] ); ?>">
							<p class="description"><?php esc_html_e( 'Use an address on a domain you control. Generic addresses (gmail, yahoo, etc.) are commonly rejected by receiving servers.', 'tradeschool-manager' ); ?></p></td></tr>
					<tr><th><?php esc_html_e( 'Reply-To Email', 'tradeschool-manager' ); ?></th>
						<td><input type="email" class="regular-text" name="reply_to" value="<?php echo esc_attr( $m['reply_to'] ); ?>" placeholder="<?php esc_attr_e( 'Optional  -  defaults to From Email', 'tradeschool-manager' ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Force Sender Identity', 'tradeschool-manager' ); ?></th>
						<td><label><input type="checkbox" name="force_sender" value="1" <?php checked( $m['force_sender'] ); ?>>
							<?php esc_html_e( 'Always override From / From Name on every outgoing email, even when other plugins set their own.', 'tradeschool-manager' ); ?></label></td></tr>
					<tr><th><?php esc_html_e( 'Activity Log', 'tradeschool-manager' ); ?></th>
						<td><label><input type="checkbox" name="log_enabled" value="1" <?php checked( $m['log_enabled'] ); ?>>
							<?php esc_html_e( 'Keep the last 100 wp_mail() attempts for troubleshooting.', 'tradeschool-manager' ); ?></label></td></tr>
				</table>
				<p><button class="button button-primary"><?php esc_html_e( 'Save Standard Mail Settings', 'tradeschool-manager' ); ?></button></p>
			</form>

			<hr style="margin:18px 0;">
			<form method="post" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
				<?php wp_nonce_field( 'tsm_mail_test', 'tsm_mail_test_nonce' ); ?>
				<label style="font-weight:600;"><?php esc_html_e( 'Send test email to:', 'tradeschool-manager' ); ?></label>
				<input type="email" name="test_to" class="regular-text" required value="<?php echo esc_attr( wp_get_current_user()->user_email ); ?>">
				<button class="button"><?php esc_html_e( 'Send Test', 'tradeschool-manager' ); ?></button>
			</form>
		</div>

		<div class="tsm-bv-card">
			<h3 style="display:flex;justify-content:space-between;align-items:center;">
				<?php esc_html_e( 'wp_mail()  -  Last 100 Sends', 'tradeschool-manager' ); ?>
				<?php $log = TSMP_Mail::get_log(); if ( ! empty( $log ) ) : ?>
					<form method="post" style="margin:0;">
						<?php wp_nonce_field( 'tsm_mail_clear', 'tsm_mail_clear_nonce' ); ?>
						<button class="button button-small"><?php esc_html_e( 'Clear log', 'tradeschool-manager' ); ?></button>
					</form>
				<?php endif; ?>
			</h3>
			<?php if ( empty( $log ) ) : ?>
				<p class="description"><?php esc_html_e( 'No emails have been sent yet (or the log is disabled).', 'tradeschool-manager' ); ?></p>
			<?php else : ?>
				<table class="tsm-bv-log">
					<thead><tr>
						<th style="width:150px;"><?php esc_html_e( 'Time', 'tradeschool-manager' ); ?></th>
						<th style="width:80px;"><?php esc_html_e( 'Status', 'tradeschool-manager' ); ?></th>
						<th><?php esc_html_e( 'To', 'tradeschool-manager' ); ?></th>
						<th><?php esc_html_e( 'Subject', 'tradeschool-manager' ); ?></th>
						<th><?php esc_html_e( 'Detail', 'tradeschool-manager' ); ?></th>
					</tr></thead>
					<tbody>
					<?php foreach ( $log as $row ) :
						$status = $row['status'] ?? 'pending';
						$cls    = 'sent' === $status ? 'ok' : ( 'failed' === $status ? 'err' : '' );
					?>
						<tr>
							<td><code><?php echo esc_html( $row['time'] ?? '' ); ?></code></td>
							<td class="<?php echo esc_attr( $cls ); ?>"><?php echo esc_html( ucfirst( $status ) ); ?></td>
							<td><?php echo esc_html( $row['to'] ?? '' ); ?></td>
							<td><?php echo esc_html( $row['subject'] ?? '' ); ?></td>
							<td><code style="font-size:11px;"><?php echo esc_html( $row['detail'] ?? '' ); ?></code></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>
		<?php
	}


	private static function render_settings_tab() {
		$s       = self::get_all();
		$log     = get_option( self::LOG_OPTION, array() );
		$counter = self::get_counter();
		$cap     = (int) $s['daily_cap'];
		$pct     = $cap > 0 ? min( 100, (int) round( ( $counter['sent'] / $cap ) * 100 ) ) : 0;
		$account = self::is_configured() ? self::fetch_account() : null;

		?>
		<div class="tsm-bv-card">
			<h3>
				<?php esc_html_e( 'Brevo Status', 'tradeschool-manager' ); ?>
				<?php if ( self::is_configured() ) : ?>
					<span class="tsm-bv-status ok"><?php esc_html_e( 'Active', 'tradeschool-manager' ); ?></span>
				<?php else : ?>
					<span class="tsm-bv-status off"><?php esc_html_e( 'Inactive', 'tradeschool-manager' ); ?></span>
				<?php endif; ?>
				<?php if ( self::cap_reached() ) : ?>
					<span class="tsm-bv-status warn" title="<?php esc_attr_e( 'Falling back to wp_mail until tomorrow', 'tradeschool-manager' ); ?>"><?php esc_html_e( 'Daily cap reached', 'tradeschool-manager' ); ?></span>
				<?php endif; ?>
			</h3>
			<p class="description">
				<?php esc_html_e( 'When Active, every email sent by this plugin (and by WordPress) is routed through the Brevo transactional API. Brevo is included with TradeSchool Manager at no extra cost  -  you only need a free Brevo account and an API key. Verify your sender domain in Brevo (DKIM / DMARC) for the best deliverability.', 'tradeschool-manager' ); ?>
			</p>

			<?php if ( $cap > 0 ) : ?>
				<p style="margin-top:14px;"><strong><?php esc_html_e( "Today's sends", 'tradeschool-manager' ); ?>:</strong>
					<?php echo esc_html( sprintf( '%d / %d', (int) $counter['sent'], $cap ) ); ?>
					<span class="description">(<?php echo esc_html( $counter['date'] ); ?> UTC)</span></p>
				<div class="tsm-bv-meter <?php echo $pct >= 80 ? 'warn' : ''; ?>"><span style="width:<?php echo (int) $pct; ?>%"></span></div>
			<?php else : ?>
				<p style="margin-top:14px;"><strong><?php esc_html_e( "Today's sends", 'tradeschool-manager' ); ?>:</strong>
					<?php echo esc_html( sprintf( '%d (no local cap)', (int) $counter['sent'] ) ); ?></p>
			<?php endif; ?>

			<?php if ( is_array( $account ) ) : ?>
				<p class="description" style="margin-top:10px;">
					<?php
					$plan_label = ' - ';
					if ( ! empty( $account['plan'][0] ) ) {
						$p = $account['plan'][0];
						$plan_label = ( $p['type'] ?? '' ) . ' - ' . ( $p['credits'] ?? '?' ) . ' ' . ( $p['creditsType'] ?? 'credits' );
					}
					echo esc_html( sprintf(
						/* translators: placeholder(s) for dynamic value(s). */
						__( 'Brevo account: %1$s  -  Plan: %2$s', 'tradeschool-manager' ),
						$account['email'] ?? '?',
						$plan_label
					) );
					?>
				</p>
			<?php endif; ?>
		</div>

		<form method="post" class="tsm-bv-card">
			<?php wp_nonce_field( 'tsmp_brevo', 'tsmp_brevo_nonce' ); ?>
			<h3><?php esc_html_e( 'Connection', 'tradeschool-manager' ); ?></h3>
			<table class="form-table">
				<tr>
					<th><?php esc_html_e( 'Enable Brevo', 'tradeschool-manager' ); ?></th>
					<td><label><input type="checkbox" name="enabled" value="1" <?php checked( $s['enabled'] ); ?>>
						<?php esc_html_e( 'Send all plugin email through Brevo', 'tradeschool-manager' ); ?></label></td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'API v3 Key', 'tradeschool-manager' ); ?></th>
					<td><input type="password" class="large-text code" name="api_key" value="<?php echo esc_attr( $s['api_key'] ); ?>" autocomplete="off">
						<p class="description"><?php
							printf(
								/* translators: placeholder(s) for dynamic value(s). */
								wp_kses_post( __( 'Create one in Brevo  <strong>SMTP &amp; API  API Keys</strong>. <a href="%s" target="_blank" rel="noopener">Open Brevo dashboard</a>.', 'tradeschool-manager' ) ),
								'https://app.brevo.com/settings/keys/api'
							);
						?></p></td>
				</tr>
			</table>

			<h3><?php esc_html_e( 'Sender Identity', 'tradeschool-manager' ); ?></h3>
			<div class="tsm-bv-grid">
				<p><label><strong><?php esc_html_e( 'From Email', 'tradeschool-manager' ); ?></strong><br>
					<input type="email" class="regular-text" name="from_email" value="<?php echo esc_attr( $s['from_email'] ); ?>"></label>
					<br><span class="description"><?php esc_html_e( 'Must be on a domain you have authenticated in Brevo (Senders & IP  Domains).', 'tradeschool-manager' ); ?></span></p>
				<p><label><strong><?php esc_html_e( 'From Name', 'tradeschool-manager' ); ?></strong><br>
					<input type="text" class="regular-text" name="from_name" value="<?php echo esc_attr( $s['from_name'] ); ?>"></label></p>
				<p><label><strong><?php esc_html_e( 'Reply-To (optional)', 'tradeschool-manager' ); ?></strong><br>
					<input type="email" class="regular-text" name="reply_to" value="<?php echo esc_attr( $s['reply_to'] ); ?>"></label></p>
				<p><label><strong><?php esc_html_e( 'Tag Prefix', 'tradeschool-manager' ); ?></strong><br>
					<input type="text" class="regular-text" name="tag_prefix" value="<?php echo esc_attr( $s['tag_prefix'] ); ?>"></label>
					<br><span class="description"><?php esc_html_e( 'Prepended to every Brevo tag (e.g. tsm-welcome, tsm-grade).', 'tradeschool-manager' ); ?></span></p>
			</div>

			<h3><?php esc_html_e( 'Daily Limit & Fallback', 'tradeschool-manager' ); ?></h3>
			<table class="form-table">
				<tr>
					<th><?php esc_html_e( 'Daily send cap', 'tradeschool-manager' ); ?></th>
					<td>
						<input type="number" min="0" step="1" name="daily_cap" value="<?php echo esc_attr( $s['daily_cap'] ); ?>" class="small-text">
						<p class="description"><?php
							echo esc_html( sprintf(
								/* translators: %d: Brevo Free plan daily cap (numeric) */
								__( 'Match this to your Brevo plan limit. Free plan = %d emails/day. Use 0 to disable the local cap and let Brevo handle quota enforcement.', 'tradeschool-manager' ),
								self::FREE_DAILY_CAP
							) );
						?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Fallback to wp_mail()', 'tradeschool-manager' ); ?></th>
					<td><label><input type="checkbox" name="fallback_wp_mail" value="1" <?php checked( $s['fallback_wp_mail'] ); ?>>
						<?php esc_html_e( 'When the cap is hit or Brevo returns 402/429, deliver the email through the site\'s native wp_mail() instead of failing.', 'tradeschool-manager' ); ?></label></td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Activity log', 'tradeschool-manager' ); ?></th>
					<td><label><input type="checkbox" name="log_enabled" value="1" <?php checked( $s['log_enabled'] ); ?>> <?php esc_html_e( 'Keep the last 100 sends in the log below', 'tradeschool-manager' ); ?></label></td>
				</tr>
			</table>

			<p><button class="button button-primary"><?php esc_html_e( 'Save Brevo Settings', 'tradeschool-manager' ); ?></button></p>
		</form>

		<div class="tsm-bv-card">
			<h3><?php esc_html_e( 'Diagnostics', 'tradeschool-manager' ); ?></h3>
			<div class="tsm-bv-grid">
				<form method="post">
					<?php wp_nonce_field( 'tsmp_brevo_test_conn', 'tsmp_brevo_test_conn_nonce' ); ?>
					<p><strong><?php esc_html_e( 'Test API Key', 'tradeschool-manager' ); ?></strong></p>
					<p class="description"><?php esc_html_e( 'Pings the Brevo /v3/account endpoint with the saved key.', 'tradeschool-manager' ); ?></p>
					<p><button class="button"><?php esc_html_e( 'Test Connection', 'tradeschool-manager' ); ?></button></p>
				</form>
				<form method="post">
					<?php wp_nonce_field( 'tsmp_brevo_test_send', 'tsmp_brevo_test_send_nonce' ); ?>
					<p><strong><?php esc_html_e( 'Send Test Email', 'tradeschool-manager' ); ?></strong></p>
					<p><input type="email" name="test_to" class="regular-text" placeholder="you@example.com" value="<?php echo esc_attr( wp_get_current_user()->user_email ); ?>" required></p>
					<p><button class="button"><?php esc_html_e( 'Send Test', 'tradeschool-manager' ); ?></button></p>
				</form>
			</div>
		</div>

		<div class="tsm-bv-card">
			<h3 style="display:flex;justify-content:space-between;align-items:center;">
				<?php esc_html_e( 'Recent Sends (last 100)', 'tradeschool-manager' ); ?>
				<form method="post" style="margin:0;">
					<?php wp_nonce_field( 'tsmp_brevo_clear_log', 'tsmp_brevo_clear_log_nonce' ); ?>
					<button class="button button-small"><?php esc_html_e( 'Clear log', 'tradeschool-manager' ); ?></button>
				</form>
			</h3>
			<?php if ( empty( $log ) ) : ?>
				<p class="description"><?php esc_html_e( 'No sends recorded yet.', 'tradeschool-manager' ); ?></p>
			<?php else : ?>
				<table class="tsm-bv-log">
					<thead><tr>
						<th><?php esc_html_e( 'Time', 'tradeschool-manager' ); ?></th>
						<th><?php esc_html_e( 'To', 'tradeschool-manager' ); ?></th>
						<th><?php esc_html_e( 'Subject', 'tradeschool-manager' ); ?></th>
						<th><?php esc_html_e( 'Status', 'tradeschool-manager' ); ?></th>
						<th><?php esc_html_e( 'Detail / MessageID', 'tradeschool-manager' ); ?></th>
					</tr></thead>
					<tbody>
					<?php foreach ( $log as $row ) : ?>
						<tr>
							<td><?php echo esc_html( $row['time'] ); ?></td>
							<td><?php echo esc_html( $row['to'] ); ?></td>
							<td><?php echo esc_html( $row['subject'] ); ?></td>
							<td class="<?php echo $row['ok'] ? 'ok' : 'err'; ?>"><?php echo $row['ok'] ? 'Sent' : 'Failed'; ?></td>
							<td><code style="font-size:11px;"><?php echo esc_html( $row['detail'] ); ?></code></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>
		<?php
	}

	private static function render_about_tab() {
		?>
		<div class="tsm-bv-card">
			<h3><?php esc_html_e( 'Why Brevo?', 'tradeschool-manager' ); ?></h3>
			<p><?php esc_html_e( 'Brevo (formerly Sendinblue) is a reputable European email service provider with a genuinely generous free tier  -  no credit card required to start. For a small trade school sending welcome emails, grade notifications, payment reminders, and the occasional broadcast to students, the free plan is usually enough to cover daily operations.', 'tradeschool-manager' ); ?></p>
			<p><?php esc_html_e( 'TradeSchool Manager bundles the Brevo integration in core at no additional cost. You only pay Brevo if you outgrow their free plan.', 'tradeschool-manager' ); ?></p>
		</div>

		<div class="tsm-bv-card">
			<h3><?php esc_html_e( 'Free Tier  -  What You Get', 'tradeschool-manager' ); ?></h3>
			<ul style="line-height:1.7;">
				<li><strong><?php esc_html_e( '300 transactional emails per day', 'tradeschool-manager' ); ?></strong> <?php esc_html_e( '(about 9,000 / month)  -  counter resets every 24 hours.', 'tradeschool-manager' ); ?></li>
				<li><?php esc_html_e( 'Unlimited contacts in your Brevo address book.', 'tradeschool-manager' ); ?></li>
				<li><?php esc_html_e( 'DKIM/DMARC domain authentication for high deliverability.', 'tradeschool-manager' ); ?></li>
				<li><?php esc_html_e( 'Open & click tracking, bounce/complaint handling.', 'tradeschool-manager' ); ?></li>
				<li><?php esc_html_e( 'Brevo branding appears in the email footer on the free tier.', 'tradeschool-manager' ); ?></li>
			</ul>
			<p class="description"><?php esc_html_e( 'When you reach the 300/day limit, this plugin automatically falls back to your site\'s native wp_mail() so no email is lost  -  and resumes Brevo delivery the next day.', 'tradeschool-manager' ); ?></p>
		</div>

		<div class="tsm-bv-card">
			<h3><?php esc_html_e( 'Upgrading Brevo', 'tradeschool-manager' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Pricing changes over time  -  always check Brevo for current rates. Typical paid tiers as of writing:', 'tradeschool-manager' ); ?></p>
			<div class="tsm-bv-plans">
				<div class="tsm-bv-plan">
					<h4><?php esc_html_e( 'Free', 'tradeschool-manager' ); ?></h4>
					<div class="price">$0</div>
					<ul>
						<li><?php esc_html_e( '300 emails / day', 'tradeschool-manager' ); ?></li>
						<li><?php esc_html_e( 'Brevo footer branding', 'tradeschool-manager' ); ?></li>
						<li><?php esc_html_e( 'Unlimited contacts', 'tradeschool-manager' ); ?></li>
					</ul>
				</div>
				<div class="tsm-bv-plan">
					<h4><?php esc_html_e( 'Starter', 'tradeschool-manager' ); ?></h4>
					<div class="price"><?php esc_html_e( '~$9/mo', 'tradeschool-manager' ); ?></div>
					<ul>
						<li><?php esc_html_e( '20,000+ emails / month', 'tradeschool-manager' ); ?></li>
						<li><?php esc_html_e( 'No daily sending limit', 'tradeschool-manager' ); ?></li>
						<li><?php esc_html_e( 'Remove Brevo branding (add-on)', 'tradeschool-manager' ); ?></li>
					</ul>
				</div>
				<div class="tsm-bv-plan">
					<h4><?php esc_html_e( 'Business', 'tradeschool-manager' ); ?></h4>
					<div class="price"><?php esc_html_e( '~$18/mo', 'tradeschool-manager' ); ?></div>
					<ul>
						<li><?php esc_html_e( 'Marketing automation', 'tradeschool-manager' ); ?></li>
						<li><?php esc_html_e( 'A/B testing, send-time optimization', 'tradeschool-manager' ); ?></li>
						<li><?php esc_html_e( 'Advanced reporting', 'tradeschool-manager' ); ?></li>
					</ul>
				</div>
			</div>
			<p style="margin-top:16px;">
				<a class="button button-primary" href="https://www.brevo.com/pricing/" target="_blank" rel="noopener"><?php esc_html_e( 'View current Brevo pricing', 'tradeschool-manager' ); ?></a>
				<a class="button" href="https://app.brevo.com/" target="_blank" rel="noopener"><?php esc_html_e( 'Open Brevo dashboard', 'tradeschool-manager' ); ?></a>
			</p>
			<p class="description"><?php esc_html_e( "Once you upgrade, increase the 'Daily send cap' on the Settings tab so the local limiter matches your new plan.", 'tradeschool-manager' ); ?></p>
		</div>

		<div class="tsm-bv-card">
			<h3><?php esc_html_e( 'Setup Checklist', 'tradeschool-manager' ); ?></h3>
			<ol style="line-height:1.7;">
				<li><?php
					/* translators: placeholder(s) for dynamic value(s). */
					printf( wp_kses_post( __( 'Sign up at <a href="%s" target="_blank" rel="noopener">brevo.com</a> (no credit card required).', 'tradeschool-manager' ) ), 'https://www.brevo.com/' );
				?></li>
				<li><?php esc_html_e( 'In Brevo, go to Senders & IP  Domains and authenticate your school\'s domain (DKIM + DMARC). This is the single biggest deliverability factor.', 'tradeschool-manager' ); ?></li>
				<li><?php
					/* translators: placeholder(s) for dynamic value(s). */
					printf( wp_kses_post( __( 'Create an API key under SMTP &amp; API  <a href="%s" target="_blank" rel="noopener">API Keys</a>.', 'tradeschool-manager' ) ), 'https://app.brevo.com/settings/keys/api' );
				?></li>
				<li><?php esc_html_e( 'Paste the key on the Settings tab, fill in your From Email/Name, and enable Brevo.', 'tradeschool-manager' ); ?></li>
				<li><?php esc_html_e( 'Use the Diagnostics buttons to test the connection and send a test email to yourself.', 'tradeschool-manager' ); ?></li>
			</ol>
		</div>
		<?php
	}
}
