<?php
/**
 * Pro: Archived school years (read-only) + portal theming.
 *
 * @package TradeSchoolManagerPro
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Plugin-owned custom tables; table names interpolated only; user values always pass through $wpdb->prepare().

class TSMP_Archive_Theme {

	const THEME_OPTION = 'tsmp_portal_theme';

	public static function defaults() {
		return array(
			'primary_color' => '#1f6feb',
			'bg_color'      => '#ffffff',
			'text_color'    => '#1f2937',
			'card_radius'   => '8',
			'header_layout' => 'centered',
			'announcement'  => '',
		);
	}

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

	public static function update_theme( $data ) {
		$existing = self::get_theme();
		$merged   = array_merge( $existing, $data );
		update_option( self::THEME_OPTION, $merged );
		return $merged;
	}

	/* --- Archive a school year + enforce read-only --- */
	public static function set_archived( $year_id, $archived = true ) {
		global $wpdb;
		$wpdb->update( $wpdb->prefix . 'tsm_school_years', array( 'archived' => $archived ? 1 : 0 ), array( 'id' => absint( $year_id ) ) );
	}

	public static function is_archived( $year_id ) {
		global $wpdb;
		return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT archived FROM {$wpdb->prefix}tsm_school_years WHERE id = %d", absint( $year_id ) ) );
	}

	public static function render_admin_archive() {
		// Toggle.
		if ( isset( $_GET['archive_year'] ) && check_admin_referer( 'tsmp_archive_' . absint( $_GET['archive_year'] ) ) ) {
			$id = absint( $_GET['archive_year'] );
			self::set_archived( $id, ! self::is_archived( $id ) );
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Archive status updated.', 'tradeschool-manager' ) . '</p></div>';
		}
		$years = TSM_School_Years::all();
		?>
		<h2><?php esc_html_e( 'Archived School Years', 'tradeschool-manager' ); ?></h2>
		<p><?php esc_html_e( 'Archived years are read-only: classes, grades, and assignments cannot be edited or deleted.', 'tradeschool-manager' ); ?></p>
		<table class="widefat striped">
			<thead><tr><th><?php esc_html_e( 'Name', 'tradeschool-manager' ); ?></th><th><?php esc_html_e( 'Dates', 'tradeschool-manager' ); ?></th><th><?php esc_html_e( 'Archived', 'tradeschool-manager' ); ?></th><th></th></tr></thead>
			<tbody>
				<?php foreach ( $years as $y ) : ?>
					<tr>
						<td><?php echo esc_html( $y->name ); ?></td>
						<td><?php echo esc_html( $y->start_date . ' -> ' . $y->end_date ); ?></td>
						<td><?php echo $y->archived ? '🔒 Yes' : ' - '; ?></td>
						<td><a class="button button-small" href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'archive_year', $y->id ), 'tsmp_archive_' . $y->id ) ); ?>"><?php echo $y->archived ? esc_html__( 'Unarchive', 'tradeschool-manager' ) : esc_html__( 'Archive', 'tradeschool-manager' ); ?></a></td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php
	}

	public static function render_admin_theme() {
		if ( isset( $_POST['tsmp_theme_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsmp_theme_nonce'] ) ), 'tsmp_theme' ) ) {
			self::update_theme(
				array(
					'primary_color' => sanitize_hex_color( wp_unslash( $_POST['primary_color'] ?? '' ) ),
					'bg_color'      => sanitize_hex_color( wp_unslash( $_POST['bg_color'] ?? '' ) ),
					'text_color'    => sanitize_hex_color( wp_unslash( $_POST['text_color'] ?? '' ) ),
					'card_radius'   => absint( wp_unslash( $_POST['card_radius'] ?? 8 ) ),
					'header_layout' => sanitize_text_field( wp_unslash( $_POST['header_layout'] ?? 'centered' ) ),
					'announcement'  => wp_kses_post( wp_unslash( $_POST['announcement'] ?? '' ) ),
				)
			);
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Portal theme saved.', 'tradeschool-manager' ) . '</p></div>';
		}
		$t = self::get_theme();
		?>
		<h2><?php esc_html_e( 'Customize Portal Appearance', 'tradeschool-manager' ); ?></h2>
		<form method="post">
			<?php wp_nonce_field( 'tsmp_theme', 'tsmp_theme_nonce' ); ?>
			<table class="form-table">
				<tr><th><?php esc_html_e( 'Primary Color', 'tradeschool-manager' ); ?></th><td><input type="color" name="primary_color" value="<?php echo esc_attr( $t['primary_color'] ); ?>"></td></tr>
				<tr><th><?php esc_html_e( 'Background Color', 'tradeschool-manager' ); ?></th><td><input type="color" name="bg_color" value="<?php echo esc_attr( $t['bg_color'] ); ?>"></td></tr>
				<tr><th><?php esc_html_e( 'Text Color', 'tradeschool-manager' ); ?></th><td><input type="color" name="text_color" value="<?php echo esc_attr( $t['text_color'] ); ?>"></td></tr>
				<tr><th><?php esc_html_e( 'Card Radius (px)', 'tradeschool-manager' ); ?></th><td><input type="number" name="card_radius" min="0" max="40" value="<?php echo esc_attr( $t['card_radius'] ); ?>"></td></tr>
				<tr><th><?php esc_html_e( 'Header Layout', 'tradeschool-manager' ); ?></th><td>
					<select name="header_layout">
						<option value="centered" <?php selected( $t['header_layout'], 'centered' ); ?>>Centered</option>
						<option value="left" <?php selected( $t['header_layout'], 'left' ); ?>>Left-aligned</option>
					</select>
				</td></tr>
				<tr><th><?php esc_html_e( 'Announcement (shown on portal)', 'tradeschool-manager' ); ?></th><td><textarea class="large-text" name="announcement" rows="4"><?php echo esc_textarea( $t['announcement'] ); ?></textarea></td></tr>
			</table>
			<p><button class="button button-primary"><?php esc_html_e( 'Save Theme', 'tradeschool-manager' ); ?></button></p>
		</form>
		<?php
	}

	public static function inject_portal_css() {
		$t = self::get_theme();
		$align = 'left' === $t['header_layout'] ? 'left' : 'center';
		TSM_Inline_Assets::style(
			'tsmp-archive-theme',
			sprintf(
				'.tsm-portal-wrap{background:%1$s;color:%2$s;padding:24px;border-radius:%3$dpx;}.tsm-portal-header{text-align:%4$s;}.tsm-portal-wrap a,.tsm-portal-wrap h2,.tsm-portal-wrap h3{color:%5$s;}.tsm-btn{background:%5$s !important;}',
				esc_attr( $t['bg_color'] ),
				esc_attr( $t['text_color'] ),
				absint( $t['card_radius'] ),
				esc_attr( $align ),
				esc_attr( $t['primary_color'] )
			)
		);
	}

	public static function announcement_html() {
		$t = self::get_theme();
		if ( empty( $t['announcement'] ) ) return '';
		return '<section style="background:#fffbe6;border:1px solid #f1d99c;padding:12px 16px;border-radius:6px;margin-bottom:14px;">' . wp_kses_post( $t['announcement'] ) . '</section>';
	}
}
