<?php

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

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;

final class WC_Advanced_EMT_Blocks_Support extends AbstractPaymentMethodType {

    protected $name = 'advanced_emt';

    public function initialize() {
        // Optionally add setup code here
    }

    public function is_active() {
        $settings = get_option( 'woocommerce_' . $this->name . '_settings', [] );
        return isset( $settings['enabled'] ) && $settings['enabled'] === 'yes';
    }
    public function get_payment_method_script_handles() {

        $handle = 'wc-advanced-emt-blocks';

        $asset_path = plugin_dir_path( __DIR__ ) . 'assets/build/emt-block-v2.asset.php';
        $script_url = plugin_dir_url( __DIR__ ) . 'assets/build/emt-block-v2.js';

        $deps    = array( 'wc-blocks-registry', 'wc-settings', 'wp-element', 'wp-i18n', 'wc-blocks-data-store' );
        $version = time(); // cache-bust so you are 100% not seeing old output

        if ( file_exists( $asset_path ) ) {
            $asset = require $asset_path;

            if ( ! empty( $asset['dependencies'] ) && is_array( $asset['dependencies'] ) ) {
                $deps = array_values( array_unique( array_merge( $deps, $asset['dependencies'] ) ) );
            }

            if ( ! empty( $asset['version'] ) ) {
                // keep cache-bust for now; we can revert after it’s clean
                // $version = $asset['version'];
            }
        }

        wp_register_script(
            $handle,
            $script_url,
            $deps,
            $version,
            true
        );

        // Pass payment method data directly to JS via localization
        $payment_data = $this->get_payment_method_data();
        wp_localize_script( $handle, 'emtBlocksData', $payment_data );

        return array( $handle );
    }

    public function get_payment_method_data() {
        // Checkout block editor previews can execute this before gateways are fully initialized.
        // Return empty data instead of throwing fatal errors in that context.
        if ( ! function_exists( 'WC' ) || ! WC() ) {
            return [];
        }

        $payment_gateways = WC()->payment_gateways();
        if ( ! $payment_gateways || ! method_exists( $payment_gateways, 'payment_gateways' ) ) {
            return [];
        }

        $registered_gateways = $payment_gateways->payment_gateways();
        $gateway = $registered_gateways['advanced_emt'] ?? null;
        if ( ! $gateway ) {
            return [];
        }

        $settings = get_option('woocommerce_' . $this->name . '_settings', []);
        $discount_percent = isset($settings['discount_percent']) ? (float) $settings['discount_percent'] : 0.0;
        $discount_notice = isset($settings['discount_notice']) ? (string) $settings['discount_notice'] : '';

        // Sanitize and limit the notice so accidental text or very long values don't leak to frontend
        $discount_notice = trim( wp_strip_all_tags( $discount_notice ) );
        if ( strlen( $discount_notice ) > 200 ) {
            $discount_notice = function_exists( 'mb_substr' )
                ? mb_substr( $discount_notice, 0, 197 ) . '...'
                : substr( $discount_notice, 0, 197 ) . '...';
        }

        // Build title with logo using plugins_url for proper path resolution
        $logo_url = plugins_url('assets/interac.png', dirname(__DIR__) . '/advanced-emt-payment-gateway.php');
        $title = $gateway->get_option('title');
        
        $notice = '';
        if ( $discount_percent > 0 ) {
            $notice = $discount_notice === ''
                ? sprintf( /* translators: %s is the discount percent */ __( 'Save %s%% when you pay with EMT. (discount applied at checkout)', 'advanced-emt-payment-gateway' ), $discount_percent )
                : str_replace( '[discount]', $discount_percent . '%', $discount_notice );
        }

        return [
            'title' => $title,
            'description' => $gateway->get_option('description'),
            'logoUrl' => $logo_url,
            'discountPercent' => $discount_percent,
            'discountNotice' => $notice,
        ];
    }
}
