<?php
/**
 * Admin Belt Colors Management
 *
 * @package KarateClubManager
 */

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

/**
 * Class MACM_Admin_Belt_Colors
 */
class MACM_Admin_Belt_Colors {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ), 11 );
		add_action( 'admin_post_macm_save_belt_color', array( $this, 'handle_save' ) );
		add_action( 'admin_post_macm_delete_belt_color', array( $this, 'handle_delete' ) );
	}

	/**
	 * Add menu page
	 */
	public function add_menu_page() {
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'Belt Colors', 'martial-arts-club-manager' ),
			__( 'Belt Colors', 'martial-arts-club-manager' ),
			'manage_macm_settings',
			'kcm-belt-colors',
			array( $this, 'render_page' )
		);
	}

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

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

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

		return MACM_Belt_Color::get( $belt_color_id );
	}

	/**
	 * Render belt colors 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 belt colors.
		$belt_colors = MACM_Belt_Color::get_all( false );

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

		// Get message from transient (set by save/delete handlers).
		$message       = '';
		$error         = '';
		$transient_key = 'macm_belt_color_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'] : '';
		}

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

			<?php
			switch ( $message ) {
				case 'created':
					echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Belt color created successfully.', 'martial-arts-club-manager' ) . '</p></div>';
					break;
				case 'updated':
					echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Belt color updated successfully.', 'martial-arts-club-manager' ) . '</p></div>';
					break;
				case 'deleted':
					echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Belt color 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-belt-colors-grid">
				<!-- Add/Edit Form -->
				<div class="kcm-form-wrapper">
					<h2><?php echo $edit_belt_color ? esc_html__( 'Edit Belt Color', 'martial-arts-club-manager' ) : esc_html__( 'Add New Belt Color', 'martial-arts-club-manager' ); ?></h2>

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

						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="color_key"><?php esc_html_e( 'Color Key', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
								</th>
								<td>
									<input type="text"
											id="color_key"
											name="color_key"
											class="regular-text"
											value="<?php echo $edit_belt_color ? esc_attr( $edit_belt_color->color_key ) : ''; ?>"
											required
											pattern="[a-z0-9_-]+"
											<?php echo $edit_belt_color ? 'readonly' : ''; ?>>
									<p class="description"><?php esc_html_e( 'Lowercase letters, numbers, underscores and hyphens only (e.g., "blue", "black_stripe"). Cannot be changed after creation.', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="color_name"><?php esc_html_e( 'Color 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="color_name"
											name="color_name"
											class="regular-text"
											value="<?php echo $edit_belt_color ? esc_attr( $edit_belt_color->color_name ) : ''; ?>"
											required>
									<p class="description"><?php esc_html_e( 'Display name for this belt color (e.g., "Blue", "Black (1st Degree)").', '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_belt_color ? esc_attr( $edit_belt_color->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_belt_color ? $edit_belt_color->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_belt_color ? esc_html__( 'Update Belt Color', 'martial-arts-club-manager' ) : esc_html__( 'Add Belt Color', 'martial-arts-club-manager' ); ?>
							</button>
							<?php if ( $edit_belt_color ) : ?>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-belt-colors' ) ); ?>" class="button">
									<?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?>
								</a>
							<?php endif; ?>
						</p>
					</form>
				</div>

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

					<?php if ( $belt_colors ) : ?>
						<table class="wp-list-table widefat fixed striped">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Color Key', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Color Name', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Sort Order', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Members', 'martial-arts-club-manager' ); ?></th>
									<th><?php esc_html_e( 'Actions', 'martial-arts-club-manager' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $belt_colors as $color ) : ?>
									<?php
									global $wpdb;
									$member_cache_key = 'macm_belt_member_count_' . $color->color_key;
									$member_count     = wp_cache_get( $member_cache_key, 'macm' );

									if ( false === $member_count ) {
										$member_count = (int) $wpdb->get_var(
											$wpdb->prepare(
												"SELECT COUNT(*) FROM {$wpdb->prefix}macm_members WHERE belt_color = %s AND status = 'active'",
												$color->color_key
											)
										);
										wp_cache_set( $member_cache_key, $member_count, 'macm', 300 );
									}
									?>
									<tr>
										<td><code><?php echo esc_html( $color->color_key ); ?></code></td>
										<td><strong><?php echo esc_html( $color->color_name ); ?></strong></td>
										<td><?php echo esc_html( $color->sort_order ); ?></td>
										<td>
											<?php if ( $color->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 echo esc_html( $member_count ); ?></td>
										<td>
											<?php
											$actions = array();

											// Edit action (with nonce for security).
											$edit_url        = wp_nonce_url(
												admin_url( 'admin.php?page=kcm-belt-colors&action=edit&id=' . $color->id ),
												'macm_edit_belt_color_' . $color->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 belt color?', '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_belt_color&belt_color_id=' . $color->id ), 'macm_delete_belt_color_' . $color->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 belt colors found. Add your first belt color above.', 'martial-arts-club-manager' ); ?></p>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<?php
		// Enqueue inline styles for belt colors page using WordPress-compliant method.
		$belt_colors_styles = '
.kcm-belt-colors-grid {
	display: grid;
	grid-template-columns: 1fr 2fr;
	gap: 20px;
	margin-top: 20px;
}
.kcm-form-wrapper,
.kcm-table-wrapper {
	background: #fff;
	padding: 20px;
	box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.kcm-belt-colors-grid .row-actions {
	position: static !important;
	visibility: visible !important;
	opacity: 1 !important;
}
@media (max-width: 1280px) {
	.kcm-belt-colors-grid {
		grid-template-columns: 1fr;
		gap: 15px;
	}
	.kcm-table-wrapper table {
		width: 100%;
	}
}
@media (max-width: 782px) {
	.kcm-form-wrapper,
	.kcm-table-wrapper {
		padding: 15px;
	}
	.kcm-form-wrapper .form-table th,
	.kcm-form-wrapper .form-table td {
		display: block;
		width: 100%;
		padding: 10px 0;
	}
	.kcm-form-wrapper .form-table th {
		border-bottom: none;
		padding-bottom: 5px;
	}
	.kcm-form-wrapper .form-table td {
		padding-top: 0;
		padding-bottom: 15px;
	}
	.kcm-form-wrapper .form-table input[type="text"],
	.kcm-form-wrapper .form-table input[type="number"] {
		width: 100%;
		max-width: 100%;
	}
	.kcm-table-wrapper {
		overflow-x: auto;
	}
	.kcm-table-wrapper table {
		min-width: 600px;
	}
	.kcm-table-wrapper table td,
	.kcm-table-wrapper table th {
		font-size: 13px;
		padding: 8px 6px;
	}
	.kcm-table-wrapper .row-actions {
		font-size: 12px;
	}
	.kcm-badge {
		font-size: 10px !important;
		padding: 2px 6px !important;
	}
}
@media (max-width: 480px) {
	.kcm-form-wrapper h2,
	.kcm-table-wrapper h2 {
		font-size: 18px;
	}
	.kcm-form-wrapper,
	.kcm-table-wrapper {
		padding: 12px;
	}
	.kcm-table-wrapper table {
		font-size: 12px;
	}
}
';
		wp_add_inline_style( 'kcm-admin-styles', $belt_colors_styles );
		?>
		<?php
	}

	/**
	 * Handle save belt color
	 */
	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_belt_color_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_belt_color_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_belt_color' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		$belt_color_id = isset( $_POST['belt_color_id'] ) ? absint( wp_unslash( $_POST['belt_color_id'] ) ) : 0;
		$data          = array(
			'color_key'  => isset( $_POST['color_key'] ) ? sanitize_key( wp_unslash( $_POST['color_key'] ) ) : '',
			'color_name' => isset( $_POST['color_name'] ) ? sanitize_text_field( wp_unslash( $_POST['color_name'] ) ) : '',
			'sort_order' => isset( $_POST['sort_order'] ) ? absint( wp_unslash( $_POST['sort_order'] ) ) : 0,
			'is_active'  => isset( $_POST['is_active'] ) ? 1 : 0,
		);

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

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

	/**
	 * Handle delete belt color
	 */
	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 belt color ID from GET parameter (link uses GET, not POST).
		$belt_color_id = isset( $_GET['belt_color_id'] ) ? absint( wp_unslash( $_GET['belt_color_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_belt_color_' . $belt_color_id ) ) {
			wp_die( esc_html__( 'Security check failed.', 'martial-arts-club-manager' ) );
		}

		$result = MACM_Belt_Color::delete( $belt_color_id );

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

// Initialize.
new MACM_Admin_Belt_Colors();
