<?php
/**
 * Admin Polish Class
 *
 * Handles admin interface enhancements like action links, notices, and help tabs.
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.0
 */

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

/**
 * KCM Admin Polish Class
 *
 * Enhances the admin interface with helpful features.
 *
 * @since 1.0.0
 */
class MACM_Admin_Polish {

	/**
	 * Initialize the class and set up hooks.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		// Plugin action links.
		add_filter( 'plugin_action_links_martial-arts-club-manager/martial-arts-club-manager.php', array( $this, 'add_action_links' ) );

		// Admin notices.
		add_action( 'admin_notices', array( $this, 'display_admin_notices' ) );

		// Help tabs.
		add_action( 'admin_head', array( $this, 'add_help_tabs' ) );

		// Review notice AJAX dismissal.
		add_action( 'wp_ajax_macm_dismiss_review_notice', array( $this, 'ajax_dismiss_review_notice' ) );
	}

	/**
	 * Add action links to plugins page.
	 *
	 * @since 1.0.0
	 * @param array $links Existing plugin action links.
	 * @return array Modified plugin action links.
	 */
	public function add_action_links( $links ) {
		$plugin_links = array(
			'<a href="' . esc_url( admin_url( 'admin.php?page=kcm-settings' ) ) . '">' . esc_html__( 'Settings', 'martial-arts-club-manager' ) . '</a>',
			'<a href="' . esc_url( admin_url( 'admin.php?page=martial-arts-club-manager' ) ) . '">' . esc_html__( 'Dashboard', 'martial-arts-club-manager' ) . '</a>',
		);

		return array_merge( $plugin_links, $links );
	}

	/**
	 * Display admin notices.
	 *
	 * @since 1.0.0
	 */
	public function display_admin_notices() {
		// Run database migrations.
		require_once MACM_PLUGIN_DIR . 'includes/database/class-macm-database-migration.php';
		MACM_Database_Migration::run_migrations();

		// Check database tables and create if missing.
		if ( ! MACM_Database::tables_exist() ) {
			// Auto-fix: Create missing tables.
			MACM_Database::create_tables();
			?>
			<div class="notice notice-success is-dismissible">
				<p>
					<strong><?php esc_html_e( 'Martial Arts Club Manager:', 'martial-arts-club-manager' ); ?></strong>
					<?php esc_html_e( 'Missing database tables have been automatically created.', 'martial-arts-club-manager' ); ?>
				</p>
			</div>
			<?php
		}

		// Check and create missing plugin pages.
		$this->check_plugin_pages();

		// Check if WooCommerce is active.
		if ( ! class_exists( 'WooCommerce' ) ) {
			$screen = get_current_screen();
			if ( $screen && isset( $screen->id ) && false !== strpos( $screen->id, 'martial-arts' ) ) {
				?>
				<div class="notice notice-warning">
					<p>
						<strong><?php esc_html_e( 'Martial Arts Club Manager:', 'martial-arts-club-manager' ); ?></strong>
						<?php esc_html_e( 'WooCommerce is not active. Some features require WooCommerce to be installed and activated.', 'martial-arts-club-manager' ); ?>
					</p>
				</div>
				<?php
			}
		}

		// Show welcome notice on first activation (dismissible).
		if ( get_option( 'macm_show_welcome_notice', false ) ) {
			?>
			<div class="notice notice-success is-dismissible" data-dismissible="kcm-welcome-notice">
				<p>
					<strong><?php esc_html_e( 'Thank you for installing Martial Arts Club Manager!', 'martial-arts-club-manager' ); ?></strong>
				</p>
				<p>
					<?php esc_html_e( 'Get started by configuring your locations, groups, and classes.', 'martial-arts-club-manager' ); ?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=martial-arts-club-manager' ) ); ?>" class="button button-primary">
						<?php esc_html_e( 'View Dashboard', 'martial-arts-club-manager' ); ?>
					</a>
				</p>
			</div>
			<?php
			// Delete the option after showing once.
			delete_option( 'macm_show_welcome_notice' );
		}

		// Show review notice after 14 days.
		$this->maybe_show_review_notice();
	}

	/**
	 * AJAX handler for dismissing the review notice.
	 *
	 * @since 1.0.325
	 */
	public function ajax_dismiss_review_notice() {
		check_ajax_referer( 'macm-review-nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error();
		}

		$action_type = isset( $_POST['action_type'] ) ? sanitize_key( $_POST['action_type'] ) : '';
		$user_id     = get_current_user_id();

		if ( 'later' === $action_type ) {
			update_user_meta( $user_id, 'macm_review_notice_remind_after', time() + ( 30 * DAY_IN_SECONDS ) );
		} else {
			update_user_meta( $user_id, 'macm_review_notice_dismissed', true );
		}

		wp_send_json_success();
	}

	/**
	 * Conditionally display a review notice on plugin admin pages.
	 *
	 * @since 1.0.325
	 */
	private function maybe_show_review_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen || ! isset( $screen->id ) || false === strpos( $screen->id, 'martial-arts' ) ) {
			return;
		}

		$user_id = get_current_user_id();

		if ( get_user_meta( $user_id, 'macm_review_notice_dismissed', true ) ) {
			return;
		}

		$remind_after = get_user_meta( $user_id, 'macm_review_notice_remind_after', true );
		if ( $remind_after && (int) $remind_after > time() ) {
			return;
		}

		$install_date = get_option( 'macm_plugin_install_date' );
		if ( ! $install_date ) {
			update_option( 'macm_plugin_install_date', time() );
			return;
		}

		if ( ( time() - (int) $install_date ) < ( 14 * DAY_IN_SECONDS ) ) {
			return;
		}

		$review_url = 'https://wordpress.org/support/plugin/martial-arts-club-manager/reviews/#new-post';
		$nonce      = wp_create_nonce( 'macm-review-nonce' );
		?>
		<div class="notice notice-info is-dismissible macm-review-notice" data-nonce="<?php echo esc_attr( $nonce ); ?>">
			<p>
				<strong><?php esc_html_e( 'Enjoying Martial Arts Club Manager?', 'martial-arts-club-manager' ); ?></strong>
				<?php esc_html_e( "We'd love to hear your feedback! A quick review on WordPress.org helps other club owners discover the plugin.", 'martial-arts-club-manager' ); ?>
			</p>
			<p>
				<a href="<?php echo esc_url( $review_url ); ?>"
					target="_blank" rel="noopener noreferrer"
					class="button button-primary macm-review-btn" data-action="reviewed">
					<?php esc_html_e( 'Leave a Review', 'martial-arts-club-manager' ); ?>
				</a>
				<a href="#" class="button macm-review-btn" data-action="later">
					<?php esc_html_e( 'Maybe Later', 'martial-arts-club-manager' ); ?>
				</a>
				<a href="#" class="macm-review-btn" data-action="dismiss"
					style="margin-left: 10px; text-decoration: none; color: #787c82;">
					<?php esc_html_e( 'I already did', 'martial-arts-club-manager' ); ?>
				</a>
			</p>
		</div>
		<script>
		jQuery( document ).ready( function( $ ) {
			$( '.macm-review-btn' ).on( 'click', function( e ) {
				var $btn = $( this );
				var action = $btn.data( 'action' );

				if ( action !== 'reviewed' ) {
					e.preventDefault();
				}

				$.post( ajaxurl, {
					action: 'macm_dismiss_review_notice',
					nonce: $( '.macm-review-notice' ).data( 'nonce' ),
					action_type: action
				} );

				$( '.macm-review-notice' ).fadeOut( 300 );
			} );
		} );
		</script>
		<?php
	}

	/**
	 * Add contextual help tabs to admin pages.
	 *
	 * @since 1.0.0
	 */
	public function add_help_tabs() {
		$screen = get_current_screen();

		if ( ! $screen || ! isset( $screen->id ) ) {
			return;
		}

		$is_macm_page = false;

		// Dashboard help.
		if ( 'toplevel_page_martial-arts-club-manager' === $screen->id ) {
			$is_macm_page = true;
			$screen->add_help_tab(
				array(
					'id'      => 'kcm-dashboard-overview',
					'title'   => __( 'Overview', 'martial-arts-club-manager' ),
					'content' => '<p>' . __( 'The dashboard provides a quick overview of your karate club statistics, recent activity, and quick access to important features.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Statistics Cards:</strong> View total members, active classes, attendance this month, and membership breakdown.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Recent Members:</strong> See the 5 most recently added members with their belt color and user association.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Quick Actions:</strong> Fast links to commonly used features like managing members, classes, attendance, sending emails, and settings.', 'martial-arts-club-manager' ) . '</p>',
				)
			);

			$screen->add_help_tab(
				array(
					'id'      => 'kcm-dashboard-getting-started',
					'title'   => __( 'Getting Started', 'martial-arts-club-manager' ),
					'content' => '<p>' . __( 'Follow these steps to get started with Martial Arts Club Manager:', 'martial-arts-club-manager' ) . '</p>' .
								'<ol>' .
								'<li>' . __( '<strong>Configure Locations:</strong> Add your dojo locations under Locations.', 'martial-arts-club-manager' ) . '</li>' .
								'<li>' . __( '<strong>Create Groups:</strong> Set up age or skill-based groups.', 'martial-arts-club-manager' ) . '</li>' .
								'<li>' . __( '<strong>Schedule Classes:</strong> Create class schedules with times and locations.', 'martial-arts-club-manager' ) . '</li>' .
								'<li>' . __( '<strong>Add Members:</strong> Members can self-register through WooCommerce My Account page.', 'martial-arts-club-manager' ) . '</li>' .
								'<li>' . __( '<strong>Track Attendance:</strong> Record attendance for each class session.', 'martial-arts-club-manager' ) . '</li>' .
								'</ol>',
				)
			);
		}

		// Members help.
		if ( 'martial-arts_page_kcm-members' === $screen->id ) {
			$is_macm_page = true;
			$screen->add_help_tab(
				array(
					'id'      => 'kcm-members-overview',
					'title'   => __( 'Overview', 'martial-arts-club-manager' ),
					'content' => '<p>' . __( 'The Members page displays all registered members with their details including name, date of birth, belt color, and membership type.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Adding Members:</strong> Members are added by users through the WooCommerce My Account page. Users can manage their own member profiles.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Membership Types:</strong> Premium and Basic membership types are assigned by administrators and determine access to exclusive content like training videos.', 'martial-arts-club-manager' ) . '</p>',
				)
			);
		}

		// Classes help.
		if ( 'martial-arts_page_kcm-classes' === $screen->id ) {
			$is_macm_page = true;
			$screen->add_help_tab(
				array(
					'id'      => 'kcm-classes-overview',
					'title'   => __( 'Overview', 'martial-arts-club-manager' ),
					'content' => '<p>' . __( 'Manage your karate class schedules, locations, and member enrollments from this page.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Creating Classes:</strong> Each class should have a name, schedule (day and time), location, and optional group assignment.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Enrolling Members:</strong> Assign members to classes to track their participation and attendance.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Archiving Classes:</strong> Archive classes that are no longer active instead of deleting them to preserve historical data.', 'martial-arts-club-manager' ) . '</p>',
				)
			);
		}

		// Attendance help.
		if ( 'martial-arts_page_kcm-attendance' === $screen->id ) {
			$is_macm_page = true;
			$screen->add_help_tab(
				array(
					'id'      => 'kcm-attendance-overview',
					'title'   => __( 'Overview', 'martial-arts-club-manager' ),
					'content' => '<p>' . __( 'Track and manage class attendance records from this page.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Recording Attendance:</strong> Select a class and date, then mark which members attended that session.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Viewing Records:</strong> Filter attendance records by class, member, or date range.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Exporting Data:</strong> Export attendance reports to CSV format for external analysis or record keeping.', 'martial-arts-club-manager' ) . '</p>',
				)
			);
		}

		// Email help.
		if ( 'martial-arts_page_kcm-send-email' === $screen->id ) {
			$is_macm_page = true;
			$screen->add_help_tab(
				array(
					'id'      => 'kcm-email-overview',
					'title'   => __( 'Overview', 'martial-arts-club-manager' ),
					'content' => '<p>' . __( 'Send personalized bulk emails to all users or specific users.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Recipients:</strong> Choose to send to all users or select specific users from the list.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Email Content:</strong> Compose your message using the visual editor. Emails are personalized with the recipient\'s first name and include a list of their associated members.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Email Settings:</strong> Configure sender name, email address, header, and footer text in Settings > Email tab.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Preview:</strong> Use the preview button to see how your email will look before sending.', 'martial-arts-club-manager' ) . '</p>',
				)
			);
		}

		// Settings help.
		if ( 'martial-arts_page_kcm-settings' === $screen->id ) {
			$is_macm_page = true;
			$screen->add_help_tab(
				array(
					'id'      => 'kcm-settings-overview',
					'title'   => __( 'Overview', 'martial-arts-club-manager' ),
					'content' => '<p>' . __( 'Configure plugin settings across multiple areas:', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>General:</strong> Date and time formats, items per page display settings.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Access Control:</strong> Select which pages require users to be logged in to access.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>WooCommerce:</strong> Configure product integration settings, member selector text, and display options.', 'martial-arts-club-manager' ) . '</p>' .
								'<p>' . __( '<strong>Email:</strong> Set sender information and email template header/footer for bulk emails.', 'martial-arts-club-manager' ) . '</p>',
				)
			);
		}

		// Add sidebar only to KCM pages.
		if ( $is_macm_page ) {
			$screen->set_help_sidebar(
				'<p><strong>' . __( 'For more information:', 'martial-arts-club-manager' ) . '</strong></p>' .
				'<p><a href="' . esc_url( admin_url( 'admin.php?page=martial-arts-club-manager' ) ) . '">' . __( 'View Dashboard', 'martial-arts-club-manager' ) . '</a></p>' .
				'<p><a href="' . esc_url( admin_url( 'admin.php?page=kcm-settings' ) ) . '">' . __( 'Plugin Settings', 'martial-arts-club-manager' ) . '</a></p>'
			);
		}
	}

	/**
	 * Check and create missing plugin pages.
	 *
	 * @since 1.0.73
	 */
	private function check_plugin_pages() {
		// FREE pages - always available.
		$free_pages = array(
			array(
				'title'   => 'Members Area',
				'slug'    => 'members-area',
				'content' => '[macm_member_area]',
				'option'  => 'macm_members_area_page_id',
			),
			array(
				'title'   => 'Book a Trial Class',
				'slug'    => 'book-trial-class',
				'content' => '[macm_trial_booking_form]',
				'option'  => 'macm_trial_booking_page_id',
			),
		);

		// PREMIUM pages - only for premium users.
		$premium_pages = array(
			array(
				'title'   => 'Training Videos',
				'slug'    => 'training-videos',
				'content' => '[macm_training_videos]',
				'option'  => 'macm_training_videos_page_id',
			),
			array(
				'title'   => 'Class Register',
				'slug'    => 'class-register',
				'content' => '[macm_class_register]',
				'option'  => 'macm_class_register_page_id',
			),
			array(
				'title'   => 'Events & Competitions',
				'slug'    => 'events-competitions',
				'content' => '[macm_events]',
				'option'  => 'macm_events_page_id',
			),
		);

		// Combine pages based on license status.
		$pages = $free_pages;
		if ( function_exists( 'macm_fs' ) && macm_fs()->can_use_premium_code() ) {
			$pages = array_merge( $pages, $premium_pages );
		}

		$pages_created = false;

		foreach ( $pages as $page_data ) {
			// Check if page option exists.
			$page_id = get_option( $page_data['option'], false );

			// If option doesn't exist or page doesn't exist, create it.
			if ( ! $page_id || ! get_post( $page_id ) ) {
				// Check if page already exists by slug.
				$existing_page = get_page_by_path( $page_data['slug'] ?? '' );

				if ( $existing_page && ! is_null( $existing_page ) ) {
					// Page exists, store its ID.
					update_option( $page_data['option'], $existing_page->ID );
				} else {
					// Create new page.
					$new_page_id = wp_insert_post(
						array(
							'post_title'     => $page_data['title'],
							'post_name'      => $page_data['slug'],
							'post_content'   => $page_data['content'],
							'post_status'    => 'publish',
							'post_type'      => 'page',
							'post_author'    => 1,
							'comment_status' => 'closed',
							'ping_status'    => 'closed',
						)
					);

					if ( $new_page_id && ! is_wp_error( $new_page_id ) ) {
						update_option( $page_data['option'], $new_page_id );
						$pages_created = true;
					}
				}
			}
		}

		// Show notice if pages were created.
		if ( $pages_created ) {
			?>
			<div class="notice notice-success is-dismissible">
				<p>
					<strong><?php esc_html_e( 'Martial Arts Club Manager:', 'martial-arts-club-manager' ); ?></strong>
					<?php esc_html_e( 'Missing plugin pages have been automatically created.', 'martial-arts-club-manager' ); ?>
				</p>
			</div>
			<?php
		}
	}
}
