<?php
/**
 * Pro: Instructor notes per student.
 *
 * @package TradeSchoolManagerPro
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

class TSMP_Notes {
	public static function table() {
		global $wpdb; return $wpdb->prefix . 'tsm_notes';
	}

	public static function for_student( $student_id ) {
		global $wpdb;
		$t = self::table();
		return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$t} WHERE student_id = %d ORDER BY id DESC", absint( $student_id ) ) );
	}

	public static function add( $student_id, $body ) {
		global $wpdb;
		$wpdb->insert(
			self::table(),
			array(
				'student_id' => absint( $student_id ),
				'author_id'  => get_current_user_id(),
				'body'       => sanitize_textarea_field( $body ),
			)
		);
		return (int) $wpdb->insert_id;
	}

	public static function delete( $id ) {
		global $wpdb;
		$wpdb->delete( self::table(), array( 'id' => absint( $id ) ) );
	}

	public static function render_admin() {
		// Handle "add note to selected audience"
		if ( isset( $_POST['tsmp_note_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsmp_note_nonce'] ) ), 'tsmp_note' ) ) {
			$body = sanitize_textarea_field( wp_unslash( $_POST['body'] ?? '' ) );
			list( $type, $value ) = TSMP_Audience::parse_post( wp_unslash( $_POST ), 'audience' );
			$targets = TSMP_Audience::resolve_students( $type, $value );
			$n = 0;
			if ( $body && ! empty( $targets ) ) {
				foreach ( $targets as $s ) { self::add( $s->id, $body ); $n++; }
			}
			/* translators: %d: number of students the note was saved to. */
			echo '<div class="notice notice-success"><p>' . esc_html( sprintf( _n( 'Saved note to %d student.', 'Saved note to %d students.', $n, 'tradeschool-manager' ), $n ) ) . '</p></div>';
		}
		if ( isset( $_GET['del_note'] ) && check_admin_referer( 'tsmp_del_note_' . absint( $_GET['del_note'] ) ) ) {
			self::delete( absint( $_GET['del_note'] ) );
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Note deleted.', 'tradeschool-manager' ) . '</p></div>';
		}

		$filter_sid = isset( $_GET['student_id'] ) ? absint( $_GET['student_id'] ) : 0;
		$students   = TSM_Students::active();
		?>
		<div style="display:grid;grid-template-columns:1.1fr 1fr;gap:24px;align-items:start;margin-top:14px;">

			<!-- Compose card -->
			<div style="background:#fff;border:1px solid #dcdcde;border-radius:10px;padding:18px;">
				<h2 style="margin-top:0;"><?php esc_html_e( 'Add Note', 'tradeschool-manager' ); ?></h2>
				<form method="post">
					<?php wp_nonce_field( 'tsmp_note', 'tsmp_note_nonce' ); ?>
					<p style="margin:0 0 6px;font-weight:600;"><?php esc_html_e( 'Audience', 'tradeschool-manager' ); ?></p>
					<?php TSMP_Audience::render( 'audience', array( 'type' => 'specific' ) ); ?>
					<p style="margin:14px 0 6px;font-weight:600;"><?php esc_html_e( 'Note', 'tradeschool-manager' ); ?></p>
					<textarea required class="large-text" rows="6" name="body" placeholder="<?php esc_attr_e( 'This note will be attached to every selected student\'s record.', 'tradeschool-manager' ); ?>"></textarea>
					<p style="margin-top:14px;"><button class="button button-primary"><?php esc_html_e( 'Save Note', 'tradeschool-manager' ); ?></button></p>
				</form>
			</div>

			<!-- Browse card -->
			<div style="background:#fff;border:1px solid #dcdcde;border-radius:10px;padding:18px;">
				<h2 style="margin-top:0;"><?php esc_html_e( 'Browse Notes', 'tradeschool-manager' ); ?></h2>
				<form method="get" style="margin-bottom:12px;">
					<input type="hidden" name="page" value="tsm-notes">
					<select name="student_id" onchange="this.form.submit()" style="min-width:260px;">
						<option value="0"><?php esc_html_e( ' -  Select student  - ', 'tradeschool-manager' ); ?></option>
						<?php foreach ( $students as $s ) : ?>
							<option value="<?php echo (int) $s->id; ?>" <?php selected( $filter_sid, $s->id ); ?>><?php echo esc_html( $s->last_name . ', ' . $s->first_name ); ?></option>
						<?php endforeach; ?>
					</select>
				</form>
				<?php if ( $filter_sid ) :
					$notes = self::for_student( $filter_sid );
					if ( empty( $notes ) ) : ?>
						<p style="color:#646970;"><?php esc_html_e( 'No notes for this student yet.', 'tradeschool-manager' ); ?></p>
					<?php else :
						foreach ( $notes as $n ) :
							$u = $n->author_id ? get_userdata( $n->author_id ) : null; ?>
							<div style="background:#fafafa;padding:10px 14px;border:1px solid #eee;border-radius:6px;margin:8px 0;">
								<div style="font-size:12px;color:#666;">
									<?php echo esc_html( ( $u ? $u->user_login : ' - ' ) . ' - ' . $n->created_at ); ?>
									<a style="float:right;" href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'del_note', $n->id ), 'tsmp_del_note_' . $n->id ) ); ?>" onclick="return confirm('Delete?')"><?php esc_html_e( 'Delete', 'tradeschool-manager' ); ?></a>
								</div>
								<div><?php echo nl2br( esc_html( $n->body ) ); ?></div>
							</div>
						<?php endforeach;
					endif;
				else : ?>
					<p style="color:#646970;"><?php esc_html_e( 'Pick a student to view their notes.', 'tradeschool-manager' ); ?></p>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}
}
