<?php
/**
 * Admin Page Access Control
 *
 * Manages page-level access control configuration
 *
 * @package KarateClubManager
 */

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

/**
 * Class MACM_Admin_Page_Access
 */
class MACM_Admin_Page_Access {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ), 20 );
		add_action( 'admin_post_macm_save_page_access', array( $this, 'handle_save' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
	}

	/**
	 * Add menu page
	 */
	public function add_menu_page() {
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'Page Access Control', 'martial-arts-club-manager' ),
			__( 'Page Access Control', 'martial-arts-club-manager' ),
			'manage_macm_settings',
			'kcm-page-access',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Enqueue scripts and styles
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Only load on our page access page.
		// Check if we're on the page access admin page.
		$screen = get_current_screen();
		if ( ! $screen || false === strpos( $screen->id, 'kcm-page-access' ) ) {
			return;
		}

		wp_enqueue_style( 'macm-page-access-admin', plugins_url( 'assets/css/admin-page-access.css', dirname( __DIR__ ) ), array(), MACM_VERSION );
		wp_enqueue_script( 'macm-page-access-admin', plugins_url( 'assets/js/admin-page-access.js', dirname( __DIR__ ) ), array( 'jquery' ), MACM_VERSION, true );

		// Localize script.
		wp_localize_script(
			'macm-page-access-admin',
			'macmPageAccess',
			array(
				'users'           => $this->get_users_for_select(),
				'membershipTypes' => $this->get_membership_types_for_select(),
				'groups'          => $this->get_groups_for_select(),
				'ruleTypeLabels'  => array(
					'user'            => __( 'User', 'martial-arts-club-manager' ),
					'membership_type' => __( 'Membership Type', 'martial-arts-club-manager' ),
					'group'           => __( 'Group', 'martial-arts-club-manager' ),
				),
			)
		);
	}

	/**
	 * Render page access control 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 WordPress pages.
		$pages = get_pages(
			array(
				'sort_column' => 'post_title',
				'sort_order'  => 'ASC',
			)
		);

		// Get all protected pages.
		$protected_pages    = MACM_Page_Access::get_all_protected_pages();
		$protected_page_ids = array();
		foreach ( $protected_pages as $protected ) {
			$protected_page_ids[] = $protected->page_id;
		}

		?>
		<div class="wrap kcm-page-access-wrap">
			<h1 class="wp-heading-inline"><?php esc_html_e( 'Page Access Control', 'martial-arts-club-manager' ); ?></h1>
			<hr class="wp-header-end">

			<?php
			// Display messages from transient (set by save handler).
			$transient_key = 'macm_page_access_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'] : __( 'An error occurred.', 'martial-arts-club-manager' );

				switch ( $message ) {
					case 'saved':
						echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Page access settings saved 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-page-access-info">
				<p><?php esc_html_e( 'Control which pages require login or specific permissions to view. Select pages below and configure their access rules.', 'martial-arts-club-manager' ); ?></p>
				<p class="description">
					<?php esc_html_e( 'Access types:', 'martial-arts-club-manager' ); ?><br>
					<strong><?php esc_html_e( 'Login Required:', 'martial-arts-club-manager' ); ?></strong> <?php esc_html_e( 'Any logged-in user can view the page.', 'martial-arts-club-manager' ); ?><br>
					<strong><?php esc_html_e( 'Custom Rules:', 'martial-arts-club-manager' ); ?></strong> <?php esc_html_e( 'Only users matching at least one rule can view the page (OR logic).', 'martial-arts-club-manager' ); ?>
				</p>
			</div>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="kcm-page-access-form">
				<?php wp_nonce_field( 'macm_save_page_access', 'macm_page_access_nonce' ); ?>
				<input type="hidden" name="action" value="macm_save_page_access">

				<div class="kcm-page-access-container">
					<!-- Pages List -->
					<div class="kcm-pages-list">
						<h2><?php esc_html_e( 'Pages', 'martial-arts-club-manager' ); ?></h2>
						<div class="kcm-pages-list-inner">
							<?php if ( empty( $pages ) ) : ?>
								<p class="kcm-no-pages"><?php esc_html_e( 'No pages found.', 'martial-arts-club-manager' ); ?></p>
							<?php else : ?>
								<?php foreach ( $pages as $page ) : ?>
									<?php
									$is_protected = in_array( $page->ID, $protected_page_ids, true );
									$page_access  = MACM_Page_Access::get_page_access( $page->ID );
									$access_type  = $page_access ? $page_access->access_type : 'login_required';
									$rules        = $page_access ? MACM_Page_Access::get_page_rules( $page->ID ) : array();

									// Determine status text - check if page has access configuration.
									// Use direct page_access check instead of relying on protected_page_ids array.
									$status_text  = '';
									$status_class = '';
									if ( $page_access ) {
										// Page has access control configured.
										if ( 'custom' === $access_type ) {
											$status_text  = __( 'Custom Rules', 'martial-arts-club-manager' );
											$status_class = 'kcm-status-custom';
										} else {
											$status_text  = __( 'Login Required', 'martial-arts-club-manager' );
											$status_class = 'kcm-status-login';
										}
										// Also ensure is_protected is true.
										$is_protected = true;
									}
									?>
									<div class="kcm-page-item <?php echo $is_protected ? 'is-protected' : ''; ?>" data-page-id="<?php echo esc_attr( $page->ID ); ?>" data-access-type="<?php echo esc_attr( $access_type ); ?>">
										<label class="kcm-page-checkbox">
											<input type="checkbox"
													name="protected_pages[]"
													value="<?php echo esc_attr( $page->ID ); ?>"
													class="kcm-page-toggle"
													<?php checked( $is_protected ); ?>>
											<span class="kcm-page-title"><?php echo esc_html( $page->post_title ); ?></span>
											<span class="kcm-page-status <?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_text ); ?></span>
										</label>
									</div>
								<?php endforeach; ?>
							<?php endif; ?>
						</div>
					</div>

					<!-- Page Configuration -->
					<div class="kcm-page-config">
						<div class="kcm-no-page-selected">
							<p><?php esc_html_e( 'Select a protected page from the list to configure its access rules.', 'martial-arts-club-manager' ); ?></p>
						</div>

						<?php foreach ( $pages as $page ) : ?>
							<?php
							$is_protected = in_array( $page->ID, $protected_page_ids, true );
							$page_access  = MACM_Page_Access::get_page_access( $page->ID );
							$access_type  = $page_access ? $page_access->access_type : 'login_required';
							$rules        = $page_access ? MACM_Page_Access::get_page_rules( $page->ID ) : array();
							?>
							<div class="kcm-page-config-panel" data-page-id="<?php echo esc_attr( $page->ID ); ?>" style="display: none;">
								<h2>
									<?php
									printf(
										/* translators: %s: Page title */
										esc_html__( 'Access Rules for: %s', 'martial-arts-club-manager' ),
										esc_html( $page->post_title )
									);
									?>
								</h2>

								<table class="form-table">
									<tr>
										<th scope="row">
											<label for="access_type_<?php echo esc_attr( $page->ID ); ?>">
												<?php esc_html_e( 'Access Type', 'martial-arts-club-manager' ); ?>
											</label>
										</th>
										<td>
											<select name="access_type[<?php echo esc_attr( $page->ID ); ?>]"
													id="access_type_<?php echo esc_attr( $page->ID ); ?>"
													class="kcm-access-type-select">
												<option value="login_required" <?php selected( $access_type, 'login_required' ); ?>>
													<?php esc_html_e( 'Login Required', 'martial-arts-club-manager' ); ?>
												</option>
												<option value="custom" <?php selected( $access_type, 'custom' ); ?>>
													<?php esc_html_e( 'Custom Rules', 'martial-arts-club-manager' ); ?>
												</option>
											</select>
											<p class="description">
												<?php esc_html_e( 'Choose whether any logged-in user can access or only those matching custom rules.', 'martial-arts-club-manager' ); ?>
											</p>
										</td>
									</tr>
								</table>

								<div class="kcm-custom-rules" style="<?php echo 'custom' === $access_type ? '' : 'display: none;'; ?>">
									<h3><?php esc_html_e( 'Custom Access Rules', 'martial-arts-club-manager' ); ?></h3>
									<p class="description">
										<?php esc_html_e( 'Add one or more rules. Users matching ANY rule will be granted access (OR logic).', 'martial-arts-club-manager' ); ?>
									</p>

									<div class="kcm-rules-container" data-page-id="<?php echo esc_attr( $page->ID ); ?>">
										<?php if ( ! empty( $rules ) ) : ?>
											<?php foreach ( $rules as $index => $rule ) : ?>
												<div class="kcm-rule-item">
													<div class="kcm-rule-fields">
														<select name="rule_type[<?php echo esc_attr( $page->ID ); ?>][]" class="kcm-rule-type">
															<option value="user" <?php selected( $rule->rule_type, 'user' ); ?>>
																<?php esc_html_e( 'User', 'martial-arts-club-manager' ); ?>
															</option>
															<option value="membership_type" <?php selected( $rule->rule_type, 'membership_type' ); ?>>
																<?php esc_html_e( 'Membership Type', 'martial-arts-club-manager' ); ?>
															</option>
															<option value="group" <?php selected( $rule->rule_type, 'group' ); ?>>
																<?php esc_html_e( 'Group', 'martial-arts-club-manager' ); ?>
															</option>
														</select>

														<select name="rule_value[<?php echo esc_attr( $page->ID ); ?>][]" class="kcm-rule-value">
															<?php $this->render_rule_value_options( $rule->rule_type, $rule->rule_value ); ?>
														</select>

														<button type="button" class="button kcm-remove-rule">
															<?php esc_html_e( 'Remove', 'martial-arts-club-manager' ); ?>
														</button>
													</div>
													<?php if ( $index < count( $rules ) - 1 ) : ?>
														<div class="kcm-rule-separator"><?php esc_html_e( 'OR', 'martial-arts-club-manager' ); ?></div>
													<?php endif; ?>
												</div>
											<?php endforeach; ?>
										<?php else : ?>
											<div class="kcm-rule-item">
												<div class="kcm-rule-fields">
													<select name="rule_type[<?php echo esc_attr( $page->ID ); ?>][]" class="kcm-rule-type">
														<option value="user"><?php esc_html_e( 'User', 'martial-arts-club-manager' ); ?></option>
														<option value="membership_type"><?php esc_html_e( 'Membership Type', 'martial-arts-club-manager' ); ?></option>
														<option value="group"><?php esc_html_e( 'Group', 'martial-arts-club-manager' ); ?></option>
													</select>

													<select name="rule_value[<?php echo esc_attr( $page->ID ); ?>][]" class="kcm-rule-value">
														<?php $this->render_rule_value_options( 'user', 0 ); ?>
													</select>

													<button type="button" class="button kcm-remove-rule">
														<?php esc_html_e( 'Remove', 'martial-arts-club-manager' ); ?>
													</button>
												</div>
											</div>
										<?php endif; ?>
									</div>

									<button type="button" class="button kcm-add-rule" data-page-id="<?php echo esc_attr( $page->ID ); ?>">
										<?php esc_html_e( 'Add Rule', 'martial-arts-club-manager' ); ?>
									</button>
								</div>
							</div>
						<?php endforeach; ?>
					</div>
				</div>

				<div class="kcm-unsaved-notice" style="display: none;">
					<?php esc_html_e( 'You have unsaved changes. Click "Save Access Settings" to apply them.', 'martial-arts-club-manager' ); ?>
				</div>

				<p class="submit">
					<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php esc_attr_e( 'Save Access Settings', 'martial-arts-club-manager' ); ?>">
				</p>
			</form>
		</div>
		<?php
	}

	/**
	 * Render rule value options based on rule type
	 *
	 * @param string $rule_type     Rule type: 'user', 'membership_type', or 'group'.
	 * @param int    $selected_value Selected value ID.
	 */
	private function render_rule_value_options( $rule_type, $selected_value = 0 ) {
		switch ( $rule_type ) {
			case 'user':
				$users = $this->get_users_for_select();
				foreach ( $users as $user_id => $user_name ) {
					printf(
						'<option value="%d" %s>%s</option>',
						esc_attr( $user_id ),
						selected( $selected_value, $user_id, false ),
						esc_html( $user_name )
					);
				}
				break;

			case 'membership_type':
				$types = $this->get_membership_types_for_select();
				foreach ( $types as $type_id => $type_name ) {
					printf(
						'<option value="%d" %s>%s</option>',
						esc_attr( $type_id ),
						selected( $selected_value, $type_id, false ),
						esc_html( $type_name )
					);
				}
				break;

			case 'group':
				$groups = $this->get_groups_for_select();
				foreach ( $groups as $group_id => $group_name ) {
					printf(
						'<option value="%d" %s>%s</option>',
						esc_attr( $group_id ),
						selected( $selected_value, $group_id, false ),
						esc_html( $group_name )
					);
				}
				break;
		}
	}

	/**
	 * Handle form submission
	 */
	public function handle_save() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to perform this action.', 'martial-arts-club-manager' ) );
		}

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

		// Get protected pages from form.
		$protected_pages = isset( $_POST['protected_pages'] ) ? array_map( 'absint', wp_unslash( $_POST['protected_pages'] ) ) : array();
		$access_types    = isset( $_POST['access_type'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['access_type'] ) ) : array();

		// Handle nested array structure for rule_type and rule_value.
		// Use map_deep for nested array sanitization.
		$rule_types = array();
		if ( isset( $_POST['rule_type'] ) && is_array( $_POST['rule_type'] ) ) {
			$sanitized_rule_types = map_deep( wp_unslash( $_POST['rule_type'] ), 'sanitize_text_field' );
			foreach ( $sanitized_rule_types as $page_id => $types ) {
				if ( is_array( $types ) ) {
					$rule_types[ absint( $page_id ) ] = $types;
				}
			}
		}

		$rule_values = array();
		if ( isset( $_POST['rule_value'] ) && is_array( $_POST['rule_value'] ) ) {
			$sanitized_rule_values = map_deep( wp_unslash( $_POST['rule_value'] ), 'sanitize_text_field' );
			foreach ( $sanitized_rule_values as $page_id => $values ) {
				if ( is_array( $values ) ) {
					$rule_values[ absint( $page_id ) ] = $values;
				}
			}
		}

		// Get all WordPress pages.
		$all_pages = get_pages();

		// Process each page.
		foreach ( $all_pages as $page ) {
			$page_id = $page->ID;

			// Check if page should be protected.
			if ( in_array( $page_id, $protected_pages, true ) ) {
				// Get access type for this page.
				$access_type = isset( $access_types[ $page_id ] ) ? sanitize_text_field( $access_types[ $page_id ] ) : 'login_required';

				// Get rules for this page.
				$rules = array();
				if ( 'custom' === $access_type && isset( $rule_types[ $page_id ] ) && isset( $rule_values[ $page_id ] ) ) {
					$page_rule_types  = $rule_types[ $page_id ];
					$page_rule_values = $rule_values[ $page_id ];

					// Ensure we have arrays before counting.
					if ( is_array( $page_rule_types ) && is_array( $page_rule_values ) ) {
						$rule_count = count( $page_rule_types );
						for ( $i = 0; $i < $rule_count; $i++ ) {
							if ( isset( $page_rule_types[ $i ] ) && isset( $page_rule_values[ $i ] ) ) {
								$rules[] = array(
									'type'  => sanitize_text_field( $page_rule_types[ $i ] ),
									'value' => absint( $page_rule_values[ $i ] ),
								);
							}
						}
					}
				}

				// Save page access.
				$result = MACM_Page_Access::save_page_access( $page_id, $access_type, $rules );

				if ( is_wp_error( $result ) ) {
					// Store error message in transient.
					$transient_key = 'macm_page_access_message_' . get_current_user_id();
					set_transient(
						$transient_key,
						array(
							'type'  => 'error',
							'error' => $result->get_error_message(),
						),
						30
					);
					wp_safe_redirect( admin_url( 'admin.php?page=kcm-page-access' ) );
					exit;
				}
			} else {
				// Page should not be protected - delete access if exists.
				MACM_Page_Access::delete_page_access( $page_id );
			}
		}

		// Store success message in transient.
		$transient_key = 'macm_page_access_message_' . get_current_user_id();
		set_transient(
			$transient_key,
			array( 'type' => 'saved' ),
			30
		);

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

	/**
	 * Get users for select dropdown
	 *
	 * @return array Array of user_id => user_name.
	 */
	private function get_users_for_select() {
		$users = get_users(
			array(
				'orderby' => 'display_name',
				'order'   => 'ASC',
			)
		);

		$result = array();
		foreach ( $users as $user ) {
			$result[ $user->ID ] = $user->display_name . ' (' . $user->user_email . ')';
		}

		return $result;
	}

	/**
	 * Get membership types for select dropdown
	 *
	 * @return array Array of type_id => type_name.
	 */
	private function get_membership_types_for_select() {
		return MACM_Membership_Type::get_types_for_select( false );
	}

	/**
	 * Get groups for select dropdown
	 *
	 * @return array Array of group_id => group_name.
	 */
	private function get_groups_for_select() {
		$groups = MACM_Group::get_all( false );
		$result = array();

		foreach ( $groups as $group ) {
			$result[ $group->id ] = $group->group_name;
		}

		return $result;
	}
}

// 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_Page_Access();
	}
}
