<?php
/**
 * Admin Instructors Management
 *
 * Handles the instructors management admin page
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.2
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class MACM_Admin_Instructors
 *
 * Manages the clubs admin interface
 *
 * @since 1.0.2
 */
class MACM_Admin_Instructors {

	/**
	 * Constructor
	 *
	 * @since 1.0.2
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ), 13 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_post_macm_save_instructor', array( $this, 'save_instructor' ) );
		add_action( 'admin_post_macm_delete_instructor', array( $this, 'delete_instructor' ) );
	}

	/**
	 * Add submenu page
	 *
	 * @since 1.0.2
	 */
	public function add_menu_page() {
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'Instructors', 'martial-arts-club-manager' ),
			__( 'Instructors', 'martial-arts-club-manager' ),
			'manage_macm_classes',
			'kcm-instructors',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Enqueue scripts for instructors page
	 *
	 * @since 1.0.174
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Only load on instructors page.
		if ( false === strpos( $hook, 'kcm-instructors' ) ) {
			return;
		}

		wp_enqueue_script(
			'kcm-admin-instructors',
			MACM_PLUGIN_URL . 'assets/js/admin-instructors.js',
			array( 'jquery' ),
			MACM_VERSION,
			true
		);
	}

	/**
	 * Render the clubs page
	 *
	 * @since 1.0.2
	 */
	public function render_page() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'martial-arts-club-manager' ) );
		}

		// Get all clubs (including inactive).
		$instructors = MACM_Instructor::get_all( false );

		// Get message from transient (set by save/delete handlers).
		$message       = '';
		$error         = '';
		$transient_key = 'macm_instructor_message_' . get_current_user_id();
		$transient     = get_transient( $transient_key );

		if ( $transient ) {
			delete_transient( $transient_key );
			$message = isset( $transient['type'] ) ? $transient['type'] : '';
			$error   = isset( $transient['error'] ) ? $transient['error'] : '';
		}

		// Get instructor to edit (with nonce verification).
		$edit_instructor = null;
		$edit_nonce      = filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$edit_id_input   = filter_input( INPUT_GET, 'edit', FILTER_SANITIZE_NUMBER_INT );
		if ( $edit_nonce && $edit_id_input ) {
			$edit_id = absint( $edit_id_input );
			if ( $edit_id > 0 && wp_verify_nonce( $edit_nonce, 'macm_edit_instructor_' . $edit_id ) ) {
				$edit_instructor = MACM_Instructor::get( $edit_id );
			}
		}

		// Check for saved form data (from validation error).
		$form_data = null;
		if ( $error ) {
			$form_data = get_transient( 'macm_instructor_form_data_' . get_current_user_id() );
			if ( $form_data ) {
				delete_transient( 'macm_instructor_form_data_' . get_current_user_id() );
			}
		}

		// Helper function to get field value (prioritize form_data, then edit_instructor, then default).
		$get_value = function ( $field, $default = '' ) use ( $form_data, $edit_instructor ) {
			if ( $form_data && isset( $form_data[ $field ] ) ) {
				return $form_data[ $field ];
			}
			// Special case: instructor_id is stored as 'id' in the object.
			if ( 'instructor_id' === $field && $edit_instructor && isset( $edit_instructor->id ) ) {
				return $edit_instructor->id;
			}
			if ( $edit_instructor && isset( $edit_instructor->$field ) ) {
				return $edit_instructor->$field ?? $default;
			}
			return $default;
		};

		?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?php esc_html_e( 'Instructors', 'martial-arts-club-manager' ); ?></h1>
			<a href="#" class="page-title-action" id="kcm-add-instructor-btn"><?php esc_html_e( 'Add New', 'martial-arts-club-manager' ); ?></a>
			<hr class="wp-header-end">

			<p class="description">
				<?php esc_html_e( 'Manage instructors. Instructors can be assigned to classes for teaching and attendance tracking.', 'martial-arts-club-manager' ); ?>
			</p>

			<?php if ( 'saved' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Instructor saved successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php elseif ( 'deleted' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Instructor deleted successfully. All member associations have been removed.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php endif; ?>

			<?php if ( $error ) : ?>
				<div class="notice notice-error ">
					<p><strong>Error:</strong> <?php echo esc_html( urldecode( $error ) ); ?></p>
				</div>
			<?php endif; ?>

			<!-- Add/Edit Form -->
			<div id="kcm-instructor-form" style="<?php echo ( $edit_instructor || $error ) ? '' : 'display: none;'; ?>">
				<div class="card" style="max-width: 600px; margin: 20px 0;">
					<h2><?php echo ( $edit_instructor || ( $form_data && isset( $form_data['instructor_id'] ) ) ) ? esc_html__( 'Edit Instructor', 'martial-arts-club-manager' ) : esc_html__( 'Add New Instructor', 'martial-arts-club-manager' ); ?></h2>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<?php wp_nonce_field( 'macm_save_instructor', 'macm_instructor_nonce' ); ?>
						<input type="hidden" name="action" value="macm_save_instructor">
						<?php if ( $edit_instructor || ( $form_data && isset( $form_data['instructor_id'] ) ) ) : ?>
							<input type="hidden" name="instructor_id" value="<?php echo esc_attr( $get_value( 'instructor_id' ) ); ?>">
						<?php endif; ?>

						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="full_name"><?php esc_html_e( 'Full Name', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
								</th>
								<td>
									<input type="text"
											id="full_name"
											name="full_name"
											class="regular-text"
											value="<?php echo esc_attr( $get_value( 'full_name' ) ); ?>"
											>
									<p class="description"><?php esc_html_e( 'Enter the instructor\'s full name', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="instructor_email"><?php esc_html_e( 'Email', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<input type="text"
											id="instructor_email"
											name="email"
											class="regular-text"
											value="<?php echo esc_attr( $get_value( 'email' ) ); ?>">
									<p class="description"><?php esc_html_e( 'Instructor\'s email address (optional)', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="instructor_phone"><?php esc_html_e( 'Phone', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<input type="tel" pattern="[0-9+\-\s\(\)]+" title="Please enter a valid phone number (numbers, spaces, +, -, parentheses only)"
											id="instructor_phone"
											name="phone"
											class="regular-text"
											value="<?php echo esc_attr( $get_value( 'phone' ) ); ?>">
									<p class="description"><?php esc_html_e( 'Contact phone number - numbers only (optional)', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="instructor_specialization"><?php esc_html_e( 'Specialization', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<textarea id="instructor_specialization"
												name="specialization"
												class="large-text"
												rows="2"><?php echo esc_textarea( $get_value( 'specialization' ) ); ?></textarea>
									<p class="description"><?php esc_html_e( 'E.g., Kumite, Kata, Kids Training, etc. (optional)', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="instructor_bio"><?php esc_html_e( 'Bio', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<textarea id="instructor_bio"
												name="bio"
												class="large-text"
												rows="4"><?php echo esc_textarea( $get_value( 'bio' ) ); ?></textarea>
									<p class="description"><?php esc_html_e( 'Brief biography or qualifications (optional)', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="instructor_is_active"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<label>
										<input type="checkbox"
												id="instructor_is_active"
												name="is_active"
												value="1"
												<?php checked( $get_value( 'is_active', 1 ), 1 ); ?>>
										<?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?>
									</label>
									<p class="description"><?php esc_html_e( 'Inactive instructors won\'t be available for class assignment', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
						</table>

						<p class="submit">
							<input type="submit" class="button button-primary" value="<?php echo ( $edit_instructor || ( $form_data && isset( $form_data['instructor_id'] ) ) ) ? esc_attr__( 'Update Instructor', 'martial-arts-club-manager' ) : esc_attr__( 'Add Instructor', 'martial-arts-club-manager' ); ?>">
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-instructors' ) ); ?>" class="button"><?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?></a>
						</p>
					</form>
				</div>
			</div>

			<!-- Instructors List -->
			<table class="wp-list-table widefat fixed striped kcm-instructors-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Instructor Name', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Email', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Phone', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Specialization', 'martial-arts-club-manager' ); ?></th>
						<th scope="col" class="num"><?php esc_html_e( 'Classes', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Actions', 'martial-arts-club-manager' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php if ( ! empty( $instructors ) ) : ?>
						<?php foreach ( $instructors as $instructor ) : ?>
							<?php
							$class_count = MACM_Instructor::get_class_count( $instructor->id );
							?>
							<tr>
								<td>
									<strong><?php echo esc_html( $instructor->full_name ); ?></strong>
								</td>
								<td>
									<?php echo $instructor->email ? esc_html( $instructor->email ) : '<span class="description">' . esc_html__( '—', 'martial-arts-club-manager' ) . '</span>'; ?>
								</td>
								<td>
									<?php echo $instructor->phone ? esc_html( $instructor->phone ) : '<span class="description">' . esc_html__( '—', 'martial-arts-club-manager' ) . '</span>'; ?>
								</td>
								<td>
									<?php echo $instructor->specialization ? esc_html( $instructor->specialization ) : '<span class="description">' . esc_html__( '—', 'martial-arts-club-manager' ) . '</span>'; ?>
								</td>
								<td class="num">
									<?php echo esc_html( $class_count ); ?>
								</td>
								<td>
									<?php if ( $instructor->is_active ) : ?>
										<span class="kcm-badge kcm-badge-success"><?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?></span>
									<?php else : ?>
										<span class="kcm-badge kcm-badge-inactive"><?php esc_html_e( 'Inactive', 'martial-arts-club-manager' ); ?></span>
									<?php endif; ?>
								</td>
								<td>
									<?php
									$actions = array();

									// Edit action (with nonce for security).
									$edit_url        = wp_nonce_url(
										admin_url( 'admin.php?page=kcm-instructors&edit=' . $instructor->id ),
										'macm_edit_instructor_' . $instructor->id
									);
									$actions['edit'] = sprintf(
										'<a href="%s">%s</a>',
										esc_url( $edit_url ),
										esc_html__( 'Edit', 'martial-arts-club-manager' )
									);

									// Delete action (only if not in use).
									if ( 0 === $class_count ) {
										$confirm_message   = esc_js( __( 'Are you sure you want to delete this instructor? All member associations will be removed.', 'martial-arts-club-manager' ) );
										$actions['delete'] = sprintf(
											'<a href="%s" class="submitdelete" onclick="return confirm(&quot;%s&quot;);">%s</a>',
											esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=macm_delete_instructor&instructor_id=' . $instructor->id ), 'macm_delete_instructor_nonce_' . $instructor->id ) ),
											$confirm_message,
											esc_html__( 'Delete', 'martial-arts-club-manager' )
										);
									}

									echo '<div class="row-actions">';
									$action_links = array();
									foreach ( $actions as $key => $action ) {
										$action_links[] = '<span class="' . esc_attr( $key ) . '">' . $action . '</span>';
									}
									$allowed_html = array(
										'span' => array( 'class' => array() ),
										'a'    => array(
											'href'    => array(),
											'class'   => array(),
											'onclick' => array(),
										),
									);
									echo wp_kses( implode( ' | ', $action_links ), $allowed_html );
									if ( $class_count > 0 ) {
										echo ' | <span class="description">' . esc_html__( 'In use', 'martial-arts-club-manager' ) . '</span>';
									}
									echo '</div>';
									?>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php else : ?>
						<tr>
							<td colspan="7" style="text-align: center; padding: 40px 20px;">
								<p><?php esc_html_e( 'No instructors found.', 'martial-arts-club-manager' ); ?></p>
								<p><a href="#" id="kcm-add-instructor-btn-empty" class="button button-primary"><?php esc_html_e( 'Add Your First Instructor', 'martial-arts-club-manager' ); ?></a></p>
							</td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * Save club
	 *
	 * @since 1.0.2
	 */
	public function save_instructor() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'martial-arts-club-manager' ) );
		}

		// Verify nonce.
		$nonce = isset( $_POST['macm_instructor_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_instructor_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_instructor' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Validate email if provided (before sanitization).
		$raw_email = isset( $_POST['email'] ) ? trim( sanitize_email( wp_unslash( $_POST['email'] ) ) ) : '';
		if ( ! empty( $raw_email ) && ! is_email( $raw_email ) ) {
			// Store form data and error message in transients.
			set_transient( 'macm_instructor_form_data_' . get_current_user_id(), $_POST, 45 );
			set_transient(
				'macm_instructor_message_' . get_current_user_id(),
				array(
					'type'  => 'error',
					'error' => __( 'Invalid email address. Please enter a valid email or leave it empty.', 'martial-arts-club-manager' ),
				),
				30
			);
			wp_safe_redirect( admin_url( 'admin.php?page=kcm-instructors' ) );
			exit;
		}

		// Validate phone if provided (before sanitization).
		$raw_phone = isset( $_POST['phone'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['phone'] ) ) ) : '';
		if ( ! empty( $raw_phone ) && ! preg_match( '/^[0-9+\-\s\(\)]+$/', $raw_phone ) ) {
			// Store form data and error message in transients.
			set_transient( 'macm_instructor_form_data_' . get_current_user_id(), $_POST, 45 );
			set_transient(
				'macm_instructor_message_' . get_current_user_id(),
				array(
					'type'  => 'error',
					'error' => __( 'Invalid phone number. Please use only numbers, spaces, +, -, and parentheses.', 'martial-arts-club-manager' ),
				),
				30
			);
			wp_safe_redirect( admin_url( 'admin.php?page=kcm-instructors' ) );
			exit;
		}

		// Get instructor data.
		$instructor_data = array(
			'full_name'      => isset( $_POST['full_name'] ) ? sanitize_text_field( wp_unslash( $_POST['full_name'] ) ) : '',
			'email'          => ! empty( $raw_email ) ? sanitize_email( $raw_email ) : '',
			'phone'          => isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '',
			'specialization' => isset( $_POST['specialization'] ) ? sanitize_textarea_field( wp_unslash( $_POST['specialization'] ) ) : '',
			'bio'            => isset( $_POST['bio'] ) ? sanitize_textarea_field( wp_unslash( $_POST['bio'] ) ) : '',
			'is_active'      => isset( $_POST['is_active'] ) ? 1 : 0,
		);

		// Update or create.
		if ( isset( $_POST['instructor_id'] ) && ! empty( $_POST['instructor_id'] ) ) {
			// Update existing instructor.
			$instructor_id = absint( wp_unslash( $_POST['instructor_id'] ) );
			$result        = MACM_Instructor::update( $instructor_id, $instructor_data );
		} else {
			// Create new instructor.
			$result = MACM_Instructor::create( $instructor_data );
		}

		// Handle result - store message in transient.
		$transient_key = 'macm_instructor_message_' . get_current_user_id();
		if ( is_wp_error( $result ) ) {
			set_transient(
				$transient_key,
				array(
					'type'  => 'error',
					'error' => $result->get_error_message(),
				),
				30
			);
		} else {
			set_transient(
				$transient_key,
				array( 'type' => 'saved' ),
				30
			);
		}
		wp_safe_redirect( admin_url( 'admin.php?page=kcm-instructors' ) );
		exit;
	}

	/**
	 * Delete club
	 *
	 * @since 1.0.2
	 */
	public function delete_instructor() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'martial-arts-club-manager' ) );
		}

		// Get club ID.
		$instructor_id = isset( $_GET['instructor_id'] ) ? absint( wp_unslash( $_GET['instructor_id'] ) ) : 0;

		// Verify nonce.
		$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_delete_instructor_nonce_' . $instructor_id ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Delete club.
		$result = MACM_Instructor::delete( $instructor_id );

		// Handle result - store message in transient.
		$transient_key = 'macm_instructor_message_' . get_current_user_id();
		if ( is_wp_error( $result ) ) {
			set_transient(
				$transient_key,
				array(
					'type'  => 'error',
					'error' => $result->get_error_message(),
				),
				30
			);
		} else {
			set_transient(
				$transient_key,
				array( 'type' => 'deleted' ),
				30
			);
		}
		wp_safe_redirect( admin_url( 'admin.php?page=kcm-instructors' ) );
		exit;
	}
}

// Initialize.
new MACM_Admin_Instructors();
