<?php
/**
 * Admin Membership Types Management
 *
 * @package KarateClubManager
 */

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

/**
 * Class MACM_Admin_Membership_Types
 */
class MACM_Admin_Membership_Types {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ), 12 );
		add_action( 'admin_post_macm_save_membership_type', array( $this, 'handle_save' ) );
		add_action( 'admin_post_macm_delete_membership_type', array( $this, 'handle_delete' ) );
	}

	/**
	 * Add menu page
	 */
	public function add_menu_page() {
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'Membership Types', 'martial-arts-club-manager' ),
			__( 'Membership Types', 'martial-arts-club-manager' ),
			'manage_macm_settings',
			'kcm-membership-types',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Get edit membership type from request (with nonce verification).
	 *
	 * @return object|null Membership type object or null.
	 */
	private function get_edit_membership_type_from_request() {
		// Check for edit nonce in URL (added by edit links).
		if ( ! isset( $_GET['_wpnonce'] ) ) {
			return null;
		}

		$membership_type_id = isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0;
		if ( $membership_type_id <= 0 ) {
			return null;
		}

		// Verify nonce for edit action.
		$nonce = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) );
		if ( ! wp_verify_nonce( $nonce, 'macm_edit_membership_type_' . $membership_type_id ) ) {
			return null;
		}

		return MACM_Membership_Type::get( $membership_type_id );
	}

	/**
	 * Render membership types management page
	 */
	public function render_page() {
		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'martial-arts-club-manager' ) );
		}

		// Get all membership types.
		$membership_types = MACM_Membership_Type::get_all( false );

		// Check if we're editing (with nonce verification).
		$edit_membership_type = $this->get_edit_membership_type_from_request();

		?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?php esc_html_e( 'Membership Types', 'martial-arts-club-manager' ); ?></h1>
			<hr class="wp-header-end">

			<?php
			// Display messages from transient (set by save/delete handlers).
			$transient_key = 'macm_membership_type_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'] : '';

				switch ( $message ) {
					case 'created':
						echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Membership type created successfully.', 'martial-arts-club-manager' ) . '</p></div>';
						break;
					case 'updated':
						echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Membership type updated successfully.', 'martial-arts-club-manager' ) . '</p></div>';
						break;
					case 'deleted':
						echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Membership type deleted successfully.', 'martial-arts-club-manager' ) . '</p></div>';
						break;
					case 'error':
						echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $error ) . '</p></div>';
						break;
				}
			}
			?>

			<div class="kcm-membership-types-grid">
				<!-- Add/Edit Form -->
				<div class="kcm-form-wrapper">
					<h2><?php echo $edit_membership_type ? esc_html__( 'Edit Membership Type', 'martial-arts-club-manager' ) : esc_html__( 'Add New Membership Type', 'martial-arts-club-manager' ); ?></h2>

					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<?php wp_nonce_field( 'macm_save_membership_type', 'macm_membership_type_nonce' ); ?>
						<input type="hidden" name="action" value="macm_save_membership_type">
						<?php if ( $edit_membership_type ) : ?>
							<input type="hidden" name="membership_type_id" value="<?php echo esc_attr( $edit_membership_type->id ); ?>">
						<?php endif; ?>

						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="type_name"><?php esc_html_e( 'Type 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="type_name"
											name="type_name"
											class="regular-text"
											value="<?php echo $edit_membership_type ? esc_attr( $edit_membership_type->type_name ) : ''; ?>"
											required>
									<p class="description"><?php esc_html_e( 'Display name for this membership type (e.g., "Premium", "Basic", "Student").', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="description"><?php esc_html_e( 'Description', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<textarea id="description"
												name="description"
												class="large-text"
												rows="4"><?php echo $edit_membership_type ? esc_textarea( $edit_membership_type->description ?? '' ) : ''; ?></textarea>
									<p class="description"><?php esc_html_e( 'Optional description or notes about this membership type.', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="sort_order"><?php esc_html_e( 'Sort Order', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<input type="number"
											id="sort_order"
											name="sort_order"
											min="0"
											value="<?php echo $edit_membership_type ? esc_attr( $edit_membership_type->sort_order ) : '0'; ?>">
									<p class="description"><?php esc_html_e( 'Lower numbers appear first in the dropdown.', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="is_active"><?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<label>
										<input type="checkbox"
												id="is_active"
												name="is_active"
												value="1"
												<?php checked( $edit_membership_type ? $edit_membership_type->is_active : 1, 1 ); ?>>
										<?php esc_html_e( 'Active (appears in dropdowns)', 'martial-arts-club-manager' ); ?>
									</label>
								</td>
							</tr>
						</table>

						<p class="submit">
							<button type="submit" class="button button-primary">
								<?php echo $edit_membership_type ? esc_html__( 'Update Membership Type', 'martial-arts-club-manager' ) : esc_html__( 'Add Membership Type', 'martial-arts-club-manager' ); ?>
							</button>
							<?php if ( $edit_membership_type ) : ?>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-membership-types' ) ); ?>" class="button">
									<?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?>
								</a>
							<?php endif; ?>
						</p>
					</form>
				</div>

				<!-- Membership Types List -->
				<div class="kcm-table-wrapper">
					<h2><?php esc_html_e( 'Existing Membership Types', 'martial-arts-club-manager' ); ?></h2>

					<?php if ( $membership_types ) : ?>
						<table class="wp-list-table widefat fixed striped">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Type Name', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Description', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Sort Order', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Members Count', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Actions', 'martial-arts-club-manager' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $membership_types as $type ) : ?>
									<?php $member_count = MACM_Membership_Type::get_member_count( $type->id ); ?>
									<tr>
										<td><strong><?php echo esc_html( $type->type_name ); ?></strong></td>
										<td><?php echo $type->description ? esc_html( wp_trim_words( $type->description, 10 ) ) : '<span class="description">' . esc_html__( 'No description', 'martial-arts-club-manager' ) . '</span>'; ?></td>
										<td><?php echo esc_html( $type->sort_order ); ?></td>
										<td><?php echo esc_html( $member_count ); ?></td>
										<td>
											<?php if ( $type->is_active ) : ?>
												<span class="kcm-badge" style="background: #00a32a; color: #fff; padding: 3px 8px; border-radius: 3px; font-size: 11px;"><?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?></span>
											<?php else : ?>
												<span class="kcm-badge" style="background: #dba617; color: #fff; padding: 3px 8px; border-radius: 3px; font-size: 11px;"><?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-membership-types&action=edit&id=' . $type->id ),
												'macm_edit_membership_type_' . $type->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 === $member_count ) {
												$confirm_message   = esc_js( __( 'Are you sure you want to delete this membership type?', '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_membership_type&membership_type_id=' . $type->id ), 'macm_delete_membership_type_' . $type->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 ( $member_count > 0 ) {
												echo ' | <span class="description">' . esc_html__( 'Cannot delete (in use)', 'martial-arts-club-manager' ) . '</span>';
											}
											echo '</div>';
											?>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					<?php else : ?>
						<p><?php esc_html_e( 'No membership types found. Add your first membership type above.', 'martial-arts-club-manager' ); ?></p>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Handle save membership type
	 */
	public function handle_save() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'martial-arts-club-manager' ) );
		}

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

		$membership_type_id = isset( $_POST['membership_type_id'] ) ? absint( wp_unslash( $_POST['membership_type_id'] ) ) : 0;
		$data               = array(
			'type_name'   => isset( $_POST['type_name'] ) ? sanitize_text_field( wp_unslash( $_POST['type_name'] ) ) : '',
			'description' => isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '',
			'sort_order'  => isset( $_POST['sort_order'] ) ? absint( wp_unslash( $_POST['sort_order'] ) ) : 0,
			'is_active'   => isset( $_POST['is_active'] ) ? 1 : 0,
		);

		if ( $membership_type_id ) {
			// Update existing.
			$result  = MACM_Membership_Type::update( $membership_type_id, $data );
			$message = 'updated';
		} else {
			// Create new.
			$result  = MACM_Membership_Type::create( $data );
			$message = 'created';
		}

		// Store message in transient for display.
		$transient_key = 'macm_membership_type_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' => $message ),
				30
			);
		}

		wp_safe_redirect( admin_url( 'admin.php?page=kcm-membership-types' ) );
		exit;
	}

	/**
	 * Handle delete membership type
	 */
	public function handle_delete() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'martial-arts-club-manager' ) );
		}

		// Get membership type ID from GET parameter (link uses GET, not POST).
		$membership_type_id = isset( $_GET['membership_type_id'] ) ? absint( wp_unslash( $_GET['membership_type_id'] ) ) : 0;

		// Verify nonce (wp_nonce_url adds '_wpnonce' to GET parameters).
		$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_delete_membership_type_' . $membership_type_id ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		$result = MACM_Membership_Type::delete( $membership_type_id );

		// Store message in transient for display.
		$transient_key = 'macm_membership_type_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-membership-types' ) );
		exit;
	}
}

// Initialize.
new MACM_Admin_Membership_Types();
