<?php
/**
 * Frontend — return button on My Account orders + view-order, links to wizard page,
 * checkout digital-content waiver, and asset enqueue for the wizard / guest form.
 *
 * @package WPNest_Returns_For_WooCommerce
 */

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

class WPNest_RFW_Frontend {

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_filter( 'woocommerce_my_account_my_orders_actions', array( $this, 'add_orders_table_action' ), 20, 2 );
        add_action( 'woocommerce_order_details_after_order_table', array( $this, 'render_view_order_button' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );

        add_action( 'woocommerce_review_order_before_submit', array( $this, 'render_digital_waiver_checkbox' ) );
        add_action( 'woocommerce_checkout_order_processed', array( $this, 'save_digital_waiver_meta' ), 10, 3 );

        // Dorzucamy przycisk „Zwróć to zamówienie" do maili WooCommerce o
        // statusie zamówienia (customer_processing/completed/...) — klient ma
        // wszystko czego potrzebuje do startu zwrotu w jednym mailu.
        add_action( 'woocommerce_email_after_order_table', array( $this, 'render_email_return_cta' ), 20, 4 );
    }

    private function plugin_enabled() {
        return (bool) get_option( 'wpnest_rfw_enabled', 1 );
    }

    private function button_label() {
        $label = trim( (string) get_option( 'wpnest_rfw_button_label', '' ) );
        // Empty value OR the raw English default (legacy default from v1.0.0 activator
        // that never went through gettext) → use the translated default. This makes
        // the fallback idempotent without relying on the one-shot migration in
        // class-upgrade.php — even if an old install stored "Return this order" as
        // a literal, the email/My Account button picks up the PL translation.
        if ( '' === $label || 'Return this order' === $label ) {
            return __( 'Return this order', 'wpnest-returns-for-woocommerce' );
        }
        return $label;
    }

    /**
     * URL to the wizard page for a given order — uses the auto-created /returns/ page.
     */
    private function wizard_url( $order_id ) {
        $page_id = (int) get_option( 'wpnest_rfw_page_id', 0 );
        $base    = $page_id ? get_permalink( $page_id ) : home_url( '/' );
        return add_query_arg( 'order', (int) $order_id, $base );
    }

    public function add_orders_table_action( $actions, $order ) {
        if ( ! $this->plugin_enabled() || ! $order instanceof WC_Order ) {
            return $actions;
        }
        if ( ! get_option( 'wpnest_rfw_show_on_my_account', 1 ) ) {
            return $actions;
        }
        $order_id = (int) $order->get_id();
        if ( ! WPNest_RFW_Eligibility::is_eligible( $order_id ) ) {
            return $actions;
        }
        $actions['wpnest_rfw_return'] = array(
            'url'  => esc_url( $this->wizard_url( $order_id ) ),
            'name' => $this->button_label(),
        );
        return $actions;
    }

    public function render_view_order_button( $order ) {
        if ( ! $this->plugin_enabled() || ! $order instanceof WC_Order ) {
            return;
        }
        if ( ! get_option( 'wpnest_rfw_show_on_view_order', 1 ) ) {
            return;
        }
        $order_id = (int) $order->get_id();

        // Idempotency guard — `woocommerce_order_details_after_order_table`
        // can fire twice on the same view-order page when the theme overrides
        // `order/order-details.php` and re-invokes the action. Render at most
        // once per (request × order).
        static $rendered = array();
        if ( isset( $rendered[ $order_id ] ) ) {
            return;
        }
        $rendered[ $order_id ] = true;

        if ( ! WPNest_RFW_Eligibility::is_eligible( $order_id ) ) {
            return;
        }
        ?>
        <p class="wpnest-rfw-view-order-action">
            <a href="<?php echo esc_url( $this->wizard_url( $order_id ) ); ?>" class="button wpnest-rfw-btn">
                <?php echo esc_html( $this->button_label() ); ?>
            </a>
        </p>
        <?php
    }

    /**
     * Adds a "Return this order" CTA to WooCommerce customer emails (order
     * confirmation, processing, completed, on-hold). Skipped for refund /
     * cancellation emails (`$sent_to_admin === true` lub status w wykluczonych).
     *
     * Filter `wpnest_rfw_email_show_return_cta` pozwala wyłączyć dla konkretnego
     * mail/typ (np. tylko dla `customer_completed`).
     *
     * @param WC_Order $order
     * @param bool     $sent_to_admin
     * @param bool     $plain_text
     * @param WC_Email $email
     */
    public function render_email_return_cta( $order, $sent_to_admin, $plain_text, $email ) {
        if ( ! $this->plugin_enabled() || ! $order instanceof WC_Order ) {
            return;
        }
        if ( $sent_to_admin ) {
            return; // admin emails — no customer CTA
        }
        $order_id = (int) $order->get_id();
        if ( ! WPNest_RFW_Eligibility::is_eligible( $order_id ) ) {
            return;
        }

        /**
         * @param bool     $show
         * @param WC_Order $order
         * @param WC_Email $email
         */
        $show = apply_filters( 'wpnest_rfw_email_show_return_cta', true, $order, $email );
        if ( ! $show ) {
            return;
        }

        // URL w mailu dodaje token HMAC — gość kliknie i ląduje od razu w
        // wizardzie (bez wpisywania email + numeru zamówienia). Zalogowany
        // owner i tak by przeszedł przez standardową gałąź `?order=ID`.
        $base_url = $this->wizard_url( $order_id );
        $url      = add_query_arg(
            't',
            WPNest_RFW_Email_Token::make( $order_id ),
            $base_url
        );
        $label = $this->button_label();

        if ( $plain_text ) {
            echo "\n" . esc_html( $label ) . ":\n" . esc_url_raw( $url ) . "\n\n";
            return;
        }

        // HTML email — table-based dla Outlook/Gmail compatibility.
        ?>
        <table cellspacing="0" cellpadding="0" border="0" style="margin:20px 0 24px;width:100%">
            <tr><td>
                <a href="<?php echo esc_url( $url ); ?>"
                   style="display:inline-block;background:#1d4ed8;color:#ffffff;padding:12px 22px;border-radius:6px;text-decoration:none;font-weight:600;font-size:15px">
                    <?php echo esc_html( $label ); ?> →
                </a>
            </td></tr>
            <tr><td style="padding-top:8px;color:#64748b;font-size:13px">
                <?php esc_html_e( 'Jeżeli chcesz zwrócić to zamówienie, kliknij przycisk powyżej — to zajmie około 60 sekund.', 'wpnest-returns-for-woocommerce' ); ?>
            </td></tr>
        </table>
        <?php
    }

    public function enqueue_assets() {
        $page_id     = (int) get_option( 'wpnest_rfw_page_id', 0 );
        $on_returns  = ( $page_id > 0 && is_page( $page_id ) );
        // We enqueue only on the returns page now — the wizard + guest verify both live there.
        if ( ! $on_returns ) {
            return;
        }

        wp_enqueue_style(
            'wpnest-rfw-frontend',
            WPNEST_RFW_PLUGIN_URL . 'assets/css/frontend.css',
            array(),
            WPNEST_RFW_VERSION
        );

        wp_enqueue_script(
            'wpnest-rfw-frontend',
            WPNEST_RFW_PLUGIN_URL . 'assets/js/frontend.js',
            array( 'jquery' ),
            WPNEST_RFW_VERSION,
            true
        );

        wp_localize_script(
            'wpnest-rfw-frontend',
            'wpnest_rfw',
            array(
                'rest_url' => esc_url_raw( rest_url( 'wpnest-rfw/v1' ) ),
                'nonce'    => wp_create_nonce( 'wp_rest' ),
                'i18n'     => array(
                    'select_at_least_one' => __( 'Please select at least one item to return.', 'wpnest-returns-for-woocommerce' ),
                    'pick_reason'         => __( 'Please choose a reason for every item.', 'wpnest-returns-for-woocommerce' ),
                    'reason_text_required' => __( 'Please add details for the items where "Other" is selected.', 'wpnest-returns-for-woocommerce' ),
                    'must_confirm'        => __( 'Please confirm the statement before submitting.', 'wpnest-returns-for-woocommerce' ),
                    'submitting'          => __( 'Submitting…', 'wpnest-returns-for-woocommerce' ),
                    'success'             => __( 'Your return request has been received. Check your email for confirmation.', 'wpnest-returns-for-woocommerce' ),
                    'error'               => __( 'Could not submit the return request. Please try again.', 'wpnest-returns-for-woocommerce' ),
                    'qty_label'           => __( 'Qty', 'wpnest-returns-for-woocommerce' ),
                    'reason_label'        => __( 'Reason', 'wpnest-returns-for-woocommerce' ),
                ),
            )
        );
    }

    public function render_digital_waiver_checkbox() {
        if ( ! get_option( 'wpnest_rfw_exclude_digital_with_waiver', 1 ) ) {
            return;
        }
        if ( ! $this->cart_is_fully_digital() ) {
            return;
        }
        ?>
        <p class="form-row wpnest-rfw-digital-consent">
            <label class="wpnest-rfw-check">
                <input type="checkbox" name="wpnest_rfw_digital_consent" value="1">
                <span><?php esc_html_e( 'I agree to the immediate delivery of digital content and acknowledge that I lose my right of return upon delivery.', 'wpnest-returns-for-woocommerce' ); ?></span>
            </label>
        </p>
        <?php
    }

    public function save_digital_waiver_meta( $order_id, $posted_data, $order ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- WC handles checkout nonce upstream.
        if ( empty( $_POST['wpnest_rfw_digital_consent'] ) ) {
            return;
        }
        if ( ! $order instanceof WC_Order ) {
            $order = wc_get_order( $order_id );
        }
        if ( $order instanceof WC_Order ) {
            $order->update_meta_data( '_wpnest_rfw_digital_waiver', 1 );
            $order->save_meta_data();
        }
    }

    private function cart_is_fully_digital() {
        if ( ! function_exists( 'WC' ) || ! WC()->cart || WC()->cart->is_empty() ) {
            return false;
        }
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            $product = isset( $cart_item['data'] ) ? $cart_item['data'] : null;
            if ( ! $product || ( ! $product->is_downloadable() && ! $product->is_virtual() ) ) {
                return false;
            }
        }
        return true;
    }
}
