<?php
/**
 * TSM Add-ons framework.
 *
 * Free core ships with hooks for paid add-ons. Each paid feature is gated
 * behind tsm_addon_active( 'slug' ); add-ons register themselves by adding
 * to the tsm_addon_active_<slug> filter.
 *
 * The add-on catalog (names, descriptions, prices, checkout URLs) is
 * hardcoded below  -  no remote fetch, no transients, no Cloudflare. Edit
 * the catalog() method to update pricing or copy.
 *
 * @package TradeSchoolManager
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound

class TSM_Addons {

	const DATA_MARKER_OPTION = 'tsm_addon_data_markers';

	/**
	 * Hardcoded add-on catalog. Single source of truth for the Add-ons tab.
	 * All add-ons are live (active=true)  -  none are "Coming soon".
	 */
	public static function catalog() {
		return array(
			'certificates' => array(
				'name'        => __( 'Certificates', 'tradeschool-manager' ),
				'description' => __( 'Design unlimited certificate templates with the visual editor, set auto-issue rules per program, class, or workshop, and let students download signed PDFs from their portal.', 'tradeschool-manager' ),
				'availability_label' => __( 'Optional add-on', 'tradeschool-manager' ),
				'url'                => 'https://tradeschoolmanager.com/addons/certificates/',
			),
			'reports_transcripts' => array(
				'name'        => __( 'Reports & Transcripts', 'tradeschool-manager' ),
				'description' => __( 'Calculate weighted GPA, issue official transcripts, generate term and year summary report cards, and award credit hours.', 'tradeschool-manager' ),
				'availability_label' => __( 'Optional add-on', 'tradeschool-manager' ),
				'url'                => 'https://tradeschoolmanager.com/addons/reports-transcripts/',
			),
			'workshops' => array(
				'name'        => __( 'Workshops', 'tradeschool-manager' ),
				'description' => __( 'Run continuing-education or single-day workshops outside your normal school year  -  each with templates, instances, attendance, and its own gradebook.', 'tradeschool-manager' ),
				'availability_label' => __( 'Optional add-on', 'tradeschool-manager' ),
				'url'                => 'https://tradeschoolmanager.com/addons/workshops/',
			),
			'applications' => array(
				'name'        => __( 'Applications', 'tradeschool-manager' ),
				'description' => __( 'Build custom application forms per program, review submissions in an admissions board, and convert accepted applicants into enrolled students in one click.', 'tradeschool-manager' ),
				'availability_label' => __( 'Optional add-on', 'tradeschool-manager' ),
				'url'                => 'https://tradeschoolmanager.com/addons/applications/',
			),
			'invoicing' => array(
				'name'        => __( 'Invoicing & Payments', 'tradeschool-manager' ),
				'description' => __( 'Auto-generated payment plans, Stripe checkout, account statements, and a court-ready contract engine. The financial side of running your school.', 'tradeschool-manager' ),
				'availability_label' => __( 'Optional add-on', 'tradeschool-manager' ),
				'url'                => 'https://tradeschoolmanager.com/addons/invoicing/',
			),
			'custom_fields' => array(
				'name'        => __( 'Custom Fields & Student Docs', 'tradeschool-manager' ),
				'description' => __( 'Add unlimited custom fields to student profiles per program, and require students to upload supporting documents  -  every action audit-logged.', 'tradeschool-manager' ),
				'availability_label' => __( 'Optional add-on', 'tradeschool-manager' ),
				'url'                => 'https://tradeschoolmanager.com/addons/custom-fields/',
			),
		);
	}

	/**
	 * Built-in add-on registry  -  defines bundled vs external state.
	 */
	public static function registry() {
		$registry = array(
			'certificates' => array(
				'name'        => __( 'Certificates', 'tradeschool-manager' ),
				'description' => __( 'Designer, auto-issue rules, PDF generation, and student/teacher portal certificate sections.', 'tradeschool-manager' ),
				'bundled'     => false,
				'icon'        => 'awards',
			),
			'reports_transcripts' => array(
				'name'        => __( 'Reports & Transcripts', 'tradeschool-manager' ),
				'description' => __( 'PDF report cards, official transcripts, GPA & credit-hour engine, advanced analytics, and audit log.', 'tradeschool-manager' ),
				'bundled'     => false,
				'icon'        => 'media-document',
			),
			'brevo' => array(
				'name'        => __( 'Brevo Email Delivery', 'tradeschool-manager' ),
				'description' => __( 'Built-in transactional email via the Brevo API (300/day free). Includes daily-cap tracking, automatic fallback to wp_mail, tags, and an activity log.', 'tradeschool-manager' ),
				'bundled'     => true,
				'icon'        => 'email-alt',
			),
			'workshops' => array(
				'name'        => __( 'Workshops', 'tradeschool-manager' ),
				'description' => __( 'Standalone workshops outside school years, with their own gradebook, assignments, and certificates.', 'tradeschool-manager' ),
				'bundled'     => false,
				'icon'        => 'groups',
			),
			'applications' => array(
				'name'        => __( 'Applications', 'tradeschool-manager' ),
				'description' => __( 'Public program application forms, admissions workflow, and applicant-to-student conversion.', 'tradeschool-manager' ),
				'bundled'     => false,
				'icon'        => 'clipboard',
			),
			'invoicing' => array(
				'name'        => __( 'Invoicing & Payments', 'tradeschool-manager' ),
				'description' => __( 'Invoices, payment plans, Stripe checkout, late fees, account statements, and e-signed contracts.', 'tradeschool-manager' ),
				'bundled'     => false,
				'icon'        => 'money-alt',
			),
			'custom_fields' => array(
				'name'        => __( 'Custom Fields & Student Docs', 'tradeschool-manager' ),
				'description' => __( 'Per-program custom fields and the student document collection / audit-trail system for compliance.', 'tradeschool-manager' ),
				'bundled'     => false,
				'icon'        => 'media-default',
			),
		);

		return apply_filters( 'tradeschool_manager_addons_registry', $registry );
	}

	public static function is_active( $slug ) {
		$reg = self::registry();
		if ( isset( $reg[ $slug ]['bundled'] ) && $reg[ $slug ]['bundled'] ) {
			return (bool) apply_filters( "tsm_addon_active_{$slug}", true );
		}
		return (bool) apply_filters( "tsm_addon_active_{$slug}", false );
	}

	public static function mark_data( $slug, $count = null ) {
		$markers = get_option( self::DATA_MARKER_OPTION, array() );
		$markers[ $slug ] = array(
			'count'   => is_null( $count ) ? ( isset( $markers[ $slug ]['count'] ) ? $markers[ $slug ]['count'] : 1 ) : (int) $count,
			'updated' => time(),
		);
		update_option( self::DATA_MARKER_OPTION, $markers, false );
	}

	public static function get_data_marker( $slug ) {
		$markers = get_option( self::DATA_MARKER_OPTION, array() );
		return isset( $markers[ $slug ] ) ? $markers[ $slug ] : null;
	}

	private static function freemius_map() {
		return array(
			'applications'         => array(
				'function' => 'tsm_apps_fs',
				'license_url_function' => 'tsm_apps_license_manage_url',
				'license_button_function' => 'tsm_apps_license_button_details',
				'active_function' => array( 'TSM_Apps_License', 'is_active' ),
				'plugin'   => 'tradeschool-applications/tradeschool-applications.php',
			),
			'certificates'         => array(
				'function' => 'tsm_cert_fs',
				'license_url_function' => 'tsm_cert_license_manage_url',
				'license_button_function' => 'tsm_cert_license_button_details',
				'active_function' => 'tsm_cert_license_active',
				'plugin'   => 'tradeschool-certificates/tradeschool-certificates.php',
			),
			'custom_fields'        => array(
				'function' => 'tsm_cf_fs',
				'license_url_function' => 'tsm_cf_license_manage_url',
				'license_button_function' => 'tsm_cf_license_button_details',
				'active_function' => 'tsm_cf_license_active',
				'plugin'   => 'tradeschool-custom-fields/tradeschool-custom-fields.php',
			),
			'invoicing'            => array(
				'function' => 'tsm_invoicing_fs',
				'license_url_function' => 'tsm_invoicing_license_manage_url',
				'license_button_function' => 'tsm_invoicing_license_button_details',
				'pricing_url_function' => 'tsm_invoicing_license_pricing_url',
				'active_function' => 'tsm_invoicing_license_active',
				'plugin'   => 'tradeschool-invoicing/tradeschool-invoicing.php',
			),
			'reports_transcripts'  => array(
				'function' => 'tsm_reports_fs',
				'license_url_function' => 'tsm_reports_license_manage_url',
				'license_button_function' => 'tsm_reports_license_button_details',
				'pricing_url_function' => 'tsm_reports_license_pricing_url',
				'active_function' => 'tsm_reports_license_active',
				'plugin'   => 'tradeschool-reports/tradeschool-reports.php',
			),
			'workshops'            => array(
				'function' => 'tsm_workshops_fs',
				'license_url_function' => 'tsm_workshops_license_manage_url',
				'license_button_function' => 'tsm_workshops_license_button_details',
				'pricing_url_function' => 'tsm_workshops_license_pricing_url',
				'active_function' => 'tsm_workshops_license_active',
				'plugin'   => 'tradeschool-workshops/tradeschool-workshops.php',
			),
		);
	}

	private static function plugin_version( $plugin_file ) {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		$plugins = get_plugins();
		return isset( $plugins[ $plugin_file ]['Version'] ) ? $plugins[ $plugin_file ]['Version'] : '';
	}

	private static function freemius_details( $slug ) {
		$map = self::freemius_map();
		if ( empty( $map[ $slug ] ) ) {
			return array();
		}

		$details = array(
			'account_url' => '',
			'pricing_url' => '',
			'version'     => self::plugin_version( $map[ $slug ]['plugin'] ),
			'state'       => __( 'Installed', 'tradeschool-manager' ),
			'tone'        => 'neutral',
			'note'        => __( 'Manage this add-on from its WordPress plugin page.', 'tradeschool-manager' ),
			'account_button_class' => 'button button-primary',
			'account_button_label' => '',
		);

		if ( empty( $map[ $slug ]['function'] ) || ! function_exists( $map[ $slug ]['function'] ) ) {
			return $details;
		}

		if ( ! empty( $map[ $slug ]['license_button_function'] ) && function_exists( $map[ $slug ]['license_button_function'] ) ) {
			$button = call_user_func( $map[ $slug ]['license_button_function'] );
			if ( is_array( $button ) ) {
				$details['account_url']          = isset( $button['url'] ) ? (string) $button['url'] : $details['account_url'];
				$details['account_button_class'] = isset( $button['class'] ) ? (string) $button['class'] : $details['account_button_class'];
				$details['account_button_label'] = isset( $button['label'] ) ? (string) $button['label'] : $details['account_button_label'];
			}
		} elseif ( ! empty( $map[ $slug ]['license_url_function'] ) && function_exists( $map[ $slug ]['license_url_function'] ) ) {
			$details['account_url'] = call_user_func( $map[ $slug ]['license_url_function'] );
		}

		$fs = call_user_func( $map[ $slug ]['function'] );
		if ( ! is_object( $fs ) ) {
			return $details;
		}

		if ( '' === $details['account_url'] && method_exists( $fs, 'get_account_url' ) ) {
			$details['account_url'] = $fs->get_account_url();
		}
		if ( ! empty( $map[ $slug ]['pricing_url_function'] ) && function_exists( $map[ $slug ]['pricing_url_function'] ) ) {
			$details['pricing_url'] = call_user_func( $map[ $slug ]['pricing_url_function'], array( 'billing_cycle' => 'annual' ) );
		} elseif ( method_exists( $fs, 'checkout_url' ) ) {
			$details['pricing_url'] = $fs->checkout_url();
		}

		$active = false;
		if ( ! empty( $map[ $slug ]['active_function'] ) && is_callable( $map[ $slug ]['active_function'] ) ) {
			$active = (bool) call_user_func( $map[ $slug ]['active_function'] );
		} elseif ( method_exists( $fs, 'can_use_premium_code' ) ) {
			$active = (bool) $fs->can_use_premium_code();
		}

		if ( $active ) {
			$details['state'] = __( 'Licensed', 'tradeschool-manager' );
			$details['tone']  = 'good';
			$details['note']  = __( 'Premium access is active for this site.', 'tradeschool-manager' );
		} elseif ( method_exists( $fs, 'is_registered' ) && $fs->is_registered() ) {
			$details['state'] = __( 'Needs attention', 'tradeschool-manager' );
			$details['tone']  = 'warn';
			$details['note']  = __( 'The add-on is installed, but premium access is not currently active.', 'tradeschool-manager' );
		} else {
			$details['state'] = __( 'Not connected', 'tradeschool-manager' );
			$details['tone']  = 'warn';
			$details['note']  = __( 'Connect or activate a license to receive premium access and updates.', 'tradeschool-manager' );
		}

		return $details;
	}

	private static function addon_badge( $label, $tone = 'neutral' ) {
		$colors = array(
			'good'    => 'background:#dcfce7;color:#166534;border-color:#bbf7d0;',
			'warn'    => 'background:#fff7ed;color:#9a3412;border-color:#fed7aa;',
			'neutral' => 'background:#f1f5f9;color:#475569;border-color:#e2e8f0;',
			'core'    => 'background:#e0f2fe;color:#075985;border-color:#bae6fd;',
		);
		$style = isset( $colors[ $tone ] ) ? $colors[ $tone ] : $colors['neutral'];
		return '<span class="tsm-addon-badge" style="display:inline-flex;align-items:center;border:1px solid;padding:3px 9px;border-radius:999px;font-size:11px;font-weight:700;line-height:1.4;' . esc_attr( $style ) . '">' . esc_html( $label ) . '</span>';
	}

	public static function maybe_show_orphan_notices() {
		if ( ! current_user_can( 'manage_options' ) ) { return; }
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( $screen && false === strpos( (string) $screen->id, 'tsm' ) ) {
			return;
		}
		$markers = get_option( self::DATA_MARKER_OPTION, array() );
		if ( empty( $markers ) ) { return; }
		$reg = self::registry();
		foreach ( $markers as $slug => $info ) {
			if ( self::is_active( $slug ) ) { continue; }
			$dismissed = (array) get_user_meta( get_current_user_id(), 'tsm_addon_notice_dismissed', true );
			if ( in_array( $slug, $dismissed, true ) ) { continue; }
			$label = isset( $reg[ $slug ]['name'] ) ? $reg[ $slug ]['name'] : $slug;
			$count = (int) ( $info['count'] ?? 0 );
			$dismiss_url = wp_nonce_url(
				add_query_arg( array( 'tsm_dismiss_addon_notice' => $slug ) ),
				'tsm_dismiss_addon_notice_' . $slug
			);
			echo '<div class="notice notice-warning"><p>';
			printf(
				/* translators: 1: add-on name (HTML strong tag), 2: number of records */
				esc_html__( 'TradeSchool Manager: you have data from the %1$s add-on (%2$d records). Reactivate the add-on to manage it, or dismiss this notice.', 'tradeschool-manager' ),
				'<strong>' . esc_html( $label ) . '</strong>',
				(int) $count
			);
			echo ' &nbsp; <a class="button button-small" href="' . esc_url( admin_url( 'admin.php?page=tsm-settings&tab=addons' ) ) . '">' . esc_html__( 'View Add-ons', 'tradeschool-manager' ) . '</a>';
			echo ' <a class="button button-small" href="' . esc_url( $dismiss_url ) . '">' . esc_html__( 'Dismiss', 'tradeschool-manager' ) . '</a>';
			echo '</p></div>';
		}
	}

	public static function handle_dismiss() {
		if ( empty( $_GET['tsm_dismiss_addon_notice'] ) ) { return; }
		$slug = sanitize_key( wp_unslash( $_GET['tsm_dismiss_addon_notice'] ) );
		if ( ! current_user_can( 'manage_options' ) ) { return; }
		check_admin_referer( 'tsm_dismiss_addon_notice_' . $slug );
		$dismissed   = (array) get_user_meta( get_current_user_id(), 'tsm_addon_notice_dismissed', true );
		$dismissed[] = $slug;
		update_user_meta( get_current_user_id(), 'tsm_addon_notice_dismissed', array_values( array_unique( $dismissed ) ) );
		wp_safe_redirect( remove_query_arg( array( 'tsm_dismiss_addon_notice', '_wpnonce' ) ) );
		exit;
	}

	/**
	 * Render the Add-ons settings tab.
	 */
	public static function render_settings_tab() {
		$reg             = self::registry();
		$catalog         = self::catalog();
		$installed_count = 0;
		$bundled_count   = 0;
		$available_count = 0;
		$installed       = array();
		$available       = array();
		foreach ( $reg as $slug => $info ) {
			if ( self::is_active( $slug ) ) {
				$installed_count++;
				$installed[ $slug ] = $info;
			}
			if ( ! empty( $info['bundled'] ) ) {
				$bundled_count++;
			}
		}
		foreach ( $catalog as $slug => $info ) {
			if ( ! self::is_active( $slug ) ) {
				$available_count++;
				$available[ $slug ] = $info;
			}
		}
		?>
		<div class="tsm-addons-wrap" style="max-width:1180px;">
			<?php
			TSM_Inline_Assets::style(
				'tsm-addons-settings',
				'.tsm-addons-wrap .tsm-addon-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:16px;align-items:stretch;}'
				. '.tsm-addons-wrap .tsm-addon-card-pro{display:flex;flex-direction:column;min-height:250px;border:1px solid #dcdcde;background:#fff;border-radius:8px;box-shadow:0 1px 2px rgba(15,23,42,.04);overflow:hidden;}'
				. '.tsm-addons-wrap .tsm-addon-card-head{display:flex;justify-content:space-between;gap:14px;align-items:flex-start;padding:18px 18px 12px;}'
				. '.tsm-addons-wrap .tsm-addon-card-head h3{margin:0 0 6px;font-size:16px;line-height:1.3;}'
				. '.tsm-addons-wrap .tsm-addon-card-desc{margin:0;color:#64748b;line-height:1.45;}'
				. '.tsm-addons-wrap .tsm-addon-card-body{padding:0 18px 16px;flex:1 1 auto;}'
				. '.tsm-addons-wrap .tsm-addon-meta{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:14px 0;padding-top:14px;border-top:1px solid #e5e7eb;}'
				. '.tsm-addons-wrap .tsm-addon-meta span{display:block;color:#64748b;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.02em;}'
				. '.tsm-addons-wrap .tsm-addon-meta strong{display:block;margin-top:3px;color:#1d2327;}'
				. '.tsm-addons-wrap .tsm-addon-note{margin:0;color:#475569;line-height:1.45;}'
				. '.tsm-addons-wrap .tsm-addon-card-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center;justify-content:flex-start;padding:14px 18px;background:#f8fafc;border-top:1px solid #e5e7eb;}'
				. '.tsm-addons-wrap .tsm-addon-card-actions .button{min-height:32px;}'
			);
			?>
			<div class="tsm-panel" style="margin-bottom:18px;">
				<div class="tsm-panel-h tsm-panel-h-row">
					<h2><?php esc_html_e( 'Add-ons & Licensing', 'tradeschool-manager' ); ?></h2>
					<a class="button" target="_blank" rel="noopener" href="https://tradeschoolmanager.com/add-ons/"><?php esc_html_e( 'View Add-ons', 'tradeschool-manager' ); ?></a>
				</div>
				<div class="tsm-panel-body">
					<p style="margin-top:0;"><?php esc_html_e( 'Manage the free core, bundled services, and optional add-on plugins from one place.', 'tradeschool-manager' ); ?></p>
					<div class="tsm-cards" style="margin:16px 0;">
						<div class="tsm-card">
							<span class="tsm-card-label"><?php esc_html_e( 'Core Plugin', 'tradeschool-manager' ); ?></span>
							<span class="tsm-card-num"><?php esc_html_e( 'Free', 'tradeschool-manager' ); ?></span>
							<span class="tsm-card-sub"><?php esc_html_e( 'No license key required', 'tradeschool-manager' ); ?></span>
						</div>
						<div class="tsm-card">
							<span class="tsm-card-label"><?php esc_html_e( 'Active Items', 'tradeschool-manager' ); ?></span>
							<span class="tsm-card-num"><?php echo esc_html( $installed_count ); ?></span>
							<span class="tsm-card-sub"><?php esc_html_e( 'Bundled or installed', 'tradeschool-manager' ); ?></span>
						</div>
						<div class="tsm-card">
							<span class="tsm-card-label"><?php esc_html_e( 'Bundled Services', 'tradeschool-manager' ); ?></span>
							<span class="tsm-card-num"><?php echo esc_html( $bundled_count ); ?></span>
							<span class="tsm-card-sub"><?php esc_html_e( 'Included with core', 'tradeschool-manager' ); ?></span>
						</div>
						<div class="tsm-card">
							<span class="tsm-card-label"><?php esc_html_e( 'Optional Add-ons', 'tradeschool-manager' ); ?></span>
							<span class="tsm-card-num"><?php echo esc_html( count( $catalog ) ); ?></span>
							<?php /* translators: %d: number of optional add-ons not installed. */ ?>
							<span class="tsm-card-sub"><?php echo esc_html( sprintf( _n( '%d not installed', '%d not installed', $available_count, 'tradeschool-manager' ), $available_count ) ); ?></span>
						</div>
					</div>
					<p class="description"><?php esc_html_e( 'The core plugin does not perform license checks. Paid add-ons are separate WordPress plugins and handle their own licensing and updates.', 'tradeschool-manager' ); ?></p>
					<?php if ( class_exists( 'TSM_License' ) ) : ?>
						<?php TSM_License::render_legacy_cleanup(); ?>
					<?php endif; ?>
				</div>
			</div>

			<div class="tsm-panel" style="margin-bottom:18px;">
				<div class="tsm-panel-h tsm-panel-h-row">
					<h2><?php esc_html_e( 'Installed on This Site', 'tradeschool-manager' ); ?></h2>
					<span class="description"><?php esc_html_e( 'Manage licenses, billing, account connection, and add-on updates.', 'tradeschool-manager' ); ?></span>
				</div>
				<div class="tsm-panel-body">
					<div class="tsm-addon-grid">
						<div class="tsm-addon-card-pro">
							<div class="tsm-addon-card-head">
								<div>
									<h3><?php esc_html_e( 'TradeSchool Manager Core', 'tradeschool-manager' ); ?></h3>
									<p class="tsm-addon-card-desc"><?php esc_html_e( 'Students, classes, gradebook, portals, email tools, and shared add-on framework.', 'tradeschool-manager' ); ?></p>
								</div>
								<?php echo wp_kses_post( self::addon_badge( __( 'Included', 'tradeschool-manager' ), 'core' ) ); ?>
							</div>
							<div class="tsm-addon-card-body">
							<div class="tsm-addon-meta">
								<div><span style="display:block;color:#64748b;font-size:11px;font-weight:700;text-transform:uppercase;"><?php esc_html_e( 'License', 'tradeschool-manager' ); ?></span><strong><?php esc_html_e( 'None required', 'tradeschool-manager' ); ?></strong></div>
								<div><span style="display:block;color:#64748b;font-size:11px;font-weight:700;text-transform:uppercase;"><?php esc_html_e( 'Updates', 'tradeschool-manager' ); ?></span><strong><?php esc_html_e( 'Core plugin', 'tradeschool-manager' ); ?></strong></div>
							</div>
							<p class="tsm-addon-note"><?php esc_html_e( 'Core functionality remains available without a paid add-on license.', 'tradeschool-manager' ); ?></p>
							</div>
							<div class="tsm-addon-card-actions">
								<a class="button" href="<?php echo esc_url( admin_url( 'plugins.php' ) ); ?>"><?php esc_html_e( 'Plugin details', 'tradeschool-manager' ); ?></a>
							</div>
						</div>
						<?php foreach ( $installed as $slug => $info ) :
							if ( ! empty( $info['bundled'] ) ) {
								continue;
							}
							$details     = self::freemius_details( $slug );
							$description = isset( $catalog[ $slug ]['description'] ) ? $catalog[ $slug ]['description'] : $info['description'];
							$version     = ! empty( $details['version'] ) ? $details['version'] : __( 'Installed', 'tradeschool-manager' );
							?>
							<div class="tsm-addon-card-pro">
								<div class="tsm-addon-card-head">
									<div>
										<h3><?php echo esc_html( $info['name'] ); ?></h3>
										<p class="tsm-addon-card-desc"><?php echo esc_html( $description ); ?></p>
									</div>
									<?php echo wp_kses_post( self::addon_badge( $details['state'], $details['tone'] ) ); ?>
								</div>
								<div class="tsm-addon-card-body">
								<div class="tsm-addon-meta">
									<div><span style="display:block;color:#64748b;font-size:11px;font-weight:700;text-transform:uppercase;"><?php esc_html_e( 'Version', 'tradeschool-manager' ); ?></span><strong><?php echo esc_html( $version ); ?></strong></div>
									<div><span style="display:block;color:#64748b;font-size:11px;font-weight:700;text-transform:uppercase;"><?php esc_html_e( 'Type', 'tradeschool-manager' ); ?></span><strong><?php esc_html_e( 'Paid add-on', 'tradeschool-manager' ); ?></strong></div>
								</div>
								<p class="tsm-addon-note"><?php echo esc_html( $details['note'] ); ?></p>
								</div>
								<div class="tsm-addon-card-actions">
									<?php if ( ! empty( $details['account_url'] ) ) : ?>
										<?php $account_label = ! empty( $details['account_button_label'] ) ? $details['account_button_label'] : ( 'good' === $details['tone'] ? __( 'Manage license and billing', 'tradeschool-manager' ) : __( 'Enter license key', 'tradeschool-manager' ) ); ?>
										<a class="<?php echo esc_attr( $details['account_button_class'] ); ?>" href="<?php echo esc_url( $details['account_url'] ); ?>"><?php echo esc_html( $account_label ); ?></a>
									<?php endif; ?>
									<?php if ( ! empty( $details['pricing_url'] ) && 'good' !== $details['tone'] ) : ?>
										<a class="button" href="<?php echo esc_url( $details['pricing_url'] ); ?>"><?php esc_html_e( 'Activate or upgrade', 'tradeschool-manager' ); ?></a>
									<?php endif; ?>
									<a class="button" href="<?php echo esc_url( admin_url( 'plugins.php' ) ); ?>"><?php esc_html_e( 'Plugin details', 'tradeschool-manager' ); ?></a>
								</div>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			</div>

			<div class="tsm-panel">
				<div class="tsm-panel-h"><h2><?php esc_html_e( 'Available Add-ons', 'tradeschool-manager' ); ?></h2></div>
				<div class="tsm-panel-body">
					<?php if ( 0 === $available_count ) : ?>
						<p class="description"><?php esc_html_e( 'All currently listed add-ons are already installed on this site.', 'tradeschool-manager' ); ?></p>
					<?php else : ?>
						<div class="tsm-addon-grid">
							<?php foreach ( $available as $slug => $info ) : ?>
								<div class="tsm-addon-card-pro">
									<div class="tsm-addon-card-head">
										<div>
											<h3><?php echo esc_html( $info['name'] ); ?></h3>
											<p class="tsm-addon-card-desc"><?php echo esc_html( $info['description'] ); ?></p>
										</div>
										<?php echo wp_kses_post( self::addon_badge( $info['availability_label'], 'neutral' ) ); ?>
									</div>
									<div class="tsm-addon-card-body">
										<div class="tsm-addon-meta">
											<div><span><?php esc_html_e( 'Status', 'tradeschool-manager' ); ?></span><strong><?php esc_html_e( 'Not installed', 'tradeschool-manager' ); ?></strong></div>
											<div><span><?php esc_html_e( 'Type', 'tradeschool-manager' ); ?></span><strong><?php esc_html_e( 'Optional add-on', 'tradeschool-manager' ); ?></strong></div>
										</div>
										<p class="tsm-addon-note"><?php esc_html_e( 'Install this add-on only when your school needs this workflow.', 'tradeschool-manager' ); ?></p>
									</div>
									<div class="tsm-addon-card-actions">
										<a class="button button-secondary" href="<?php echo esc_url( $info['url'] ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Learn more', 'tradeschool-manager' ); ?></a>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}
}

/* ---------- Public helper ---------- */

function tsm_addon_active( $slug ) {
	return TSM_Addons::is_active( $slug );
}

add_action( 'admin_notices', array( 'TSM_Addons', 'maybe_show_orphan_notices' ) );
add_action( 'admin_init',    array( 'TSM_Addons', 'handle_dismiss' ) );
