<?php
/**
 * Livada SEO — Admin List Filters
 *
 * Adds a `livada_seo_filter` query var that the dashboard cards link to:
 *   missing_desc — posts with no meta description
 *   noindex      — posts flagged noindex
 *   low_score    — posts with SEO score below 50
 *   no_keyword   — posts with no focus keyword
 *
 * Hooks into pre_get_posts on edit.php so the filter applies to the standard
 * post-list table; the user can edit / quick-edit each row in place.
 *
 * @package Livada_SEO
 */

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

class Livada_SEO_Admin_Filters {

	const QUERY_VAR = 'livada_seo_filter';

	const ALLOWED = [ 'missing_desc', 'noindex', 'low_score', 'no_keyword', 'cornerstone' ];

	// ── Bootstrap ─────────────────────────────────────────────────────────────

	public static function init(): void {
		add_action( 'pre_get_posts', [ self::class, 'filter_query'   ] );
		add_action( 'admin_notices', [ self::class, 'render_notice'  ] );
	}

	/**
	 * Returns the active filter slug from the URL, or '' if none/invalid.
	 */
	public static function active_filter(): string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$filter = isset( $_GET[ self::QUERY_VAR ] ) ? sanitize_key( $_GET[ self::QUERY_VAR ] ) : '';
		return in_array( $filter, self::ALLOWED, true ) ? $filter : '';
	}

	// ── Query filter ──────────────────────────────────────────────────────────

	public static function filter_query( WP_Query $query ): void {
		if ( ! is_admin() || ! $query->is_main_query() ) {
			return;
		}

		global $pagenow;
		if ( 'edit.php' !== $pagenow ) {
			return;
		}

		$filter = self::active_filter();
		if ( '' === $filter ) {
			return;
		}

		switch ( $filter ) {
			case 'missing_desc':
				$query->set( 'meta_query', [
					'relation' => 'OR',
					[ 'key' => '_livada_seo_description', 'compare' => 'NOT EXISTS' ],
					[ 'key' => '_livada_seo_description', 'value' => '', 'compare' => '=' ],
				] );
				break;

			case 'noindex':
				$query->set( 'meta_query', [
					[ 'key' => '_livada_seo_noindex', 'value' => '1', 'compare' => '=' ],
				] );
				break;

			case 'low_score':
				$query->set( 'meta_query', [
					'relation' => 'AND',
					[ 'key' => '_livada_seo_score', 'compare' => 'EXISTS' ],
					[ 'key' => '_livada_seo_score', 'value' => 50, 'compare' => '<', 'type' => 'NUMERIC' ],
				] );
				$query->set( 'orderby', 'meta_value_num' );
				$query->set( 'meta_key', '_livada_seo_score' );
				$query->set( 'order', 'ASC' );
				break;

			case 'no_keyword':
				$query->set( 'meta_query', [
					'relation' => 'OR',
					[ 'key' => '_livada_seo_focus_keyword', 'compare' => 'NOT EXISTS' ],
					[ 'key' => '_livada_seo_focus_keyword', 'value' => '', 'compare' => '=' ],
				] );
				break;

			case 'cornerstone':
				$query->set( 'meta_query', [
					[ 'key' => '_livada_seo_cornerstone', 'value' => '1', 'compare' => '=' ],
				] );
				break;
		}
	}

	// ── Admin notice (shows what's filtered + a clear link) ──────────────────

	public static function render_notice(): void {
		global $pagenow;
		if ( 'edit.php' !== $pagenow ) {
			return;
		}

		$filter = self::active_filter();
		if ( '' === $filter ) {
			return;
		}

		$labels = [
			'missing_desc' => __( 'Showing posts without a meta description.',  'livada-seo' ),
			'noindex'      => __( 'Showing posts flagged as noindex.',           'livada-seo' ),
			'low_score'    => __( 'Showing posts with an SEO score below 50.',   'livada-seo' ),
			'no_keyword'   => __( 'Showing posts with no focus keyword set.',    'livada-seo' ),
			'cornerstone'  => __( 'Showing cornerstone content.',                 'livada-seo' ),
		];

		$label = $labels[ $filter ] ?? '';
		if ( '' === $label ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$post_type = isset( $_GET['post_type'] ) ? sanitize_key( $_GET['post_type'] ) : 'post';
		$clear_url = add_query_arg( [ 'post_type' => $post_type ], admin_url( 'edit.php' ) );

		printf(
			'<div class="notice notice-info"><p><strong>%s</strong> %s &nbsp; <a class="button button-small" href="%s">%s</a></p></div>',
			esc_html__( 'Livada SEO filter:', 'livada-seo' ),
			esc_html( $label ),
			esc_url( $clear_url ),
			esc_html__( 'Clear filter', 'livada-seo' )
		);
	}

	// ── URL helpers (used by the dashboard) ──────────────────────────────────

	/**
	 * Returns the URL of the post-list filtered by our query var.
	 *
	 * @param string $filter   One of self::ALLOWED.
	 * @param string $post_type Defaults to 'post'.
	 */
	public static function url_for( string $filter, string $post_type = 'post' ): string {
		if ( ! in_array( $filter, self::ALLOWED, true ) ) {
			return admin_url( 'edit.php' );
		}

		return add_query_arg(
			[
				'post_type'      => $post_type,
				self::QUERY_VAR  => $filter,
			],
			admin_url( 'edit.php' )
		);
	}
}
