<?php
/**
 * Admin Groups Management
 *
 * Handles the groups management admin page
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.0
 */

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

/**
 * Class MACM_Admin_Groups
 *
 * Manages the groups admin interface
 *
 * @since 1.0.0
 */
class MACM_Admin_Groups {

	/**
	 * Constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ), 14 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_post_macm_save_group', array( $this, 'save_group' ) );
		add_action( 'admin_post_macm_delete_group', array( $this, 'delete_group' ) );
	}

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

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

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

	/**
	 * Render the groups page
	 *
	 * @since 1.0.0
	 */
	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 groups (including inactive).
		$groups = MACM_Group::get_all( false );

		// Get message from transient (set by save/delete handlers).
		$message       = '';
		$error         = '';
		$transient_key = 'macm_group_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 group to edit (with nonce verification).
		$edit_group = null;
		$edit_nonce = filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$edit_input = filter_input( INPUT_GET, 'edit', FILTER_SANITIZE_NUMBER_INT );
		if ( $edit_nonce && $edit_input ) {
			$edit_id = absint( $edit_input );
			if ( $edit_id > 0 && wp_verify_nonce( $edit_nonce, 'macm_edit_group_' . $edit_id ) ) {
				$edit_group = MACM_Group::get( $edit_id );
			}
		}

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

			<p class="description">
				<?php esc_html_e( 'Groups help organize members by age, skill level, or other criteria (e.g., "Kids 5-8", "Teens", "Adults Beginner").', 'martial-arts-club-manager' ); ?>
			</p>

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

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

			<!-- Add/Edit Form -->
			<div id="kcm-group-form" style="<?php echo $edit_group ? '' : 'display: none;'; ?>">
				<div class="card" style="max-width: 600px; margin: 20px 0;">
					<h2><?php echo $edit_group ? esc_html__( 'Edit Group', 'martial-arts-club-manager' ) : esc_html__( 'Add New Group', 'martial-arts-club-manager' ); ?></h2>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<?php wp_nonce_field( 'macm_save_group', 'macm_group_nonce' ); ?>
						<input type="hidden" name="action" value="macm_save_group">
						<?php if ( $edit_group ) : ?>
							<input type="hidden" name="group_id" value="<?php echo esc_attr( $edit_group->id ); ?>">
						<?php endif; ?>

						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="group_name"><?php esc_html_e( 'Group 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="group_name"
											name="name"
											class="regular-text"
											value="<?php echo $edit_group ? esc_attr( $edit_group->group_name ) : ''; ?>"
											required>
									<p class="description"><?php esc_html_e( 'Enter the group name (e.g., "Kids 5-8 Years", "Teen Intermediate")', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="group_description"><?php esc_html_e( 'Description', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<textarea id="group_description"
												name="description"
												class="large-text"
												rows="3"><?php echo $edit_group ? esc_textarea( $edit_group->description ?? '' ) : ''; ?></textarea>
									<p class="description"><?php esc_html_e( 'Brief description of this group (optional)', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="group_is_active"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<label>
										<input type="checkbox"
												id="group_is_active"
												name="is_active"
												value="1"
												<?php checked( $edit_group ? $edit_group->is_active : 1, 1 ); ?>>
										<?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?>
									</label>
									<p class="description"><?php esc_html_e( 'Inactive groups won\'t be available for member assignment', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
						</table>

						<p class="submit">
							<input type="submit" class="button button-primary" value="<?php echo $edit_group ? esc_attr__( 'Update Group', 'martial-arts-club-manager' ) : esc_attr__( 'Add Group', 'martial-arts-club-manager' ); ?>">
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-groups' ) ); ?>" class="button"><?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?></a>
						</p>
					</form>
				</div>
			</div>

			<!-- Groups List -->
			<table class="wp-list-table widefat fixed striped kcm-groups-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Group Name', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Description', 'martial-arts-club-manager' ); ?></th>
						<th scope="col" class="num"><?php esc_html_e( 'Members', '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( $groups ) ) : ?>
						<?php foreach ( $groups as $group ) : ?>
							<?php
							$member_count = MACM_Group::get_member_count( $group->id );
							?>
							<tr>
								<td>
									<strong><?php echo esc_html( $group->group_name ); ?></strong>
								</td>
								<td>
									<?php echo $group->description ? esc_html( $group->description ) : '<span class="description">' . esc_html__( 'No description', 'martial-arts-club-manager' ) . '</span>'; ?>
								</td>
								<td class="num">
									<?php echo esc_html( $member_count ); ?>
								</td>
								<td>
									<?php if ( $group->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-groups&edit=' . $group->id ),
										'macm_edit_group_' . $group->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 group?', '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_group&group_id=' . $group->id ), 'macm_delete_group_' . $group->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__( 'In use', 'martial-arts-club-manager' ) . '</span>';
									}
									echo '</div>';
									?>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php else : ?>
						<tr>
							<td colspan="5" style="text-align: center; padding: 40px;">
								<p><?php esc_html_e( 'No groups found.', 'martial-arts-club-manager' ); ?></p>
								<p><a href="#" class="button button-primary" id="kcm-add-first-group"><?php esc_html_e( 'Add Your First Group', 'martial-arts-club-manager' ); ?></a></p>
							</td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * Save group
	 *
	 * @since 1.0.0
	 */
	public function save_group() {
		// Verify nonce.
		check_admin_referer( 'macm_save_group', 'macm_group_nonce' );

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

		// Get and sanitize data.
		$group_id = isset( $_POST['group_id'] ) ? absint( wp_unslash( $_POST['group_id'] ) ) : 0;
		$data     = array(
			'name'        => isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '',
			'description' => isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '',
			'is_active'   => isset( $_POST['is_active'] ) ? 1 : 0,
		);

		// Save or update.
		if ( $group_id ) {
			$result = MACM_Group::update( $group_id, $data );
		} else {
			$result = MACM_Group::create( $data );
		}

		// Store message in transient.
		$transient_key = 'macm_group_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-groups' ) );
		exit;
	}

	/**
	 * Delete group
	 *
	 * @since 1.0.0
	 */
	public function delete_group() {
		// Get group ID.
		$group_id = isset( $_GET['group_id'] ) ? absint( wp_unslash( $_GET['group_id'] ) ) : 0;

		// Verify nonce.
		check_admin_referer( 'macm_delete_group_' . $group_id );

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

		// Delete group.
		$result = MACM_Group::delete( $group_id );

		// Store message in transient.
		$transient_key = 'macm_group_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-groups' ) );
		exit;
	}
}

// Initialize.
new MACM_Admin_Groups();
