<?php

defined( 'ABSPATH' ) || exit;
/**
 * Tax Exemption section on the WordPress user profile edit screen.
 *
 * FREE:  Tri-state exemption override (follow role rules / always / never) + note.
 * PRO:   Status badge + link to review queue. All management via queue.
 */
class Rankd_Tx_User_Profile {
    public static function init() {
        add_action( 'show_user_profile', array(__CLASS__, 'render_field') );
        add_action( 'edit_user_profile', array(__CLASS__, 'render_field') );
        add_action( 'personal_options_update', array(__CLASS__, 'save_field') );
        add_action( 'edit_user_profile_update', array(__CLASS__, 'save_field') );
    }

    // -------------------------------------------------------------------------
    // Render
    // -------------------------------------------------------------------------
    public static function render_field( WP_User $user ) {
        if ( !Rankd_Tx_Capabilities::is_in_scope( $user ) ) {
            return;
        }
        // VIEW is open to anyone who can open this profile screen at all
        // (WordPress already requires user-editing rights for that). Only
        // CHANGING exemption data requires the management capability — the
        // controls below render disabled for viewers, and save_field
        // independently re-enforces the same check server-side regardless
        // of what the markup shows.
        if ( !Rankd_Tx_Capabilities::current_user_can_view() ) {
            return;
        }
        $can_edit = Rankd_Tx_Capabilities::current_user_can_edit();
        echo '<h2>' . esc_html__( 'Tax Exemption', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</h2>';
        if ( !$can_edit ) {
            echo '<p class="description">' . esc_html__( 'Read-only — you do not have permission to change tax exemption data.', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</p>';
        }
        echo '<table class="form-table" role="presentation">';
        // Standalone premium block (no else) — Freemius strips the whole
        // block from the free build, leaving $rendered_pro false so the
        // free field renders.
        $rendered_pro = false;
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            self::render_pro__premium_only( $user, $can_edit );
            $rendered_pro = true;
        }
        if ( !$rendered_pro ) {
            self::render_free( $user, $can_edit );
        }
        echo '</table>';
    }

    // -------------------------------------------------------------------------
    // Shared: tri-state override select
    // -------------------------------------------------------------------------
    /**
     * Renders the Exemption Override select row (both tiers).
     *
     * @param WP_User $user
     * @param string  $description Raw (unescaped) description text — escaped here on output.
     */
    private static function render_override_select( WP_User $user, $description, $can_edit = true ) {
        $override = Rankd_Tx_Capabilities::get_override( $user->ID );
        $options = array(
            ''       => __( 'Follow role rules (default)', 'rankd-tax-exemption-certificates-for-woocommerce' ),
            'always' => __( 'Always exempt', 'rankd-tax-exemption-certificates-for-woocommerce' ),
            'never'  => __( 'Never exempt', 'rankd-tax-exemption-certificates-for-woocommerce' ),
        );
        echo '<tr>';
        echo '<th scope="row"><label for="rankd_tx_override">' . esc_html__( 'Tax Exemption Override', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</label></th>';
        echo '<td>';
        echo '<select name="rankd_tx_override" id="rankd_tx_override"' . (( $can_edit ? '' : ' disabled="disabled"' )) . '>';
        foreach ( $options as $value => $label ) {
            echo '<option value="' . esc_attr( $value ) . '" ' . selected( $override, $value, false ) . '>' . esc_html( $label ) . '</option>';
        }
        echo '</select>';
        echo '<p class="description">' . esc_html( $description ) . '</p>';
        echo '</td>';
        echo '</tr>';
    }

    // -------------------------------------------------------------------------
    // FREE: Override select + note
    // -------------------------------------------------------------------------
    private static function render_free( WP_User $user, $can_edit = true ) {
        $note = (string) get_user_meta( $user->ID, RANKD_TX_META_NOTE, true );
        wp_nonce_field( 'rankd_tx_save_profile_' . $user->ID, 'rankd_tx_profile_nonce' );
        self::render_override_select( $user, __( 'Follow role rules: exempt only when the user holds a Tax-Exempt Role (WooCommerce → Settings → Tax Exemption). Always: tax is removed from this customer\'s orders regardless of role. Never: this plugin will not exempt this user at all, even if their role is tax exempt. Takes effect on their next page load.', 'rankd-tax-exemption-certificates-for-woocommerce' ), $can_edit );
        echo '<tr>';
        echo '<th scope="row"><label for="rankd_tx_exempt_note">' . esc_html__( 'Internal Note', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</label></th>';
        echo '<td>';
        echo '<input type="text" name="rankd_tx_exempt_note" id="rankd_tx_exempt_note" value="' . esc_attr( $note ) . '" class="regular-text" placeholder="' . esc_attr__( 'e.g. 501(c)(3) Non-Profit — exemption cert on file', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '"' . (( $can_edit ? '' : ' disabled="disabled"' )) . ' />';
        echo '<p class="description">' . esc_html__( 'Internal reference only. Not visible to the customer.', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</p>';
        echo '</td>';
        echo '</tr>';
        // Upgrade notice.
        echo '<tr>';
        echo '<th></th>';
        echo '<td>';
        echo '<p class="description" style="margin-top:8px;">';
        echo esc_html__( 'Upgrade to Pro for certificate upload, approval workflow, expiry tracking, and full audit log.', 'rankd-tax-exemption-certificates-for-woocommerce' );
        echo '</p>';
        echo '</td>';
        echo '</tr>';
    }

    // -------------------------------------------------------------------------
    // Save (free tier only — pro manages via review queue)
    // -------------------------------------------------------------------------
    public static function save_field( $user_id ) {
        // The admin toggle is an independent exemption source in BOTH tiers.
        // (Previously Pro skipped this save entirely, which made toggle-only
        // exemptions impossible to set or clear after upgrading to Pro.)
        if ( !Rankd_Tx_Capabilities::is_in_scope( $user_id ) ) {
            return;
        }
        if ( !Rankd_Tx_Capabilities::current_user_can_edit() ) {
            return;
        }
        if ( !isset( $_POST['rankd_tx_profile_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['rankd_tx_profile_nonce'] ) ), 'rankd_tx_save_profile_' . $user_id ) ) {
            return;
        }
        $previous = Rankd_Tx_Capabilities::get_override( $user_id );
        $override = sanitize_key( wp_unslash( $_POST['rankd_tx_override'] ?? '' ) );
        if ( !in_array( $override, array('', 'always', 'never'), true ) ) {
            $override = '';
        }
        Rankd_Tx_Capabilities::set_override( $user_id, $override );
        $note = sanitize_text_field( wp_unslash( $_POST['rankd_tx_exempt_note'] ?? '' ) );
        update_user_meta( $user_id, RANKD_TX_META_NOTE, $note );
        Rankd_Tx_Exemption::bust_cache( $user_id );
        if ( $override !== $previous ) {
            $actions = array(
                'always' => 'admin_toggle_enabled',
                'never'  => 'override_never_set',
                ''       => 'override_cleared',
            );
            Rankd_Tx_Audit::log(
                $user_id,
                0,
                $actions[$override],
                get_current_user_id(),
                $note
            );
        }
    }

}
