<?php
/**
 * Pro feature dispatcher  -  wires everything to Free hooks when license is valid.
 *
 * @package TradeSchoolManagerPro
 */

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

class TSMP_Features {
	private static $instance = null;
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		if ( ! tradeschool_manager_is_pro_active() ) {
			return;
		}

		// Render hooks for locked Free pages.
		add_action( 'tradeschool_manager_render_attendance', array( 'TSMP_Attendance', 'render_admin' ) );
		if ( class_exists( 'TSMP_Payments' ) ) {
			add_action( 'tradeschool_manager_render_payments',    array( 'TSMP_Payments', 'render_admin' ) );
		}

		// Custom fields integration (only when add-on is active).
		if ( class_exists( 'TSMP_Custom_Fields' ) ) {
			add_action( 'tradeschool_manager_student_edit_fields', array( 'TSMP_Custom_Fields', 'render_student_fields' ) );
			add_action( 'tradeschool_manager_after_save_student',  array( 'TSMP_Custom_Fields', 'on_save_student' ), 10, 2 );
		}

		// Audit log + email triggers.
		add_action( 'tradeschool_manager_after_save_grade', array( 'TSMP_Audit', 'on_save_grade' ), 10, 4 );
		add_action( 'tradeschool_manager_after_save_grade', array( 'TSMP_Emails', 'on_save_grade' ), 20, 4 );

		// Portal additions (announcements only  -  payments + custom fields are now
		// rendered inline by the portal layout itself, so we do not duplicate them
		// at the bottom of the page).
		add_action( 'wp_head', array( 'TSMP_Archive_Theme', 'inject_portal_css' ) );
		// Note: the previous tsm_portal_after_classes hook is intentionally not
		// registered anymore. The portal template no longer fires that action.

		// Additional admin submenus.
		add_action( 'tradeschool_manager_admin_menu', array( $this, 'register_submenus' ), 10, 2 );

		// Add Pro pages to branded sidebar nav.
		add_filter( 'tradeschool_manager_admin_nav_items', array( $this, 'register_nav_items' ) );

		// admin-post handlers (PDFs, CSV export).
		if ( function_exists( 'tsm_addon_active' ) && tsm_addon_active( 'reports_transcripts' ) ) {
			add_action( 'admin_post_tsmp_report_card', array( $this, 'admin_report_card' ) );
		}
		// Certificate admin-post handlers ship in the Certificates add-on plugin.
		add_action( 'admin_post_tsmp_export',         array( 'TSMP_CSV', 'handle_export' ) );
		add_action( 'admin_post_tsmp_template',       array( 'TSMP_CSV', 'handle_template' ) );

		// Invoice PDFs + statements (admin + portal)  -  only when the Invoicing & Contracts add-on is active.
		if ( function_exists( 'tsm_addon_active' ) && tsm_addon_active( 'invoicing' ) ) {
			add_action( 'admin_post_tsmp_statement',                  array( $this, 'admin_statement' ) );
			add_action( 'admin_post_tsmp_invoice_pdf',                array( $this, 'admin_invoice_pdf' ) );
			add_action( 'admin_post_tsm_portal_invoice_pdf',          array( $this, 'portal_invoice_pdf' ) );
			add_action( 'admin_post_nopriv_tsm_portal_invoice_pdf',   array( $this, 'portal_invoice_pdf' ) );
			add_action( 'admin_post_tsm_portal_statement',            array( $this, 'portal_statement' ) );
			add_action( 'admin_post_nopriv_tsm_portal_statement',     array( $this, 'portal_statement' ) );
			add_action( 'admin_post_tsm_portal_payment_receipt',        array( $this, 'portal_payment_receipt' ) );
			add_action( 'admin_post_nopriv_tsm_portal_payment_receipt', array( $this, 'portal_payment_receipt' ) );
			add_action( 'admin_post_tsmp_payment_receipt',              array( $this, 'admin_payment_receipt' ) );
		}

		// Dashboard widget.
		add_action( 'wp_dashboard_setup', array( $this, 'dashboard_widget' ) );
	}

	public function register_submenus( $parent, $cap ) {
		// Invoicing & Contracts owns its own top-level submenu (slug: tsm-invoicing)
		// registered by TSM_Invoicing_Admin. We do NOT register a duplicate
		// "tsm-invoices" submenu here, otherwise the page renders inside two
		// shells (the legacy wrapper + the add-on's own shell_open).
		if ( function_exists( 'tsm_addon_active' ) && tsm_addon_active( 'custom_fields' ) ) {
			add_submenu_page( $parent, __( 'Custom Fields & Documents', 'tradeschool-manager' ),    __( 'Custom Fields & Docs', 'tradeschool-manager' ),    $cap, 'tsm-custom-fields',    array( $this, 'page_custom_fields' ) );
		}
		add_submenu_page( $parent, __( 'Notes', 'tradeschool-manager' ),            __( 'Notes', 'tradeschool-manager' ),            $cap, 'tsm-notes',            array( $this, 'page_notes' ) );
		// v1.9.8: Advanced Reports + Audit Log are now tabs inside the unified core "Reports" page.
		// The page callbacks below remain for backward compatibility (TSMP_Reports::render_admin / TSMP_Audit::render_admin).
		// Certificates submenu is registered by the Certificates add-on plugin.
		add_submenu_page( $parent, __( 'Announcements', 'tradeschool-manager' ),    __( 'Announcements', 'tradeschool-manager' ),    $cap, 'tsm-announcements',    array( $this, 'page_announcements' ) );
		add_submenu_page( $parent, __( 'Email Students', 'tradeschool-manager' ),   __( 'Email Students', 'tradeschool-manager' ),   $cap, 'tsm-email-students',   array( $this, 'page_email_students' ) );
		add_submenu_page( $parent, __( 'Email Templates', 'tradeschool-manager' ),  __( 'Email Templates', 'tradeschool-manager' ),  $cap, 'tsm-emails',           array( $this, 'page_emails' ) );
		add_submenu_page( $parent, __( 'Email Deliverability', 'tradeschool-manager' ),   __( 'Email Deliverability', 'tradeschool-manager' ),   $cap, 'tsm-brevo',            array( $this, 'page_brevo' ) );
		add_submenu_page( $parent, __( 'Import / Export', 'tradeschool-manager' ),  __( 'Import / Export', 'tradeschool-manager' ),  $cap, 'tsm-csv',              array( $this, 'page_csv' ) );
		// Archive is now a tab inside the "School Years" page (page_school_years)  -  no separate submenu.
		// Portal Theme submenu removed in v1.19.30  -  portals now inherit branding from the global Brand Color in Settings.
	}

	public function register_nav_items( $items ) {
		// Insert Pro items before the system section.
		// Note: Advanced Reports + Audit Log are now sub-tabs of the core "Reports" item, no longer standalone.
		$pro_items = array(
		);
		if ( function_exists( 'tsm_addon_active' ) && tsm_addon_active( 'custom_fields' ) ) {
			array_unshift( $pro_items, array( 'slug' => 'tsm-custom-fields', 'label' => __( 'Custom Fields & Docs', 'tradeschool-manager' ), 'icon' => 'dashicons-forms' ) );
		}
		$pro_items = array_merge( $pro_items, array(
			array( 'slug' => 'tsm-notes',            'label' => __( 'Notes',            'tradeschool-manager' ), 'icon' => 'dashicons-format-aside' ),
			array( 'slug' => 'tsm-announcements',    'label' => __( 'Announcements',    'tradeschool-manager' ), 'icon' => 'dashicons-megaphone' ),
			array( 'slug' => 'tsm-email-students',   'label' => __( 'Email Students',   'tradeschool-manager' ), 'icon' => 'dashicons-email' ),
			array( 'slug' => 'tsm-emails',           'label' => __( 'Email Templates',  'tradeschool-manager' ), 'icon' => 'dashicons-email-alt' ),
			array( 'slug' => 'tsm-brevo',            'label' => __( 'Email Deliverability',   'tradeschool-manager' ), 'icon' => 'dashicons-cloud' ),
			array( 'slug' => 'tsm-csv',              'label' => __( 'Import / Export',  'tradeschool-manager' ), 'icon' => 'dashicons-upload' ),
			// Archive nav item removed  -  archived years now live as a tab on the School Years page.
			// Portal Theme nav item removed in v1.19.30.
		) );
		if ( function_exists( 'tsm_addon_active' ) && tsm_addon_active( 'invoicing' ) ) {
			array_unshift( $pro_items, array( 'slug' => 'tsm-invoicing', 'label' => __( 'Invoicing', 'tradeschool-manager' ), 'icon' => 'dashicons-media-spreadsheet' ) );
		}
		// Certificates nav item is registered by the Certificates add-on plugin.
		// Find first system index.
		$out = array();
		$inserted = false;
		foreach ( $items as $it ) {
			if ( ! $inserted && isset( $it['section'] ) && 'system' === $it['section'] ) {
				foreach ( $pro_items as $p ) { $out[] = $p; }
				$inserted = true;
			}
			$out[] = $it;
		}
		if ( ! $inserted ) {
			foreach ( $pro_items as $p ) { $out[] = $p; }
		}
		return $out;
	}

	private function shell( $cb, $title ) {
		$admin = TSM_Admin::instance();
		$admin->shell_open( $title );
		call_user_func( $cb );
		$admin->shell_close();
	}
	public function page_invoices()      { $this->shell( array( 'TSMP_Invoices', 'render_admin' ),     __( 'Invoices', 'tradeschool-manager' ) ); }
	public function page_custom_fields() { $this->shell( array( 'TSMP_Custom_Fields', 'render_admin' ), __( 'Custom Fields & Student Documents', 'tradeschool-manager' ) ); }
	public function page_notes()         { $this->shell( array( 'TSMP_Notes', 'render_admin' ),         __( 'Instructor Notes', 'tradeschool-manager' ) ); }
	public function page_adv_reports()   { $this->shell( array( 'TSMP_Reports', 'render_admin' ),       __( 'Advanced Reports', 'tradeschool-manager' ) ); }
	public function page_emails()        { $this->shell( array( 'TSMP_Emails', 'render_admin' ),        __( 'Email Templates', 'tradeschool-manager' ) ); }
	public function page_brevo()         { $this->shell( array( 'TSMP_Brevo', 'render_admin' ),         __( 'Email Deliverability', 'tradeschool-manager' ) ); }
	public function page_csv()           { $this->shell( array( 'TSMP_CSV', 'render_admin' ),           __( 'Import / Export', 'tradeschool-manager' ) ); }
	public function page_audit()         { $this->shell( array( 'TSMP_Audit', 'render_admin' ),         __( 'Audit Log', 'tradeschool-manager' ) ); }
	public function page_archive()       { $this->shell( array( 'TSMP_Archive_Theme', 'render_admin_archive' ), __( 'Archived School Years', 'tradeschool-manager' ) ); }
	public function page_portal_theme()  { $this->shell( array( 'TSMP_Archive_Theme', 'render_admin_theme' ),   __( 'Portal Theme', 'tradeschool-manager' ) ); }
	public function page_announcements() { $this->shell( array( 'TSM_Announcements', 'render_admin' ),         __( 'Portal Announcements', 'tradeschool-manager' ) ); }
	public function page_email_students(){ $this->shell( array( $this, 'render_email_students' ),              __( 'Email Students', 'tradeschool-manager' ) ); }

	/* All certificate page rendering, template editor, action handlers, and editor JS/CSS were moved to the standalone Certificates add-on plugin (tradeschool-certificates) in v1.16.0. */


	/* admin-post handlers */
	public function admin_report_card() {
		if ( ! current_user_can( 'manage_tradeschool' ) ) wp_die( 'Forbidden' );
		check_admin_referer( 'tsmp_report_card' );
		$student_id = absint( $_GET['student_id'] ?? 0 );
		TSMP_PDF::output_report_card( $student_id );
	}
	public function admin_statement() {
		$sid = absint( $_GET['student_id'] ?? 0 );
		if ( ! current_user_can( 'manage_tradeschool' ) ) wp_die( 'Forbidden' );
		check_admin_referer( 'tsmp_statement_' . $sid );
		TSMP_PDF::output_statement( $sid );
	}
	/* admin_certificate / admin_generate_cert moved to the Certificates add-on plugin. */

	/* ---- Invoice PDF + portal handlers (v1.6.0) ---- */
	public function admin_invoice_pdf() {
		if ( ! current_user_can( 'manage_tradeschool' ) ) wp_die( 'Forbidden' );
		$id = absint( $_GET['id'] ?? 0 );
		check_admin_referer( 'tsmp_invoice_pdf_' . $id );
		TSMP_PDF::output_invoice( $id );
	}
	public function portal_invoice_pdf() {
		$sid = TSM_Public::current_student_id();
		if ( ! $sid ) wp_die( 'Sign in required.' );
		$id = absint( $_GET['id'] ?? 0 );
		check_admin_referer( 'tsm_portal_invoice_pdf_' . $id );
		$inv = TSMP_Invoices::get( $id );
		if ( ! $inv || (int) $inv->student_id !== $sid ) wp_die( 'Not allowed.' );
		TSMP_PDF::output_invoice( $id );
	}
	public function portal_statement() {
		$sid = TSM_Public::current_student_id();
		if ( ! $sid ) wp_die( 'Sign in required.' );
		check_admin_referer( 'tsm_portal_statement' );
		TSMP_PDF::output_account_statement( $sid );
	}
	public function portal_payment_receipt() {
		$sid = TSM_Public::current_student_id();
		if ( ! $sid ) wp_die( 'Sign in required.' );
		$id = absint( $_GET['id'] ?? 0 );
		check_admin_referer( 'tsm_portal_payment_receipt_' . $id );
		$pay = class_exists( 'TSMP_Payments' ) ? TSMP_Payments::get( $id ) : null;
		if ( ! $pay || (int) $pay->student_id !== (int) $sid ) wp_die( 'Not allowed.' );
		TSMP_PDF::output_payment_receipt( $id );
	}
	public function admin_payment_receipt() {
		if ( ! current_user_can( 'manage_tradeschool' ) ) wp_die( 'Forbidden' );
		$id = absint( $_GET['id'] ?? 0 );
		check_admin_referer( 'tsmp_payment_receipt_' . $id );
		TSMP_PDF::output_payment_receipt( $id );
	}

	public function portal_extras( $student_id ) {
		echo TSMP_Archive_Theme::announcement_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		if ( class_exists( 'TSMP_Custom_Fields' ) ) {
			TSMP_Custom_Fields::render_portal_fields( $student_id );
		}
		if ( class_exists( 'TSMP_Payments' ) ) {
			TSMP_Payments::render_portal( $student_id );
		}
	}

	public function dashboard_widget() {
		if ( ! current_user_can( 'manage_tradeschool' ) ) return;
		if ( ! class_exists( 'TSMP_Reports' ) || ! ( function_exists( 'tsm_addon_active' ) && tsm_addon_active( 'reports_transcripts' ) ) ) return;
		wp_add_dashboard_widget( 'tsmp_widget', __( 'TradeSchool Manager', 'tradeschool-manager' ), array( 'TSMP_Reports', 'dashboard_widget' ) );
	}

	/**
	 * Mass-email recipients selected via the shared audience picker.
	 */
	public function render_email_students() {
		if ( ! current_user_can( 'manage_tradeschool' ) ) return;

		$sent = 0; $failed = 0; $recipients = array();
		$posted_audience = array( 'type' => 'all', 'value' => null );

		if ( isset( $_POST['tsm_mass_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsm_mass_nonce'] ) ), 'tsm_mass_send' ) ) {
			list( $type, $value ) = TSMP_Audience::parse_post( wp_unslash( $_POST ), 'audience' );
			$posted_audience = array( 'type' => $type, 'value' => $value );
			$students   = TSMP_Audience::resolve_students( $type, $value );
			$recipients = array_values( array_filter( $students, function( $s ){ return ! empty( $s->email ); } ) );

			$subject = sanitize_text_field( wp_unslash( $_POST['subject'] ?? '' ) );
			$body    = wp_kses_post( wp_unslash( $_POST['body'] ?? '' ) );
			if ( $subject && $body && ! empty( $recipients ) ) {
				foreach ( $recipients as $s ) {
					$tokens = array(
						'first_name'  => $s->first_name,
						'last_name'   => $s->last_name,
						'school_name' => tsm_get_setting( 'school_name', get_bloginfo( 'name' ) ),
					);
					$subj_r = TSMP_Emails::render_tokens( $subject, $tokens );
					$body_r = TSMP_Emails::render_tokens( $body, $tokens );
					$bulk_headers = array(
						'Content-Type: text/html; charset=UTF-8',
						'X-TSM-Tag: broadcast',
						'X-TSM-Broadcast: 1',
					);
					$ok = wp_mail( $s->email, $subj_r, wpautop( $body_r ), $bulk_headers );
					$ok ? $sent++ : $failed++;
				}
				/* translators: 1: sent count, 2: failed count */
				echo '<div class="notice notice-success"><p>' . esc_html( sprintf( __( 'Sent %1$d emails. Failed: %2$d.', 'tradeschool-manager' ), $sent, $failed ) ) . '</p></div>';
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__( 'Subject, message, and at least one recipient with an email on file are required.', 'tradeschool-manager' ) . '</p></div>';
			}
		}
		?>
		<form method="post" onsubmit="return confirm('<?php echo esc_js( __( 'Send this message to the selected audience?', 'tradeschool-manager' ) ); ?>');">
			<?php wp_nonce_field( 'tsm_mass_send', 'tsm_mass_nonce' ); ?>

			<div style="background:#fff;border:1px solid #dcdcde;border-radius:10px;padding:18px;margin-top:14px;">
				<h2 style="margin-top:0;"><?php esc_html_e( 'Audience', 'tradeschool-manager' ); ?></h2>
				<?php TSMP_Audience::render( 'audience', $posted_audience ); ?>
			</div>

			<div style="background:#fff;border:1px solid #dcdcde;border-radius:10px;padding:18px;margin-top:16px;">
				<h2 style="margin-top:0;"><?php esc_html_e( 'Message', 'tradeschool-manager' ); ?></h2>
				<p style="margin:0 0 6px;font-weight:600;"><?php esc_html_e( 'Subject', 'tradeschool-manager' ); ?></p>
				<input id="tsm_mass_subject" class="large-text" name="subject" required value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['subject'] ?? '' ) ) ); ?>">

				<p style="margin:14px 0 6px;font-weight:600;"><?php esc_html_e( 'Body', 'tradeschool-manager' ); ?></p>
				<textarea id="tsm_mass_body" class="large-text" name="body" rows="10" required><?php echo esc_textarea( sanitize_textarea_field( wp_unslash( $_POST['body'] ?? '' ) ) ); ?></textarea>
				<p class="description"><?php esc_html_e( 'Tokens: {first_name} {last_name} {school_name}', 'tradeschool-manager' ); ?></p>

				<p style="margin-top:14px;">
					<button class="button button-primary"><?php esc_html_e( 'Send', 'tradeschool-manager' ); ?></button>
					<span class="description" style="margin-left:8px;"><?php esc_html_e( 'Only students with an email on file will be messaged.', 'tradeschool-manager' ); ?></span>
				</p>
			</div>
		</form>
		<?php
	}
}
