<?php

declare(strict_types=1);

/**
 * Media Library filter views for image attributes (Task 9).
 *
 *   - Adds a "Filter by alt status" dropdown to upload.php with:
 *       missing alt / has alt / generated by ProRank
 *   - Applies the matching `meta_query` to the main library query, only
 *     for the upload screen and only when the user can edit posts.
 *
 * No marketing copy, no extra columns, no row actions — strictly query
 * shaping so the existing Media Library UI stays familiar.
 *
 * @package ProRank\SEO\Admin
 * @since   1.3.1
 */

namespace ProRank\SEO\Admin;

use ProRank\SEO\Core\Media\ImageAttributeHistory;

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


class ImageAttributesFilters {

    public const FILTER_PARAM = 'prorank_alt_filter';

    public const VAL_MISSING_ALT = 'missing_alt';
    public const VAL_HAS_ALT     = 'has_alt';
    public const VAL_GENERATED   = 'generated';

    public function register(): void {
        if ( ! function_exists( 'add_action' ) ) {
            return;
        }
        add_action( 'restrict_manage_posts', [ $this, 'render_dropdown' ] );
        add_action( 'pre_get_posts',         [ $this, 'apply_to_query' ] );
    }

    public function render_dropdown( $post_type ): void {
        if ( $post_type !== 'attachment' ) {
            return;
        }
        if ( ! function_exists( 'current_user_can' ) || ! current_user_can( 'edit_posts' ) ) {
            return;
        }
        $current = isset( $_GET[ self::FILTER_PARAM ] )
            ? sanitize_text_field( wp_unslash( (string) $_GET[ self::FILTER_PARAM ] ) )
            : '';
        ?>
        <label for="prorank-alt-filter" class="screen-reader-text">
            <?php esc_html_e( 'Filter by alt status', 'prorank-seo' ); ?>
        </label>
        <select name="<?php echo esc_attr( self::FILTER_PARAM ); ?>" id="prorank-alt-filter">
            <option value=""><?php esc_html_e( 'Alt status: All', 'prorank-seo' ); ?></option>
            <option value="<?php echo esc_attr( self::VAL_MISSING_ALT ); ?>" <?php selected( $current, self::VAL_MISSING_ALT ); ?>>
                <?php esc_html_e( 'Missing alt text', 'prorank-seo' ); ?>
            </option>
            <option value="<?php echo esc_attr( self::VAL_HAS_ALT ); ?>" <?php selected( $current, self::VAL_HAS_ALT ); ?>>
                <?php esc_html_e( 'Has alt text', 'prorank-seo' ); ?>
            </option>
            <option value="<?php echo esc_attr( self::VAL_GENERATED ); ?>" <?php selected( $current, self::VAL_GENERATED ); ?>>
                <?php esc_html_e( 'Generated by ProRank', 'prorank-seo' ); ?>
            </option>
        </select>
        <?php
    }

    public function apply_to_query( $query ): void {
        if ( ! function_exists( 'is_admin' ) || ! is_admin() ) {
            return;
        }
        if ( ! $query instanceof \WP_Query || ! $query->is_main_query() ) {
            return;
        }
        // Only shape the upload screen query — `pre_get_posts` fires for
        // many internal WP_Query calls; we want to leave them alone.
        $pagenow = $GLOBALS['pagenow'] ?? '';
        if ( $pagenow !== 'upload.php' ) {
            return;
        }
        if ( ! function_exists( 'current_user_can' ) || ! current_user_can( 'edit_posts' ) ) {
            return;
        }
        $value = isset( $_GET[ self::FILTER_PARAM ] )
            ? sanitize_text_field( wp_unslash( (string) $_GET[ self::FILTER_PARAM ] ) )
            : '';

        $existing = (array) $query->get( 'meta_query' );

        switch ( $value ) {
            case self::VAL_MISSING_ALT:
                $existing[] = [
                    'relation' => 'OR',
                    [ 'key' => '_wp_attachment_image_alt', 'compare' => 'NOT EXISTS' ],
                    [ 'key' => '_wp_attachment_image_alt', 'value' => '', 'compare' => '=' ],
                ];
                break;
            case self::VAL_HAS_ALT:
                $existing[] = [ 'key' => '_wp_attachment_image_alt', 'value' => '', 'compare' => '!=' ];
                break;
            case self::VAL_GENERATED:
                $existing[] = [ 'key' => ImageAttributeHistory::META_GENERATED, 'value' => '1', 'compare' => '=' ];
                break;
            default:
                return;
        }
        $query->set( 'meta_query', $existing );
    }
}
