<?php

defined( 'ABSPATH' ) || exit;
/**
 * Tax Exemption column + filter on the Users list screen.
 *
 * FREE:  Read-only status badge (Always / Never / Exempt: role) and a
 *        filter dropdown. Deliberately NOT a toggle — exemption changes
 *        are audited, deliberate acts made on the user profile, and a
 *        binary toggle cannot represent the tri-state override.
 * PRO:   Adds a Certificate badge for users with an active approved
 *        certificate, and a matching filter option.
 */
class Rankd_Tx_Users_List {
    public static function init() {
        add_filter( 'manage_users_columns', array(__CLASS__, 'add_column') );
        add_filter(
            'manage_users_custom_column',
            array(__CLASS__, 'render_column'),
            10,
            3
        );
        add_action( 'restrict_manage_users', array(__CLASS__, 'render_filter') );
        add_action( 'pre_get_users', array(__CLASS__, 'apply_filter') );
    }

    // -------------------------------------------------------------------------
    // Column
    // -------------------------------------------------------------------------
    public static function add_column( $columns ) {
        $columns['rankd_tx_status'] = __( 'Tax Exemption', 'rankd-tax-exemption-certificates-for-woocommerce' );
        return $columns;
    }

    /**
     * Renders the status badge for one row.
     *
     * @param string $output  Current column output.
     * @param string $column  Column key.
     * @param int    $user_id
     * @return string
     */
    public static function render_column( $output, $column, $user_id ) {
        if ( 'rankd_tx_status' !== $column ) {
            return $output;
        }
        $override = Rankd_Tx_Capabilities::get_override( $user_id );
        if ( 'never' === $override ) {
            return '<span class="rankd-tx-badge rankd-tx-badge--revoked" title="' . esc_attr__( 'This plugin will not exempt this user (blocks role rules and certificates).', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '">' . esc_html__( 'Never exempt', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</span>';
        }
        $badges = array();
        if ( 'always' === $override ) {
            $badges[] = '<span class="rankd-tx-badge rankd-tx-badge--approved">' . esc_html__( 'Always exempt', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</span>';
        }
        if ( Rankd_Tx_Capabilities::user_has_exempt_role( $user_id ) ) {
            $badges[] = '<span class="rankd-tx-badge rankd-tx-badge--approved">' . esc_html__( 'Exempt: role', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</span>';
        }
        // PRO: active approved certificate badge (jurisdiction-agnostic —
        // certificates are matched per order address at checkout).
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $cert_badge = self::certificate_badge__premium_only( $user_id );
            if ( $cert_badge ) {
                $badges[] = $cert_badge;
            }
        }
        return ( $badges ? implode( ' ', $badges ) : '<span style="color:#999;">&mdash;</span>' );
    }

    // -------------------------------------------------------------------------
    // Filter dropdown
    // -------------------------------------------------------------------------
    /**
     * Renders the filter dropdown above the users table (top position only,
     * to avoid duplicate element IDs).
     *
     * @param string $which 'top' or 'bottom'.
     */
    public static function render_filter( $which ) {
        if ( 'top' !== $which ) {
            return;
        }
        $nonce = sanitize_text_field( wp_unslash( $_GET['rankd_tx_filter_nonce'] ?? '' ) );
        $current = ( wp_verify_nonce( $nonce, 'rankd_tx_users_filter' ) ? sanitize_key( wp_unslash( $_GET['rankd_tx_filter'] ?? '' ) ) : '' );
        $options = array(
            ''       => __( 'Tax exemption: any', 'rankd-tax-exemption-certificates-for-woocommerce' ),
            'always' => __( 'Always exempt', 'rankd-tax-exemption-certificates-for-woocommerce' ),
            'never'  => __( 'Never exempt', 'rankd-tax-exemption-certificates-for-woocommerce' ),
            'role'   => __( 'Exempt by role', 'rankd-tax-exemption-certificates-for-woocommerce' ),
        );
        // PRO: filter by active certificate.
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $options['certificate'] = __( 'Has active certificate', 'rankd-tax-exemption-certificates-for-woocommerce' );
        }
        wp_nonce_field( 'rankd_tx_users_filter', 'rankd_tx_filter_nonce', false );
        echo '<select name="rankd_tx_filter" id="rankd_tx_filter" style="float:none;margin:0 4px 0 8px;">';
        foreach ( $options as $value => $label ) {
            echo '<option value="' . esc_attr( $value ) . '" ' . selected( $current, $value, false ) . '>' . esc_html( $label ) . '</option>';
        }
        echo '</select>';
        submit_button(
            __( 'Filter', 'rankd-tax-exemption-certificates-for-woocommerce' ),
            '',
            'rankd_tx_filter_submit',
            false
        );
    }

    /**
     * Applies the selected filter to the Users list query.
     *
     * @param WP_User_Query $query
     */
    public static function apply_filter( $query ) {
        global $pagenow;
        if ( !is_admin() || 'users.php' !== $pagenow ) {
            return;
        }
        $nonce = sanitize_text_field( wp_unslash( $_GET['rankd_tx_filter_nonce'] ?? '' ) );
        if ( !wp_verify_nonce( $nonce, 'rankd_tx_users_filter' ) ) {
            return;
        }
        $filter = sanitize_key( wp_unslash( $_GET['rankd_tx_filter'] ?? '' ) );
        if ( '' === $filter ) {
            return;
        }
        if ( 'always' === $filter ) {
            $query->set( 'meta_query', array(array(
                'key'     => RANKD_TX_META_EXEMPT,
                'value'   => array('always', '1', 'yes'),
                'compare' => 'IN',
            )) );
            return;
        }
        if ( 'never' === $filter ) {
            $query->set( 'meta_query', array(array(
                'key'   => RANKD_TX_META_EXEMPT,
                'value' => 'never',
            )) );
            return;
        }
        if ( 'role' === $filter ) {
            $exempt_roles = Rankd_Tx_Capabilities::get_exempt_roles();
            if ( empty( $exempt_roles ) ) {
                $query->set( 'include', array(0) );
                // No exempt roles configured — no matches.
            } else {
                $query->set( 'role__in', $exempt_roles );
            }
            return;
        }
        // PRO: filter to users with an active approved certificate.
        if ( 'certificate' === $filter && function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $ids = self::approved_user_ids__premium_only();
            $query->set( 'include', ( $ids ? $ids : array(0) ) );
        }
    }

}
