<?php
/**
 * Pro: Email notifications + templates.
 *
 * @package TradeSchoolManagerPro
 */

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

class TSMP_Emails {

	const OPTION = 'tsmp_email_settings';

	public static function defaults() {
		return array(
			'enabled'             => 1,
			'from_name'           => get_bloginfo( 'name' ),
			'from_email'          => get_bloginfo( 'admin_email' ),
			'tpl_grade_enabled'   => 1,
			'tpl_grade_subject'   => 'New grade posted in {class_name}',
			'tpl_grade_body'      => "Hi {first_name},\n\nA new grade has been posted in {class_name}:\nAssignment: {assignment_title}\nScore: {score} / {points_possible}\n\nLog in to your portal to view all your grades.\n\n -  {school_name}",
			'tpl_payment_enabled' => 1,
			'tpl_payment_subject' => 'Payment received  -  {school_name}',
			'tpl_payment_body'    => "Hi {first_name},\n\nWe received a payment of \${amount} on {date}.\nNew balance: \${balance}\n\nThank you,\n{school_name}",
			'tpl_welcome_enabled' => 1,
			'tpl_welcome_subject' => 'Welcome to {program_name}  -  your {school_name} student account',
			'tpl_welcome_intro'   => "Congratulations, {first_name}! Your application to {program_name} has been approved and your student account is ready.",
			'tpl_welcome_billing' => "Your program tuition is \${total_cost}. We've set up your billing schedule ({billing_summary}). You can review every invoice, due date, and payment option from the Payments & Invoices tab in your student portal.",
			'tpl_welcome_closing' => "If you have any questions, just reply to this email  -  we're glad to have you on board.\n\n -  The {school_name} team",
			'portal_url'          => 'https://sodaeprogram.com/student-portal/',
		);
	}

	/**
	 * Whether a specific named template is enabled. Returns true when the
	 * master switch is on AND the template-level toggle is on.
	 *
	 * @param string $key  'grade' | 'payment' | 'welcome'
	 */
	public static function is_template_enabled( $key ) {
		$s = self::get_all();
		if ( empty( $s['enabled'] ) ) { return false; }
		$field = 'tpl_' . $key . '_enabled';
		return ! isset( $s[ $field ] ) || ! empty( $s[ $field ] );
	}

	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 render_tokens( $template, $tokens ) {
		foreach ( $tokens as $k => $v ) {
			$template = str_replace( '{' . $k . '}', (string) $v, $template );
		}
		return $template;
	}

	public static function send( $to, $subject, $body, $tag = 'general' ) {
		$settings = self::get_all();
		if ( empty( $settings['enabled'] ) ) {
			return false;
		}
		// From identity is managed centrally in Email Deliverability -> Standard Mail (TSMP_Mail).
		$headers = array(
			'Content-Type: text/plain; charset=UTF-8',
			'X-TSM-Tag: ' . sanitize_key( $tag ),
		);
		return wp_mail( $to, $subject, $body, $headers );
	}

	/**
	 * Send an HTML email (used for the welcome / approval email).
	 */
	public static function send_html( $to, $subject, $html, $tag = 'general' ) {
		$settings = self::get_all();
		if ( empty( $settings['enabled'] ) ) {
			return false;
		}
		// From identity is managed centrally in Email Deliverability -> Standard Mail (TSMP_Mail).
		$headers = array(
			'Content-Type: text/html; charset=UTF-8',
			'X-TSM-Tag: ' . sanitize_key( $tag ),
		);
		return wp_mail( $to, $subject, $html, $headers );
	}

	/**
	 * Build the polished HTML wrapper used for transactional emails (welcome, etc.).
	 */
	public static function html_wrap( $heading, $inner_html ) {
		$school = esc_html( tsm_get_setting( 'school_name', get_bloginfo( 'name' ) ) );
		ob_start(); ?>
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f4f6fa;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#1f2937;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6fa;padding:32px 16px;">
	<tr><td align="center">
		<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;box-shadow:0 4px 18px rgba(15,23,42,.08);overflow:hidden;">
			<tr><td style="background:linear-gradient(135deg,#1e40af,#2563eb);padding:28px 32px;color:#ffffff;">
				<div style="font-size:13px;letter-spacing:.08em;text-transform:uppercase;opacity:.85;"><?php echo esc_html( $school ); ?></div>
				<div style="font-size:24px;font-weight:700;margin-top:6px;line-height:1.25;"><?php echo esc_html( $heading ); ?></div>
			</td></tr>
			<tr><td style="padding:32px;font-size:15px;line-height:1.6;color:#1f2937;">
				<?php echo wp_kses_post( $inner_html ); // already-safe HTML built by caller ?>
			</td></tr>
			<tr><td style="padding:18px 32px;background:#f8fafc;border-top:1px solid #e5e7eb;font-size:12px;color:#6b7280;text-align:center;">
				&copy; <?php echo esc_html( gmdate( 'Y' ) ); ?> <?php echo wp_kses_post( $school ); ?>. <?php esc_html_e( 'All rights reserved.', 'tradeschool-manager' ); ?>
			</td></tr>
		</table>
	</td></tr>
</table>
</body></html>
		<?php
		return ob_get_clean();
	}

	/**
	 * Send the application-approved welcome email.
	 *
	 * @param array $tokens  first_name, last_name, email, username, password (raw or 'set by you'),
	 *                       program_name, total_cost, billing_summary, portal_url, school_name
	 * @return bool
	 */
	public static function send_welcome( $to, $tokens ) {
		if ( ! self::is_template_enabled( 'welcome' ) ) { return false; }
		$tpl = self::get_all();
		$subject = self::render_tokens( $tpl['tpl_welcome_subject'], $tokens );
		$intro   = nl2br( esc_html( self::render_tokens( $tpl['tpl_welcome_intro'],   $tokens ) ) );

		// If the Invoicing & Contracts add-on is not installed, the default
		// billing copy (which talks about invoices and a "Payments & Invoices"
		// portal tab) is a lie  -  neither feature exists. Swap in a plain
		// "school will contact you" message instead so the school can promote
		// the add-on to billing copy by simply installing it.
		$invoicing_on = function_exists( 'tsm_addon_active' ) && tsm_addon_active( 'invoicing' );
		$billing_src  = $invoicing_on
			? $tpl['tpl_welcome_billing']
			: __( "Your school will be in touch directly to confirm tuition and payment arrangements.", 'tradeschool-manager' );
		$billing = nl2br( esc_html( self::render_tokens( $billing_src, $tokens ) ) );

		$closing = nl2br( esc_html( self::render_tokens( $tpl['tpl_welcome_closing'], $tokens ) ) );

		$portal     = esc_url( $tokens['portal_url'] );
		$username_h = esc_html( $tokens['username'] );
		$password_h = esc_html( $tokens['password'] );

		$creds_block = '';
		if ( ! empty( $tokens['show_credentials'] ) ) {
			$creds_block =
				'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:24px 0;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:10px;">
					<tr><td style="padding:18px 22px;font-size:14px;line-height:1.6;">
						<div style="font-weight:600;color:#0f172a;margin-bottom:6px;">' . esc_html__( 'Your sign-in details', 'tradeschool-manager' ) . '</div>
						<div><strong>' . esc_html__( 'Username:', 'tradeschool-manager' ) . '</strong> ' . $username_h . '</div>
						<div><strong>' . esc_html__( 'Temporary password:', 'tradeschool-manager' ) . '</strong> <code style="background:#fff;padding:2px 6px;border-radius:4px;border:1px solid #e2e8f0;">' . $password_h . '</code></div>
						<div style="color:#64748b;font-size:12px;margin-top:8px;">' . esc_html__( 'Please change your password after your first sign-in.', 'tradeschool-manager' ) . '</div>
					</td></tr>
				</table>';
		} else {
			$creds_block =
				'<p style="margin:18px 0;color:#475569;font-size:14px;">'
				. esc_html__( 'You can sign in with the username and password you already use for your student portal.', 'tradeschool-manager' )
				. '</p>';
		}

		$button =
			'<div style="text-align:center;margin:28px 0;">
				<a href="' . $portal . '" style="background:#2563eb;color:#ffffff;text-decoration:none;font-weight:600;padding:14px 28px;border-radius:8px;display:inline-block;font-size:15px;">'
				. esc_html__( 'Sign in to your student portal', 'tradeschool-manager' )
				. '</a>
			</div>
			<p style="font-size:12px;color:#64748b;text-align:center;margin-top:-12px;">' . esc_html__( 'Or copy this link:', 'tradeschool-manager' ) . ' <a href="' . $portal . '" style="color:#2563eb;">' . $portal . '</a></p>';

		$billing_heading = $invoicing_on
			? esc_html__( 'Tuition & billing', 'tradeschool-manager' )
			: esc_html__( 'Tuition', 'tradeschool-manager' );

		$inner =
			'<p style="margin:0 0 14px;">' . $intro . '</p>'
			. $creds_block
			. $button
			. '<h3 style="margin:24px 0 8px;font-size:16px;color:#0f172a;">' . $billing_heading . '</h3>'
			. '<p style="margin:0 0 14px;color:#334155;">' . $billing . '</p>'
			. '<p style="margin:18px 0 0;">' . $closing . '</p>';

		$heading = sprintf(
			/* translators: %s = program name */
			esc_html__( 'Welcome to %s', 'tradeschool-manager' ),
			esc_html( $tokens['program_name'] )
		);
		$html = self::html_wrap( $heading, $inner );

		return self::send_html( $to, $subject, $html, 'welcome' );
	}


	public static function on_save_grade( $assignment_id, $student_id, $vals, $prev ) {
		if ( ! self::is_template_enabled( 'grade' ) ) { return; }

		// Normalize new + previous values to compare meaningful changes only.
		// Email fires when (a) the student now has a graded result and (b)
		// the score/status/bonus/penalty actually differs from what was
		// stored before. This stops the "save the form, blast every
		// student" spam pattern.
		$new_status = isset( $vals['status'] ) ? (string) $vals['status'] : '';
		if ( '' === $new_status && isset( $vals['points_earned'] ) && '' !== $vals['points_earned'] ) {
			$new_status = 'completed_ontime'; // matches TSM_Gradebook::save_grade legacy path
		}
		// Only notify when the student actually has a graded result.
		$notify_statuses = array( 'completed_ontime', 'completed_late', 'incomplete', 'missing' );
		if ( ! in_array( $new_status, $notify_statuses, true ) ) { return; }

		$norm = function ( $v ) { return ( null === $v || '' === $v ) ? '' : (string) (float) $v; };
		$new_score   = $norm( $vals['points_earned'] ?? '' );
		$new_bonus   = $norm( $vals['bonus']         ?? '' );
		$new_lp      = $norm( $vals['late_penalty']  ?? '' );

		if ( $prev ) {
			$prev_status = isset( $prev->status ) ? (string) $prev->status : '';
			$prev_score  = $norm( $prev->points_earned ?? '' );
			$prev_bonus  = $norm( $prev->bonus         ?? '' );
			$prev_lp     = $norm( $prev->late_penalty  ?? '' );
			$unchanged = ( $prev_status === $new_status )
				&& ( $prev_score === $new_score )
				&& ( $prev_bonus === $new_bonus )
				&& ( $prev_lp    === $new_lp );
			if ( $unchanged ) { return; }
		}

		$student = TSM_Students::get( $student_id );
		if ( ! $student || ! $student->email ) return;
		$assign  = TSM_Assignments::get( $assignment_id );
		if ( ! $assign ) return;
		$class   = TSM_Classes::get( $assign->class_id );

		// Skip notifications for archived school years  -  those edits are
		// administrative cleanup, not new academic results students need
		// to be told about.
		if ( $class && class_exists( 'TSM_School_Years' ) && TSM_School_Years::is_archived( (int) $class->school_year_id ) ) {
			return;
		}

		$tpl     = self::get_all();
		$tokens  = array(
			'first_name'        => $student->first_name,
			'class_name'        => $class->name ?? '',
			'assignment_title'  => $assign->title,
			'score'             => $vals['points_earned'] ?? '',
			'points_possible'   => $assign->points_possible,
			'school_name'       => tsm_get_setting( 'school_name', get_bloginfo( 'name' ) ),
		);
		self::send(
			$student->email,
			self::render_tokens( $tpl['tpl_grade_subject'], $tokens ),
			self::render_tokens( $tpl['tpl_grade_body'], $tokens ),
			'grade'
		);
	}

	public static function render_admin() {
		if ( isset( $_POST['tsmp_emails_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsmp_emails_nonce'] ) ), 'tsmp_emails' ) ) {
			$active_save = isset( $_POST['_etab'] ) ? sanitize_key( $_POST['_etab'] ) : 'general';
			$payload = array(
				'enabled'             => ! empty( $_POST['enabled'] ) ? 1 : 0,
				'from_name'           => sanitize_text_field( wp_unslash( $_POST['from_name'] ?? '' ) ),
				'from_email'          => sanitize_email( wp_unslash( $_POST['from_email'] ?? '' ) ),
				'tpl_grade_subject'   => sanitize_text_field( wp_unslash( $_POST['tpl_grade_subject'] ?? '' ) ),
				'tpl_grade_body'      => sanitize_textarea_field( wp_unslash( $_POST['tpl_grade_body'] ?? '' ) ),
				'tpl_payment_subject' => sanitize_text_field( wp_unslash( $_POST['tpl_payment_subject'] ?? '' ) ),
				'tpl_payment_body'    => sanitize_textarea_field( wp_unslash( $_POST['tpl_payment_body'] ?? '' ) ),
				'tpl_welcome_subject' => sanitize_text_field( wp_unslash( $_POST['tpl_welcome_subject'] ?? '' ) ),
				'tpl_welcome_intro'   => sanitize_textarea_field( wp_unslash( $_POST['tpl_welcome_intro']   ?? '' ) ),
				'tpl_welcome_billing' => sanitize_textarea_field( wp_unslash( $_POST['tpl_welcome_billing'] ?? '' ) ),
				'tpl_welcome_closing' => sanitize_textarea_field( wp_unslash( $_POST['tpl_welcome_closing'] ?? '' ) ),
				'portal_url'          => esc_url_raw( wp_unslash( $_POST['portal_url'] ?? '' ) ),
			);
			// Per-template enable toggles. Always carry forward via hidden inputs;
			// the visible checkbox on the active tab overwrites that template's value.
			foreach ( array( 'grade', 'payment', 'welcome' ) as $tk ) {
				$field = 'tpl_' . $tk . '_enabled';
				if ( $active_save === $tk || $active_save === 'general' ) {
					// Visible checkbox on this tab (or general overview).
					$payload[ $field ] = ! empty( $_POST[ $field ] ) ? 1 : 0;
				} else {
					$payload[ $field ] = ! empty( $_POST[ $field . '_carry' ] ) ? 1 : 0;
				}
			}
			self::update( $payload );
			update_option( 'tsm_emails_reviewed', 1, false );
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Email settings saved. Your setup checklist has been updated.', 'tradeschool-manager' ) . '</p></div>';
		}
		$s = self::get_all();
		$active = isset( $_GET['etab'] ) ? sanitize_key( $_GET['etab'] ) : 'general';
		if ( ! in_array( $active, array( 'general', 'grade', 'payment', 'welcome' ), true ) ) $active = 'general';
		$base = admin_url( 'admin.php?page=tsm-emails' );
		TSM_Inline_Assets::style(
			'tsmp-email-tabs',
			'.tsm-etabs{display:flex;gap:4px;border-bottom:1px solid #c3c4c7;margin:14px 0 18px;}.tsm-etabs a{padding:8px 14px;text-decoration:none;border:1px solid transparent;border-bottom:0;border-radius:6px 6px 0 0;color:#1d2327;font-weight:500;}.tsm-etabs a.active{background:#fff;border-color:#c3c4c7;color:#0073aa;}'
		);
		?>
		<div class="tsm-etabs">
			<a href="<?php echo esc_url( add_query_arg( 'etab', 'general', $base ) ); ?>" class="<?php echo $active==='general'?'active':''; ?>"><?php esc_html_e( 'General', 'tradeschool-manager' ); ?></a>
			<a href="<?php echo esc_url( add_query_arg( 'etab', 'welcome', $base ) ); ?>" class="<?php echo $active==='welcome'?'active':''; ?>"><?php esc_html_e( 'Welcome / Application Approved', 'tradeschool-manager' ); ?></a>
			<a href="<?php echo esc_url( add_query_arg( 'etab', 'grade',   $base ) ); ?>" class="<?php echo $active==='grade'?'active':''; ?>"><?php esc_html_e( 'Grade Posted', 'tradeschool-manager' ); ?></a>
			<a href="<?php echo esc_url( add_query_arg( 'etab', 'payment', $base ) ); ?>" class="<?php echo $active==='payment'?'active':''; ?>"><?php esc_html_e( 'Payment Received', 'tradeschool-manager' ); ?></a>
		</div>
		<?php if ( empty( get_option( 'tsm_emails_reviewed' ) ) ) : ?>
			<div class="notice notice-info inline" style="margin:0 0 16px;">
				<p>
					<strong><?php esc_html_e( 'Final setup step:', 'tradeschool-manager' ); ?></strong>
					<?php esc_html_e( 'Review these email templates, adjust anything your school wants to change, then click Save Email Settings to complete setup.', 'tradeschool-manager' ); ?>
				</p>
			</div>
		<?php endif; ?>
		<form method="post">
			<?php wp_nonce_field( 'tsmp_emails', 'tsmp_emails_nonce' ); ?>
			<input type="hidden" name="_etab" value="<?php echo esc_attr( $active ); ?>">
			<?php /* Always submit all fields so switching tabs doesn't blank others. */ ?>
			<input type="hidden" name="tpl_grade_subject"   value="<?php echo esc_attr( $s['tpl_grade_subject'] ); ?>">
			<input type="hidden" name="tpl_grade_body"     value="<?php echo esc_attr( $s['tpl_grade_body'] ); ?>">
			<input type="hidden" name="tpl_payment_subject" value="<?php echo esc_attr( $s['tpl_payment_subject'] ); ?>">
			<input type="hidden" name="tpl_payment_body"   value="<?php echo esc_attr( $s['tpl_payment_body'] ); ?>">
			<input type="hidden" name="tpl_welcome_subject" value="<?php echo esc_attr( $s['tpl_welcome_subject'] ); ?>">
			<input type="hidden" name="tpl_welcome_intro"   value="<?php echo esc_attr( $s['tpl_welcome_intro'] ); ?>">
			<input type="hidden" name="tpl_welcome_billing" value="<?php echo esc_attr( $s['tpl_welcome_billing'] ); ?>">
			<input type="hidden" name="tpl_welcome_closing" value="<?php echo esc_attr( $s['tpl_welcome_closing'] ); ?>">
			<input type="hidden" name="portal_url"         value="<?php echo esc_attr( $s['portal_url'] ); ?>">
			<?php /* From Name / From Email moved to Email Deliverability -> Standard Mail. */ ?>

			<?php /* Carry-forward values for non-active per-template enables. */ ?>
			<?php foreach ( array( 'grade', 'payment', 'welcome' ) as $tk ) : $f = 'tpl_' . $tk . '_enabled'; ?>
				<input type="hidden" name="<?php echo esc_attr( $f ); ?>_carry" value="<?php echo (int) ! empty( $s[ $f ] ); ?>">
			<?php endforeach; ?>

			<?php if ( 'general' === $active ) : ?>
				<table class="form-table">
					<tr><th><?php esc_html_e( 'Master Switch', 'tradeschool-manager' ); ?></th><td><label><input type="checkbox" name="enabled" value="1" <?php checked( $s['enabled'] ); ?>> <?php esc_html_e( 'Enable email notifications globally (must be on for any template to send)', 'tradeschool-manager' ); ?></label></td></tr>
					<tr><th><?php esc_html_e( 'Sender Identity', 'tradeschool-manager' ); ?></th><td><p class="description" style="margin:0;"><?php
						/* translators: %s = URL to Email Deliverability -> Standard Mail settings page */
						printf( wp_kses_post( __( 'From Name and From Email are managed in <a href="%s">Email Deliverability -> Standard Mail</a>.', 'tradeschool-manager' ) ), esc_url( admin_url( 'admin.php?page=tsmp-brevo&btab=standard' ) ) );
					?></p></td></tr>
					<tr><th><?php esc_html_e( 'Student Portal URL', 'tradeschool-manager' ); ?></th><td><input class="large-text code" type="url" name="portal_url" value="<?php echo esc_attr( $s['portal_url'] ); ?>"><p class="description"><?php esc_html_e( 'The login URL students will visit. Used in the welcome / approval email.', 'tradeschool-manager' ); ?></p></td></tr>
				</table>

				<h3 style="margin-top:24px;"><?php esc_html_e( 'Per-Template Toggles', 'tradeschool-manager' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Enable or disable individual notification templates. Disabled templates will not send even when the master switch is on.', 'tradeschool-manager' ); ?></p>
				<table class="form-table">
					<tr><th><?php esc_html_e( 'Welcome / Approval', 'tradeschool-manager' ); ?></th><td><label><input type="checkbox" name="tpl_welcome_enabled" value="1" <?php checked( ! empty( $s['tpl_welcome_enabled'] ) ); ?>> <?php esc_html_e( 'Send when an application is approved', 'tradeschool-manager' ); ?></label></td></tr>
					<tr><th><?php esc_html_e( 'Grade Posted', 'tradeschool-manager' ); ?></th><td><label><input type="checkbox" name="tpl_grade_enabled" value="1" <?php checked( ! empty( $s['tpl_grade_enabled'] ) ); ?>> <?php esc_html_e( 'Send when a new grade is recorded', 'tradeschool-manager' ); ?></label></td></tr>
					<tr><th><?php esc_html_e( 'Payment Received', 'tradeschool-manager' ); ?></th><td><label><input type="checkbox" name="tpl_payment_enabled" value="1" <?php checked( ! empty( $s['tpl_payment_enabled'] ) ); ?>> <?php esc_html_e( 'Send when a payment is recorded', 'tradeschool-manager' ); ?></label></td></tr>
				</table>

			<?php elseif ( 'welcome' === $active ) : ?>
				<h3><?php esc_html_e( 'Welcome / Application Approved Email', 'tradeschool-manager' ); ?></h3>
				<p><label><input type="checkbox" name="tpl_welcome_enabled" value="1" <?php checked( ! empty( $s['tpl_welcome_enabled'] ) ); ?>> <strong><?php esc_html_e( 'Enable this email', 'tradeschool-manager' ); ?></strong></label></p>
				<p class="description"><?php esc_html_e( 'Sent automatically when an application is approved. The email is wrapped in a branded HTML layout  -  only edit the text content here.', 'tradeschool-manager' ); ?></p>
				<table class="form-table">
					<tr><th><?php esc_html_e( 'Subject', 'tradeschool-manager' ); ?></th><td><input class="large-text" name="tpl_welcome_subject" value="<?php echo esc_attr( $s['tpl_welcome_subject'] ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Intro paragraph', 'tradeschool-manager' ); ?></th><td><textarea class="large-text" rows="3" name="tpl_welcome_intro"><?php echo esc_textarea( $s['tpl_welcome_intro'] ); ?></textarea></td></tr>
					<tr><th><?php esc_html_e( 'Billing paragraph', 'tradeschool-manager' ); ?></th><td><textarea class="large-text" rows="4" name="tpl_welcome_billing"><?php echo esc_textarea( $s['tpl_welcome_billing'] ); ?></textarea><p class="description"><?php esc_html_e( 'Shown only when the program has a default billing schedule and price.', 'tradeschool-manager' ); ?></p></td></tr>
					<tr><th><?php esc_html_e( 'Closing paragraph', 'tradeschool-manager' ); ?></th><td><textarea class="large-text" rows="3" name="tpl_welcome_closing"><?php echo esc_textarea( $s['tpl_welcome_closing'] ); ?></textarea></td></tr>
				</table>
				<p class="description"><?php esc_html_e( 'Tokens: {first_name} {last_name} {program_name} {total_cost} {billing_summary} {school_name} {portal_url} {username}', 'tradeschool-manager' ); ?></p>

			<?php elseif ( 'grade' === $active ) : ?>
				<h3><?php esc_html_e( 'Grade Posted Email', 'tradeschool-manager' ); ?></h3>
				<p><label><input type="checkbox" name="tpl_grade_enabled" value="1" <?php checked( ! empty( $s['tpl_grade_enabled'] ) ); ?>> <strong><?php esc_html_e( 'Enable this email', 'tradeschool-manager' ); ?></strong></label></p>
				<p><input class="large-text" name="tpl_grade_subject" value="<?php echo esc_attr( $s['tpl_grade_subject'] ); ?>"></p>
				<p><textarea class="large-text" rows="8" name="tpl_grade_body"><?php echo esc_textarea( $s['tpl_grade_body'] ); ?></textarea></p>
				<p class="description"><?php esc_html_e( 'Tokens: {first_name} {class_name} {assignment_title} {score} {points_possible} {school_name}', 'tradeschool-manager' ); ?></p>

			<?php else : /* payment */ ?>
				<h3><?php esc_html_e( 'Payment Received Email', 'tradeschool-manager' ); ?></h3>
				<p><label><input type="checkbox" name="tpl_payment_enabled" value="1" <?php checked( ! empty( $s['tpl_payment_enabled'] ) ); ?>> <strong><?php esc_html_e( 'Enable this email', 'tradeschool-manager' ); ?></strong></label></p>
				<p><input class="large-text" name="tpl_payment_subject" value="<?php echo esc_attr( $s['tpl_payment_subject'] ); ?>"></p>
				<p><textarea class="large-text" rows="8" name="tpl_payment_body"><?php echo esc_textarea( $s['tpl_payment_body'] ); ?></textarea></p>
				<p class="description"><?php esc_html_e( 'Tokens: {first_name} {amount} {date} {balance} {school_name}', 'tradeschool-manager' ); ?></p>
			<?php endif; ?>

			<?php /* General tab uses its own checkbox to set 'enabled'; other tabs need to preserve it. */ ?>
			<?php if ( 'general' !== $active ) : ?>
				<input type="hidden" name="enabled" value="<?php echo (int) $s['enabled']; ?>">
			<?php endif; ?>

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