<?php
/**
 * Admin Grading History Management
 *
 * Handles admin interface for managing member grading/belt history
 *
 * @package KarateClubManager
 * @since 1.0.114
 */

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

/**
 * MACM_Admin_Grading_History class
 */
class MACM_Admin_Grading_History {

	/**
	 * Constructor
	 */
	public function __construct() {
		// AJAX handlers.
		add_action( 'wp_ajax_macm_get_grading_history', array( $this, 'ajax_get_history' ) );
		add_action( 'wp_ajax_macm_save_grading', array( $this, 'ajax_save_grading' ) );
		add_action( 'wp_ajax_macm_delete_grading', array( $this, 'ajax_delete_grading' ) );

		// CSV export handler.
		add_action( 'admin_init', array( $this, 'handle_csv_export' ) );

		// Enqueue scripts - priority 20 to ensure it runs after MACM_Admin::enqueue_scripts (priority 10).
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 20 );
	}

	/**
	 * Enqueue admin scripts for grading history
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Load on all karate club manager admin pages.
		// The hook for subpages is like: martial-arts_page_kcm-members.
		if ( false === strpos( $hook, 'martial-arts-club-manager' ) && false === strpos( $hook, 'kcm-' ) && false === strpos( $hook, 'martial-arts' ) ) {
			return;
		}

		wp_localize_script(
			'kcm-admin-scripts',
			'macmGrading',
			array(
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'kcm-grading-nonce' ),
				'strings' => array(
					'confirmDelete' => __( 'Are you sure you want to delete this grading record?', 'martial-arts-club-manager' ),
					'loading'       => __( 'Loading...', 'martial-arts-club-manager' ),
					'error'         => __( 'An error occurred. Please try again.', 'martial-arts-club-manager' ),
					'saved'         => __( 'Grading record saved successfully.', 'martial-arts-club-manager' ),
					'deleted'       => __( 'Grading record deleted.', 'martial-arts-club-manager' ),
					'noRecords'     => __( 'No grading history found for this member.', 'martial-arts-club-manager' ),
					'addGrading'    => __( 'Add Grading', 'martial-arts-club-manager' ),
					'editGrading'   => __( 'Edit Grading', 'martial-arts-club-manager' ),
				),
			)
		);
	}

	/**
	 * AJAX handler to get grading history for a member
	 */
	public function ajax_get_history() {
		check_ajax_referer( 'kcm-grading-nonce', 'nonce' );

		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'martial-arts-club-manager' ) ) );
		}

		$member_id = isset( $_POST['member_id'] ) ? absint( wp_unslash( $_POST['member_id'] ) ) : 0;

		if ( ! $member_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid member ID.', 'martial-arts-club-manager' ) ) );
		}

		$member = MACM_Member::get( $member_id );
		if ( ! $member ) {
			wp_send_json_error( array( 'message' => __( 'Member not found.', 'martial-arts-club-manager' ) ) );
		}

		$history = MACM_Grading_History::get_member_history( $member_id );

		// Format data for response.
		$records = array();
		foreach ( $history as $record ) {
			$examiner = '';
			if ( ! empty( $record->instructor_name ) ) {
				$examiner = $record->instructor_name;
			} elseif ( ! empty( $record->examiner_name ) ) {
				$examiner = $record->examiner_name;
			}

			$records[] = array(
				'id'                     => $record->id,
				'belt_color_key'         => $record->belt_color_key,
				'color_name'             => $record->color_name ?? $record->belt_color_key,
				'grading_date'           => $record->grading_date,
				'grading_date_formatted' => date_i18n( get_option( 'date_format' ), strtotime( $record->grading_date ) ),
				'examiner_id'            => $record->examiner_id,
				'examiner_name'          => $record->examiner_name,
				'examiner_display'       => $examiner,
				'score'                  => $record->score,
				'notes'                  => $record->notes,
			);
		}

		// Get belt colors and instructors for the form.
		$belt_colors = MACM_Belt_Color::get_all();
		$instructors = MACM_Instructor::get_all();

		wp_send_json_success(
			array(
				'member_id'   => $member_id,
				'member_name' => $member->full_name,
				'records'     => $records,
				'belt_colors' => $belt_colors,
				'instructors' => $instructors,
				'export_url'  => add_query_arg(
					array(
						'action'    => 'macm_export_grading_csv',
						'member_id' => $member_id,
						'_wpnonce'  => wp_create_nonce( 'macm_export_grading_csv' ),
					),
					admin_url( 'admin.php' )
				),
			)
		);
	}

	/**
	 * AJAX handler to save a grading record
	 */
	public function ajax_save_grading() {
		check_ajax_referer( 'kcm-grading-nonce', 'nonce' );

		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'martial-arts-club-manager' ) ) );
		}

		$record_id = isset( $_POST['record_id'] ) ? absint( wp_unslash( $_POST['record_id'] ) ) : 0;
		$member_id = isset( $_POST['member_id'] ) ? absint( wp_unslash( $_POST['member_id'] ) ) : 0;

		$data = array(
			'member_id'      => $member_id,
			'belt_color_key' => isset( $_POST['belt_color_key'] ) ? sanitize_text_field( wp_unslash( $_POST['belt_color_key'] ) ) : '',
			'grading_date'   => isset( $_POST['grading_date'] ) ? sanitize_text_field( wp_unslash( $_POST['grading_date'] ) ) : '',
			'examiner_id'    => isset( $_POST['examiner_id'] ) ? absint( wp_unslash( $_POST['examiner_id'] ) ) : 0,
			'examiner_name'  => isset( $_POST['examiner_name'] ) ? sanitize_text_field( wp_unslash( $_POST['examiner_name'] ) ) : '',
			'score'          => isset( $_POST['score'] ) ? sanitize_text_field( wp_unslash( $_POST['score'] ) ) : '',
			'notes'          => isset( $_POST['notes'] ) ? sanitize_textarea_field( wp_unslash( $_POST['notes'] ) ) : '',
		);

		if ( $record_id ) {
			// Update existing.
			$result = MACM_Grading_History::update( $record_id, $data );
		} else {
			// Create new.
			$result = MACM_Grading_History::create( $data );
		}

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success(
			array(
				'message'   => __( 'Grading record saved successfully.', 'martial-arts-club-manager' ),
				'record_id' => is_int( $result ) ? $result : $record_id,
			)
		);
	}

	/**
	 * AJAX handler to delete a grading record
	 */
	public function ajax_delete_grading() {
		check_ajax_referer( 'kcm-grading-nonce', 'nonce' );

		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'martial-arts-club-manager' ) ) );
		}

		$record_id = isset( $_POST['record_id'] ) ? absint( wp_unslash( $_POST['record_id'] ) ) : 0;

		if ( ! $record_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid record ID.', 'martial-arts-club-manager' ) ) );
		}

		$result = MACM_Grading_History::delete( $record_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( array( 'message' => __( 'Grading record deleted.', 'martial-arts-club-manager' ) ) );
	}

	/**
	 * Handle CSV export request
	 */
	public function handle_csv_export() {
		if ( ! isset( $_GET['action'] ) || 'macm_export_grading_csv' !== $_GET['action'] ) {
			return;
		}

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

		if ( ! current_user_can( 'manage_macm_members' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'martial-arts-club-manager' ) );
		}

		$member_id = isset( $_GET['member_id'] ) ? absint( wp_unslash( $_GET['member_id'] ) ) : 0;

		if ( ! $member_id ) {
			wp_die( esc_html__( 'Invalid member ID.', 'martial-arts-club-manager' ) );
		}

		$csv_data = MACM_Grading_History::export_csv( $member_id );

		if ( empty( $csv_data ) ) {
			wp_die( esc_html__( 'No data to export.', 'martial-arts-club-manager' ) );
		}

		// Set headers for CSV download.
		$filename = sanitize_file_name( 'grading-history-' . $csv_data['member_name'] . '-' . wp_date( 'Y-m-d' ) . '.csv' );

		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		$output = fopen( 'php://output', 'w' );

		// Add BOM for Excel UTF-8 compatibility.
		fprintf( $output, chr( 0xEF ) . chr( 0xBB ) . chr( 0xBF ) );

		// Add member info header.
		fputcsv( $output, array( __( 'Grading History for:', 'martial-arts-club-manager' ), $csv_data['member_name'] ) );
		fputcsv( $output, array( __( 'Export Date:', 'martial-arts-club-manager' ), date_i18n( get_option( 'date_format' ) ) ) );
		fputcsv( $output, array() ); // Empty row.

		// Add headers.
		fputcsv( $output, $csv_data['headers'] );

		// Add rows.
		foreach ( $csv_data['rows'] as $row ) {
			fputcsv( $output, $row );
		}

		exit;
	}

	/**
	 * Render the grading history modal HTML
	 *
	 * Called from admin member management page
	 */
	public static function render_modal() {
		?>
		<!-- Grading History Modal -->
		<div id="kcm-grading-modal" class="kcm-modal" style="display: none;">
			<div class="kcm-modal-content kcm-modal-large">
				<div class="kcm-modal-header">
					<h3 id="kcm-grading-modal-title"><?php esc_html_e( 'Belt Grading History', 'martial-arts-club-manager' ); ?></h3>
					<button type="button" class="kcm-modal-close">&times;</button>
				</div>
				<div class="kcm-modal-body" id="kcm-grading-content">
					<div class="kcm-loading"><?php esc_html_e( 'Loading...', 'martial-arts-club-manager' ); ?></div>
				</div>
				<div class="kcm-modal-footer">
					<button type="button" class="button" id="kcm-grading-export-btn" style="display: none;">
						<span class="dashicons dashicons-download" style="vertical-align: middle;"></span>
						<?php esc_html_e( 'Export CSV', 'martial-arts-club-manager' ); ?>
					</button>
					<button type="button" class="button button-primary" id="kcm-add-grading-btn" style="display: none;">
						<span class="dashicons dashicons-plus-alt" style="vertical-align: middle;"></span>
						<?php esc_html_e( 'Add Grading', 'martial-arts-club-manager' ); ?>
					</button>
				</div>
			</div>
		</div>

		<!-- Grading Form Modal -->
		<div id="kcm-grading-form-modal" class="kcm-modal" style="display: none;">
			<div class="kcm-modal-content">
				<div class="kcm-modal-header">
					<h3 id="kcm-grading-form-title"><?php esc_html_e( 'Add Grading Record', 'martial-arts-club-manager' ); ?></h3>
					<button type="button" class="kcm-modal-close">&times;</button>
				</div>
				<div class="kcm-modal-body">
					<form id="kcm-grading-form">
						<input type="hidden" id="grading-record-id" name="record_id" value="">
						<input type="hidden" id="grading-member-id" name="member_id" value="">

						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="grading-belt-color"><?php esc_html_e( 'Belt Color', 'martial-arts-club-manager' ); ?> <span class="required">*</span></label>
								</th>
								<td>
									<select id="grading-belt-color" name="belt_color_key" required>
										<option value=""><?php esc_html_e( 'Select belt color...', 'martial-arts-club-manager' ); ?></option>
									</select>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="grading-date"><?php esc_html_e( 'Grading Date', 'martial-arts-club-manager' ); ?> <span class="required">*</span></label>
								</th>
								<td>
									<input type="date" id="grading-date" name="grading_date" required max="<?php echo esc_attr( wp_date( 'Y-m-d' ) ); ?>">
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="grading-examiner"><?php esc_html_e( 'Examiner', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<select id="grading-examiner" name="examiner_id">
										<option value=""><?php esc_html_e( 'Select instructor...', 'martial-arts-club-manager' ); ?></option>
									</select>
									<p class="description"><?php esc_html_e( 'Or enter external examiner name below:', 'martial-arts-club-manager' ); ?></p>
									<input type="text" id="grading-examiner-name" name="examiner_name" placeholder="<?php esc_attr_e( 'External examiner name', 'martial-arts-club-manager' ); ?>">
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="grading-score"><?php esc_html_e( 'Score/Grade', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<input type="text" id="grading-score" name="score" maxlength="50" placeholder="<?php esc_attr_e( 'e.g., Pass, 85%, A', 'martial-arts-club-manager' ); ?>">
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="grading-notes"><?php esc_html_e( 'Notes', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<textarea id="grading-notes" name="notes" rows="3" placeholder="<?php esc_attr_e( 'Additional notes about this grading...', 'martial-arts-club-manager' ); ?>"></textarea>
								</td>
							</tr>
						</table>
					</form>
				</div>
				<div class="kcm-modal-footer">
					<button type="button" class="button kcm-grading-form-cancel"><?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?></button>
					<button type="button" class="button button-primary" id="kcm-save-grading-btn"><?php esc_html_e( 'Save Grading', 'martial-arts-club-manager' ); ?></button>
				</div>
			</div>
		</div>
		<?php
	}
}

// Initialize - PREMIUM feature.
// This block will be removed from the free version by Freemius.
if ( function_exists( 'macm_fs' ) && macm_fs()->is__premium_only() ) {
	if ( macm_fs()->can_use_premium_code() ) {
		new MACM_Admin_Grading_History();
	}
}
