<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://yourwebsite.com
 * @since      1.0.0
 *
 * @package    CSPG_Basic_SEO_Helper
 * @subpackage CSPG_Basic_SEO_Helper/admin
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    CSPG_Basic_SEO_Helper
 * @subpackage CSPG_Basic_SEO_Helper/admin
 * @author     CSP Geeks LLC <info@cspgeeks.com>
 */
class CSPG_Basic_SEO_Helper_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version     = $version;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {
		// Only enqueue on our plugin pages
		$screen = get_current_screen();
		if ( $screen && strpos( $screen->id, 'cspg-basic-seo-helper' ) !== false ) {
			wp_enqueue_style( $this->plugin_name, CSPG_BASIC_SEO_HELPER_PLUGIN_URL . 'assets/css/admin.css', array(), $this->version, 'all' );

			// Enqueue page-specific styles
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Safe GET parameter check for page identification only, no data processing
			if ( isset( $_GET['page'] ) ) {
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Safe GET parameter check for page identification only, no data processing
				$page = sanitize_text_field( wp_unslash( $_GET['page'] ) );

				if ( 'cspg-basic-seo-helper-sitemap' === $page ) {
					wp_enqueue_style( $this->plugin_name . '-sitemap', plugin_dir_url( __DIR__ ) . 'admin/css/sitemap-display.css', array(), $this->version, 'all' );
				} elseif ( 'cspg-basic-seo-helper-templates' === $page ) {
					wp_enqueue_style( $this->plugin_name . '-templates', plugin_dir_url( __DIR__ ) . 'admin/css/templates-display.css', array(), $this->version, 'all' );
				}
			}
		}

		// Enqueue meta-box styles on post/page edit screens
		if ( $screen && in_array( $screen->base, array( 'post', 'page' ), true ) ) {
			wp_enqueue_style(
				$this->plugin_name . '-meta-box',
				plugin_dir_url( __DIR__ ) . 'admin/css/meta-box.css',
				array(),
				$this->version,
				'all'
			);
		}
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {
		// Only enqueue on our plugin pages
		$screen = get_current_screen();
		if ( strpos( $screen->id, 'cspg-basic-seo-helper' ) !== false ) {
			// Enqueue WordPress media uploader
			wp_enqueue_media();
			wp_enqueue_script( $this->plugin_name, CSPG_BASIC_SEO_HELPER_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery', 'media-upload' ), $this->version, false );

			// Enqueue page-specific scripts
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Safe GET parameter check for page identification only, no data processing
			if ( isset( $_GET['page'] ) ) {
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Safe GET parameter check for page identification only, no data processing
				$page = sanitize_text_field( wp_unslash( $_GET['page'] ) );

				if ( 'cspg-basic-seo-helper-templates' === $page ) {
					wp_enqueue_script(
						$this->plugin_name . '-templates',
						plugin_dir_url( __DIR__ ) . 'admin/js/templates-display.js',
						array( 'jquery' ),
						$this->version,
						true
					);

					// Localize script with template data
					wp_localize_script(
						$this->plugin_name . '-templates',
						'cspgbaseTemplates',
						array(
							'siteName'       => get_bloginfo( 'name' ),
							'tagline'        => get_bloginfo( 'description' ),
							'currentDate'    => gmdate( 'F j, Y' ),
							'templatesSaved' => false, // Will be set dynamically via wp_add_inline_script if needed
						)
					);
				}
			}

			// Enqueue meta box script on post/page edit screens
			if ( in_array( $screen->base, array( 'post', 'page' ), true ) ) {
				wp_enqueue_script(
					$this->plugin_name . '-meta-box',
					plugin_dir_url( __DIR__ ) . 'admin/js/meta-box.js',
					array( 'jquery', 'media-upload' ),
					$this->version,
					true
				);

				// Localize script for meta box
				wp_localize_script(
					$this->plugin_name . '-meta-box',
					'cspgbaseMetaBox',
					array(
						'selectImageTitle' => esc_html__( 'Select Social Image', 'cspg-basic-seo-helper' ),
						'useImageText'     => esc_html__( 'Use this image', 'cspg-basic-seo-helper' ),
						'mediaUnavailable' => esc_html__( 'Media uploader not available.', 'cspg-basic-seo-helper' ),
					)
				);
			}
		}
	}

	/**
	 * Initialize admin settings
	 *
	 * @since    1.0.2
	 */
	public function admin_init() {
		// Register template settings
		register_setting( 'basic_seo_helper_templates', 'cspgbase_default_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'cspgbase_default_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_post_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_post_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_page_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_page_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_home_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_home_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_category_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_category_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_tag_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_tag_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_author_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_author_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_archive_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_archive_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_search_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_search_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_404_title_template', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'basic_seo_helper_templates', 'bsh_404_description_template', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
	}

	/**
	 * Register post meta fields for REST API access
	 *
	 * Registers all SEO meta fields with the WordPress REST API to enable
	 * read/write access via /wp/v2/posts and /wp/v2/pages endpoints.
	 *
	 * @since    1.2.18
	 */
	public function register_post_meta() {
		$post_types = array( 'post', 'page' );

		// Define meta fields with their configurations
		$meta_fields = array(
			'_basic_seo_helper_title'              => array(
				'type'              => 'string',
				'description'       => 'Custom SEO title override',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_description'        => array(
				'type'              => 'string',
				'description'       => 'Custom SEO meta description',
				'single'            => true,
				'sanitize_callback' => 'sanitize_textarea_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_image'              => array(
				'type'              => 'string',
				'description'       => 'Custom social sharing image URL',
				'single'            => true,
				'sanitize_callback' => 'esc_url_raw',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_og_title'           => array(
				'type'              => 'string',
				'description'       => 'Custom Open Graph title',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_og_description'     => array(
				'type'              => 'string',
				'description'       => 'Custom Open Graph description',
				'single'            => true,
				'sanitize_callback' => 'sanitize_textarea_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_twitter_title'      => array(
				'type'              => 'string',
				'description'       => 'Custom Twitter Card title',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_twitter_description' => array(
				'type'              => 'string',
				'description'       => 'Custom Twitter Card description',
				'single'            => true,
				'sanitize_callback' => 'sanitize_textarea_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_schema_enabled'     => array(
				'type'              => 'string',
				'description'       => 'Enable Schema.org markup (1 = enabled, 0 = disabled)',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_noindex'            => array(
				'type'              => 'string',
				'description'       => 'Robots meta noindex directive (1 = enabled, 0 = disabled)',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_nofollow'           => array(
				'type'              => 'string',
				'description'       => 'Robots meta nofollow directive (1 = enabled, 0 = disabled)',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_noarchive'          => array(
				'type'              => 'string',
				'description'       => 'Robots meta noarchive directive (1 = enabled, 0 = disabled)',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
			'_basic_seo_helper_nosnippet'          => array(
				'type'              => 'string',
				'description'       => 'Robots meta nosnippet directive (1 = enabled, 0 = disabled)',
				'single'            => true,
				'sanitize_callback' => 'sanitize_text_field',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
				'show_in_rest'      => true,
			),
		);

		// Register each field for both post types
		foreach ( $post_types as $post_type ) {
			foreach ( $meta_fields as $meta_key => $args ) {
				register_post_meta( $post_type, $meta_key, $args );
			}
		}
	}

	/**
	 * Add admin menu pages
	 *
	 * @since    1.0.0
	 */
	public function admin_menu() {
		// Add main menu page
		add_menu_page(
			__( 'CSPG Basic SEO Helper', 'cspg-basic-seo-helper' ),
			__( 'CSPG Basic SEO Helper', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper-dashboard',
			array( $this, 'display_seo_health_dashboard' ),
			'dashicons-search',
			30
		);

		// Add SEO Health Dashboard as first submenu (replaces main menu item)
		add_submenu_page(
			'cspg-basic-seo-helper-dashboard',
			__( 'SEO Health Dashboard', 'cspg-basic-seo-helper' ),
			__( 'SEO Health Dashboard', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper-dashboard',
			array( $this, 'display_seo_health_dashboard' )
		);

		// Add General Settings submenu
		add_submenu_page(
			'cspg-basic-seo-helper-dashboard',
			__( 'General Settings', 'cspg-basic-seo-helper' ),
			__( 'General Settings', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper',
			array( $this, 'display_dashboard_page' )
		);

		// Add Social Media submenu
		add_submenu_page(
			'cspg-basic-seo-helper-dashboard',
			__( 'Social Media', 'cspg-basic-seo-helper' ),
			__( 'Social Media', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper-social',
			array( $this, 'display_social_media_page' )
		);

		// Add Schema Markup submenu
		add_submenu_page(
			'cspg-basic-seo-helper-dashboard',
			__( 'Schema Markup', 'cspg-basic-seo-helper' ),
			__( 'Schema Markup', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper-schema',
			array( $this, 'display_schema_page' )
		);

		// Add Meta Tags submenu
		add_submenu_page(
			'cspg-basic-seo-helper-dashboard',
			__( 'Meta Tags', 'cspg-basic-seo-helper' ),
			__( 'Meta Tags', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper-meta',
			array( $this, 'display_meta_tags_page' )
		);

		// Add Templates submenu
		add_submenu_page(
			'cspg-basic-seo-helper-dashboard',
			__( 'Templates', 'cspg-basic-seo-helper' ),
			__( 'Templates', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper-templates',
			array( $this, 'display_templates_page' )
		);

		// Add Sitemap submenu
		add_submenu_page(
			'cspg-basic-seo-helper-dashboard',
			__( 'Sitemap', 'cspg-basic-seo-helper' ),
			__( 'Sitemap', 'cspg-basic-seo-helper' ),
			'manage_options',
			'cspg-basic-seo-helper-sitemap',
			array( $this, 'display_sitemap_page' )
		);
	}

	/**
	 * Display the dashboard page
	 *
	 * @since    1.0.0
	 */
	public function display_dashboard_page() {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-admin-display.php';
	}

	/**
	 * Display the social media page
	 *
	 * @since    1.0.0
	 */
	public function display_social_media_page() {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-social-display.php';
	}

	/**
	 * Display the schema page
	 *
	 * @since    1.0.0
	 */
	public function display_schema_page() {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-schema-display.php';
	}

	/**
	 * Display the meta tags page
	 *
	 * @since    1.0.0
	 */
	public function display_meta_tags_page() {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-meta-display.php';
	}

	/**
	 * Display the templates page
	 *
	 * @since    1.0.2
	 */
	public function display_templates_page() {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-templates-display.php';
	}

	/**
	 * Display the sitemap page
	 *
	 * @since    1.0.3
	 */
	public function display_sitemap_page() {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-sitemap-display.php';
	}

	/**
	 * Display the SEO Health Dashboard
	 *
	 * @since    1.0.2
	 */
	public function display_seo_health_dashboard() {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-dashboard-display.php';
	}

	/**
	 * Get summary statistics for the SEO dashboard
	 *
	 * @since    1.0.2
	 * @return   array   Summary statistics
	 */
	public function get_seo_summary_stats() {
		$posts = get_posts(
			array(
				'post_type'   => array( 'post', 'page' ),
				'post_status' => 'publish',
				'numberposts' => -1,
			)
		);

		$stats = array(
			'good'              => 0,
			'needs_improvement' => 0,
			'poor'              => 0,
			'total'             => 0,
		);

		foreach ( $posts as $post ) {
			$score = $this->calculate_seo_score( $post->ID );
			++$stats['total'];

			if ( $score >= 80 ) {
				++$stats['good'];
			} elseif ( $score >= 50 ) {
				++$stats['needs_improvement'];
			} else {
				++$stats['poor'];
			}
		}

		return $stats;
	}

	/**
	 * Get posts for dashboard display with filtering and pagination
	 *
	 * @since    1.0.2
	 * @param    string  $filter_score  Score filter (good, needs-improvement, poor)
	 * @param    string  $filter_type   Post type filter (post, page)
	 * @param    int     $paged         Current page number
	 * @param    int     $per_page      Posts per page
	 * @return   array   Array with posts and pagination info
	 */
	public function get_posts_for_dashboard( $filter_score = '', $filter_type = '', $paged = 1, $per_page = 20 ) {
		$args = array(
			'post_type'   => ! empty( $filter_type ) ? $filter_type : array( 'post', 'page' ),
			'post_status' => 'publish',
			'numberposts' => -1, // Get all first for filtering
			'orderby'     => 'title',
			'order'       => 'ASC',
		);

		$all_posts = get_posts( $args );

		// Apply score filtering if specified
		if ( ! empty( $filter_score ) ) {
			$filtered_posts = array();
			foreach ( $all_posts as $post ) {
				$score          = $this->calculate_seo_score( $post->ID );
				$score_category = $this->get_score_category( $score );

				if ( $score_category === $filter_score ) {
					$filtered_posts[] = $post;
				}
			}
			$all_posts = $filtered_posts;
		}

		// Calculate pagination
		$total_posts = count( $all_posts );
		$total_pages = ceil( $total_posts / $per_page );
		$offset      = ( $paged - 1 ) * $per_page;

		// Get posts for current page
		$posts = array_slice( $all_posts, $offset, $per_page );

		return array(
			'posts'        => $posts,
			'total_posts'  => $total_posts,
			'total_pages'  => $total_pages,
			'current_page' => $paged,
			'per_page'     => $per_page,
		);
	}

	/**
	 * Calculate SEO score for a post
	 *
	 * @since    1.0.2
	 * @param    int    $post_id   Post ID
	 * @return   int    Score (0-100)
	 */
	public function calculate_seo_score( $post_id ) {
		$score = 0;

		// Meta Title (25 points)
		$meta_title = get_post_meta( $post_id, '_basic_seo_helper_title', true );
		if ( ! empty( $meta_title ) ) {
			$title_length = strlen( $meta_title );
			if ( $title_length >= 50 && $title_length <= 60 ) {
				$score += 25;
			} else {
				$score += 20; // Good but not optimal length
			}
		}

		// Meta Description (25 points)
		$meta_description = get_post_meta( $post_id, '_basic_seo_helper_description', true );
		if ( ! empty( $meta_description ) ) {
			$desc_length = strlen( $meta_description );
			if ( $desc_length >= 120 && $desc_length <= 160 ) {
				$score += 25;
			} else {
				$score += 20; // Good but not optimal length
			}
		}

		// Open Graph Tags (15 points)
		$og_title       = get_post_meta( $post_id, '_basic_seo_helper_og_title', true );
		$og_description = get_post_meta( $post_id, '_basic_seo_helper_og_description', true );
		if ( ! empty( $og_title ) && ! empty( $og_description ) ) {
			$score += 15;
		}

		// Twitter Card Tags (15 points)
		$twitter_title       = get_post_meta( $post_id, '_basic_seo_helper_twitter_title', true );
		$twitter_description = get_post_meta( $post_id, '_basic_seo_helper_twitter_description', true );
		if ( ! empty( $twitter_title ) && ! empty( $twitter_description ) ) {
			$score += 15;
		}

		// Schema Data (10 points) - Default to enabled
		$schema_enabled = get_post_meta( $post_id, '_basic_seo_helper_schema_enabled', true );
		if ( '' === $schema_enabled || '1' === $schema_enabled || 'yes' === $schema_enabled ) {
			$score += 10;
		}

		// Readability (5 points) - Basic check for title and description presence
		if ( ! empty( $meta_title ) && ! empty( $meta_description ) ) {
			$score += 5;
		}

		return min( 100, $score );
	}

	/**
	 * Get post SEO data for dashboard display
	 *
	 * @since    1.0.2
	 * @param    int    $post_id   Post ID
	 * @return   array  SEO data
	 */
	public function get_post_seo_data( $post_id ) {
		return array(
			'meta_title'          => get_post_meta( $post_id, '_basic_seo_helper_title', true ),
			'meta_description'    => get_post_meta( $post_id, '_basic_seo_helper_description', true ),
			'og_title'            => get_post_meta( $post_id, '_basic_seo_helper_og_title', true ),
			'og_description'      => get_post_meta( $post_id, '_basic_seo_helper_og_description', true ),
			'twitter_title'       => get_post_meta( $post_id, '_basic_seo_helper_twitter_title', true ),
			'twitter_description' => get_post_meta( $post_id, '_basic_seo_helper_twitter_description', true ),
			'schema_status'       => ( get_post_meta( $post_id, '_basic_seo_helper_schema_enabled', true ) !== '0' ) ? 'enabled' : 'disabled',
		);
	}

	/**
	 * Get score category for filtering
	 *
	 * @since    1.0.2
	 * @param    int    $score   Score (0-100)
	 * @return   string Score category
	 */
	public function get_score_category( $score ) {
		if ( $score >= 80 ) {
			return 'good';
		} elseif ( $score >= 50 ) {
			return 'needs-improvement';
		} else {
			return 'poor';
		}
	}

	/**
	 * Get CSS class for score badge
	 *
	 * @since    1.0.2
	 * @param    int    $score   Score (0-100)
	 * @return   string CSS class
	 */
	public function get_score_class( $score ) {
		if ( $score >= 80 ) {
			return 'good';
		} elseif ( $score >= 50 ) {
			return 'needs-improvement';
		} else {
			return 'poor';
		}
	}

	/**
	 * Add meta boxes to post/page edit screens
	 *
	 * @since    1.0.0
	 */
	public function add_meta_boxes() {
		$post_types = array( 'post', 'page' );

		foreach ( $post_types as $post_type ) {
			add_meta_box(
				'basic-seo-helper-meta-box',
				__( 'SEO Meta Tags Preview', 'cspg-basic-seo-helper' ),
				array( $this, 'display_meta_box' ),
				$post_type,
				'normal',
				'default'
			);
		}
	}

	/**
	 * Display the meta box content
	 *
	 * @since    1.0.0
	 */
	public function display_meta_box( $post ) {
		include_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/partials/basic-seo-helper-meta-box.php';
	}

	/**
	 * Save meta box data
	 *
	 * @since    1.0.0
	 */
	public function save_meta_box( $post_id ) {
		// Check if user has permission to edit post
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Check nonce for security
		if (
			! isset( $_POST['basic_seo_helper_meta_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['basic_seo_helper_meta_nonce'] ) ), 'basic_seo_helper_meta_box' )
		) {
			return;
		}

		// Save custom meta title if provided
		if ( isset( $_POST['basic_seo_helper_title'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_title', sanitize_text_field( wp_unslash( $_POST['basic_seo_helper_title'] ) ) );
		}

		// Save custom meta description if provided
		if ( isset( $_POST['basic_seo_helper_description'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_description', sanitize_textarea_field( wp_unslash( $_POST['basic_seo_helper_description'] ) ) );
		}

		// Save custom social image if provided
		if ( isset( $_POST['basic_seo_helper_image'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_image', esc_url_raw( wp_unslash( $_POST['basic_seo_helper_image'] ) ) );
		}

		// Save Open Graph fields
		if ( isset( $_POST['basic_seo_helper_og_title'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_og_title', sanitize_text_field( wp_unslash( $_POST['basic_seo_helper_og_title'] ) ) );
		}
		if ( isset( $_POST['basic_seo_helper_og_description'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_og_description', sanitize_textarea_field( wp_unslash( $_POST['basic_seo_helper_og_description'] ) ) );
		}

		// Save Twitter Card fields
		if ( isset( $_POST['basic_seo_helper_twitter_title'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_twitter_title', sanitize_text_field( wp_unslash( $_POST['basic_seo_helper_twitter_title'] ) ) );
		}
		if ( isset( $_POST['basic_seo_helper_twitter_description'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_twitter_description', sanitize_textarea_field( wp_unslash( $_POST['basic_seo_helper_twitter_description'] ) ) );
		}

		// Save Schema settings
		// For checkboxes: '1' = checked, '0' = unchecked, '' = not set (defaults to enabled)
		if ( isset( $_POST['basic_seo_helper_schema_enabled'] ) ) {
			update_post_meta( $post_id, '_basic_seo_helper_schema_enabled', '1' );
		} else {
			update_post_meta( $post_id, '_basic_seo_helper_schema_enabled', '0' );
		}

		// Save Robots meta tag settings
		// For each checkbox: '1' = checked, '0' = unchecked
		$robots_fields = array( 'noindex', 'nofollow', 'noarchive', 'nosnippet' );
		foreach ( $robots_fields as $field ) {
			$field_name = 'basic_seo_helper_' . $field;
			if ( isset( $_POST[ $field_name ] ) ) {
				update_post_meta( $post_id, '_' . $field_name, '1' );
			} else {
				update_post_meta( $post_id, '_' . $field_name, '0' );
			}
		}
	}

	/**
	 * Add plugin action links
	 *
	 * Adds a "Get Premium" link to the plugin actions on the plugins page.
	 *
	 * @since    1.1.1
	 * @param    array    $links    Existing plugin action links.
	 * @return   array              Modified plugin action links.
	 */
	public function add_plugin_action_links( $links ) {
		$premium_link = array(
			'<a href="https://plugins.cspgeeks.com/plugin/cspg-basic-seo-helper-premium/" target="_blank" rel="noopener noreferrer" class="cspgbase-premium-link">' . __( 'Get Premium', 'cspg-basic-seo-helper' ) . '</a>',
		);
		return array_merge( $premium_link, $links );
	}
}
