<?php

defined( 'ABSPATH' ) || exit;
/**
 * WooCommerce settings tab: WooCommerce > Tax Exemption
 */
class Rankd_Tx_Settings_Page extends WC_Settings_Page {
    public function __construct() {
        $this->id = 'rankd-tx-settings';
        $this->label = __( 'Tax Exempt Certs', 'rankd-tax-exemption-certificates-for-woocommerce' );
        parent::__construct();
        // The settings tab is management-only — hide it from the WC
        // settings nav entirely for view-only users (shop staff outside
        // the "Who Can Manage Exemptions" setting), rather than showing
        // a tab that just dead-ends.
        add_filter( 'woocommerce_settings_tabs_array', array($this, 'maybe_hide_tab'), 100 );
    }

    /**
     * Removes this tab from the WC settings nav for anyone who can view
     * but not manage. Direct URL access is still separately blocked in
     * output() below — this only controls the nav link's visibility.
     *
     * @param  string[] $tabs
     * @return string[]
     */
    public function maybe_hide_tab( $tabs ) {
        if ( !Rankd_Tx_Capabilities::current_user_can_edit() && isset( $tabs[$this->id] ) ) {
            unset($tabs[$this->id]);
        }
        return $tabs;
    }

    public function get_settings( $current_section = '' ) {
        $all_roles = Rankd_Tx_Capabilities::get_all_roles();
        // Tier-aware description: free users have no certificates, so the
        // free wording lists only the data a free install actually holds.
        // Tier-aware description: in Pro, role membership alone is not
        // enough — evidence (certificate or recorded override) is required.
        $exempt_roles_desc = __( 'Users holding ANY of these roles are automatically tax exempt in all jurisdictions. Individual users can be excluded (or included) via the Tax Exemption Override on their profile.', 'rankd-tax-exemption-certificates-for-woocommerce' );
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $exempt_roles_desc = $this->get_exempt_roles_desc__premium_only();
        }
        $uninstall_desc = __( 'Permanently delete all exemption data (admin overrides, order records, audit log, and settings) when this plugin is uninstalled from the Plugins screen.', 'rankd-tax-exemption-certificates-for-woocommerce' );
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $uninstall_desc = $this->get_uninstall_desc__premium_only();
        }
        // Build role checkboxes as a custom field — handled via save override below.
        $role_options = array();
        foreach ( $all_roles as $slug => $label ) {
            $role_options[$slug] = esc_html( $label );
        }
        $settings = array(
            array(
                'title' => __( 'Tax Exemption Settings', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                'type'  => 'title',
                'id'    => 'rankd_tx_settings_section',
            ),
            array(
                'title'   => __( 'Tax-Exempt Roles', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                'desc'    => $exempt_roles_desc,
                'id'      => 'rankd_tx_exempt_roles',
                'type'    => 'multiselect',
                'class'   => 'wc-enhanced-select',
                'options' => $role_options,
                'default' => array(),
            ),
            array(
                'title'   => __( 'Who Can Manage Exemptions', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                'desc'    => __( 'Roles allowed to CHANGE tax exemption data: profile overrides, adding/approving/rejecting/revoking certificates, exports, and this settings page. Roles not selected keep read-only access — they can still view the review queue, statuses, and profile exemption info, but every control is locked. Administrators always retain full access and cannot be removed. A role also still needs its normal WordPress permissions to reach a given screen (for example, editing another user\'s profile requires the ability to edit users).', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                'id'      => 'rankd_tx_editor_roles',
                'type'    => 'multiselect',
                'class'   => 'wc-enhanced-select',
                'options' => $role_options,
                'default' => array('administrator', 'shop_manager'),
            ),
            array(
                'title'    => __( 'Remove Data on Uninstall', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                'desc'     => $uninstall_desc,
                'desc_tip' => __( 'Off by default. Deactivating the plugin never removes data — this only applies when you click "Delete" after deactivating. Leave this off if you may reinstall later or need the audit trail for compliance.', 'rankd-tax-exemption-certificates-for-woocommerce' ),
                'id'       => 'rankd_tx_delete_data_on_uninstall',
                'type'     => 'checkbox',
                'default'  => 'no',
            ),
            // (Pro fields are merged in below — see get_pro_settings__premium_only.)
            array(
                'type' => 'sectionend',
                'id'   => 'rankd_tx_settings_section',
            ),
        );
        // PRO: settings consumed only by the certificate workflow (expiry
        // warnings, notification emails, grace period, file retention).
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $settings = $this->insert_pro_settings__premium_only( $settings );
        }
        return apply_filters( 'rankd_tx_settings', $settings );
    }

    public function output() {
        if ( !Rankd_Tx_Capabilities::current_user_can_edit() ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'rankd-tax-exemption-certificates-for-woocommerce' ) );
        }
        $queue_url = admin_url( 'admin.php?page=rankd-tx-review-queue' );
        // Use Freemius's own URL builder rather than the bare parent slug —
        // that page now redirects to this settings tab by default (see
        // Rankd_Tx_Admin::render_settings_redirect()), so it can no longer
        // double as the license-activation entry point. get_account_url()
        // is the SDK's documented method for the Account page, which
        // handles license activation directly.
        $account_url = ( function_exists( 'rankd_tx_fs' ) ? rankd_tx_fs()->get_account_url() : admin_url( 'admin.php?page=rankd-tx-settings-account' ) );
        // Standard Freemius brace-block so the check is stripped cleanly
        // from the free build.
        $is_pro = false;
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $is_pro = true;
        }
        // Nav links row — queue link only where the queue page exists (Pro);
        // license activation link shown for free users.
        echo '<div style="margin:12px 0 4px;display:flex;gap:16px;align-items:center;">';
        if ( $is_pro ) {
            echo '<a href="' . esc_url( $queue_url ) . '">' . esc_html__( '← Certificate Review Queue', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</a>';
        } else {
            echo '<a href="' . esc_url( $account_url ) . '">' . esc_html__( 'Have a license key? Activate it here →', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</a>';
        }
        echo '</div>';
        // Upgrade notice for free tier users.
        if ( !$is_pro ) {
            $upgrade_url = ( function_exists( 'rankd_tx_fs' ) ? rankd_tx_fs()->get_upgrade_url() : '#' );
            echo '<div style="background:#fff;border:1px solid #2271b1;border-left:4px solid #2271b1;padding:12px 16px;margin:16px 0;display:flex;align-items:center;justify-content:space-between;">';
            echo '<div>';
            echo '<strong>' . esc_html__( 'Upgrade to Pro', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</strong>';
            echo '<p style="margin:4px 0 0;">' . esc_html__( 'Unlock certificate submission, approval workflow, expiry enforcement, email notifications, dashboard widget, and CSV exports.', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</p>';
            echo '</div>';
            echo '<a href="' . esc_url( $upgrade_url ) . '" target="_blank" class="button button-primary" style="white-space:nowrap;margin-left:16px;">' . esc_html__( 'Upgrade to Pro →', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</a>';
            echo '</div>';
        }
        // PRO: "show the Nginx notice again" link — the notice concerns
        // uploaded certificate documents, which only exist in Pro.
        if ( function_exists( 'rankd_tx_fs' ) && rankd_tx_fs()->can_use_premium_code__premium_only() ) {
            $this->render_nginx_link__premium_only();
        }
        parent::output();
        // Compatibility note — plain-language lead, technical detail folded
        // in smaller underneath for anyone who wants it. Placed after the
        // fields so it reads as troubleshooting help, not an upfront warning.
        echo '<div style="background:#f6f7f7;border:1px solid #dcdcde;border-left:3px solid #dcdcde;padding:10px 14px;margin:20px 0 8px;font-size:13px;">' . '<strong>' . esc_html__( 'Having trouble?', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</strong> ' . esc_html__( "If your settings above look correct but a customer's tax exemption still isn't applying, another plugin on your site may be managing tax exemption in a way that conflicts with this one.", 'rankd-tax-exemption-certificates-for-woocommerce' ) . ' <a href="https://rankd.site/plugins-from-rankd-site/tax-exempt-certificate-manager-for-woocommerce/" target="_blank">' . esc_html__( 'Learn more →', 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</a>' . '<br><span style="color:#646970;">' . esc_html__( "(Technical detail: this can happen when another plugin sets WooCommerce's tax-exempt status directly instead of going through the standard filter this plugin listens for.)", 'rankd-tax-exemption-certificates-for-woocommerce' ) . '</span>' . '</div>';
    }

}
