<?php
/**
 * Admin Clubs Management
 *
 * Handles the clubs 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_Clubs
 *
 * Manages the clubs admin interface
 *
 * @since 1.0.2
 */
class MACM_Admin_Clubs {

	/**
	 * 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_club', array( $this, 'save_club' ) );
		add_action( 'admin_post_macm_delete_club', array( $this, 'delete_club' ) );
	}

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

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

		wp_enqueue_script(
			'kcm-admin-clubs',
			MACM_PLUGIN_URL . 'assets/js/admin-clubs.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).
		$clubs = MACM_Club::get_all( false );

		// Get message from transient (set by save/delete handlers).
		$message       = '';
		$error         = '';
		$transient_key = 'macm_club_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 club to edit (with nonce verification).
		$edit_club  = 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_club_' . $edit_id ) ) {
				$edit_club = MACM_Club::get( $edit_id );
			}
		}

		?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?php esc_html_e( 'Clubs', 'martial-arts-club-manager' ); ?></h1>
			<a href="#" class="page-title-action" id="kcm-add-club-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 clubs/dojos. Members can be assigned to a club for organizational purposes.', 'martial-arts-club-manager' ); ?>
			</p>

			<?php if ( 'saved' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Club saved successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php elseif ( 'deleted' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Club deleted successfully. All member associations have been removed.', '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-club-form" style="<?php echo $edit_club ? '' : 'display: none;'; ?>">
				<div class="card" style="max-width: 600px; margin: 20px 0;">
					<h2><?php echo $edit_club ? esc_html__( 'Edit Club', 'martial-arts-club-manager' ) : esc_html__( 'Add New Club', 'martial-arts-club-manager' ); ?></h2>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<?php wp_nonce_field( 'macm_save_club', 'macm_club_nonce' ); ?>
						<input type="hidden" name="action" value="macm_save_club">
						<?php if ( $edit_club ) : ?>
							<input type="hidden" name="club_id" value="<?php echo esc_attr( $edit_club->id ); ?>">
						<?php endif; ?>

						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="club_name"><?php esc_html_e( 'Club 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="club_name"
											name="name"
											class="regular-text"
											value="<?php echo $edit_club ? esc_attr( $edit_club->club_name ) : ''; ?>"
											required>
									<p class="description"><?php esc_html_e( 'Enter the club/dojo name', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="club_description"><?php esc_html_e( 'Description', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<textarea id="club_description"
												name="description"
												class="large-text"
												rows="3"><?php echo $edit_club ? esc_textarea( $edit_club->description ?? '' ) : ''; ?></textarea>
									<p class="description"><?php esc_html_e( 'Brief description of this club (optional)', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="club_is_active"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<label>
										<input type="checkbox"
												id="club_is_active"
												name="is_active"
												value="1"
												<?php checked( $edit_club ? $edit_club->is_active : 1, 1 ); ?>>
										<?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?>
									</label>
									<p class="description"><?php esc_html_e( 'Inactive clubs 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_club ? esc_attr__( 'Update Club', 'martial-arts-club-manager' ) : esc_attr__( 'Add Club', 'martial-arts-club-manager' ); ?>">
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-clubs' ) ); ?>" class="button"><?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?></a>
						</p>
					</form>
				</div>
			</div>

			<!-- Clubs List -->
			<table class="wp-list-table widefat fixed striped kcm-clubs-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Club 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( $clubs ) ) : ?>
						<?php foreach ( $clubs as $club ) : ?>
							<?php
							$member_count = MACM_Club::get_member_count( $club->id );
							?>
							<tr>
								<td>
									<strong><?php echo esc_html( $club->club_name ); ?></strong>
								</td>
								<td>
									<?php echo $club->description ? esc_html( $club->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 ( $club->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-clubs&edit=' . $club->id ),
										'macm_edit_club_' . $club->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 club? 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_club&club_id=' . $club->id ), 'macm_delete_club_' . $club->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 20px;">
								<p><?php esc_html_e( 'No clubs found.', 'martial-arts-club-manager' ); ?></p>
								<p><a href="#" id="kcm-add-club-btn-empty" class="button button-primary"><?php esc_html_e( 'Add Your First Club', 'martial-arts-club-manager' ); ?></a></p>
							</td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * Save club
	 *
	 * @since 1.0.2
	 */
	public function save_club() {
		// 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_club_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_club_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_club' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Get club data.
		$club_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,
		);

		// Update or create.
		if ( isset( $_POST['club_id'] ) && ! empty( $_POST['club_id'] ) ) {
			// Update existing club.
			$club_id = absint( wp_unslash( $_POST['club_id'] ) );
			$result  = MACM_Club::update( $club_id, $club_data );
		} else {
			// Create new club.
			$result = MACM_Club::create( $club_data );
		}

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

	/**
	 * Delete club
	 *
	 * @since 1.0.2
	 */
	public function delete_club() {
		// 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 from GET parameter (link uses GET, not POST).
		$club_id = isset( $_GET['club_id'] ) ? absint( wp_unslash( $_GET['club_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_club_' . $club_id ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		// Delete club.
		$result = MACM_Club::delete( $club_id );

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

// Initialize.
new MACM_Admin_Clubs();
