<?php
/*
Plugin Name: AhaPay Buy Now Pay Later
Description: AhaPay enables users to purchase things they love and pay later. The payment will be split into 4 or 7 instalments automatically. No hidden fees, 0% interest for 4 payment plan.
Version: 1.0.3
Author: AhaPay
Requires Plugins: woocommerce
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: ahapay-buy-now-pay-later
Domain Path:
*/

// =====================
// 1. Security Checks
// =====================
if (!defined('ABSPATH')) {
	exit;
}

if (!function_exists('add_action')) {
    esc_attr_e("Hi there! I'm just a plugin, not much I can do when called directly.", 'ahapay-buy-now-pay-later');
	exit;
}

// =====================
// 2. Constants and Definitions
// =====================
define('AHAPAYBUYNOWPAYLATER_VERSION', '1.0.3');
define('AHAPAYBUYNOWPAYLATER_LIVE_BASE_URL', "https://api.ahapay.my");
define('AHAPAYBUYNOWPAYLATER_SANDBOX_BASE_URL', "https://api.bnpl-my.dev.mychili.id");
define('AHAPAYBUYNOWPAYLATER_PLUGIN_URL', plugin_dir_url(__FILE__));
define('AHAPAYBUYNOWPAYLATER_PLUGIN_DIR', plugin_dir_path(__FILE__));

// =====================
// 3. Class Imports
// =====================
use Ahapaybuynowpaylater\Blocks\Ahapaybuynowpaylater_WC_Blocks_Support;
use Automattic\WooCommerce\Utilities\FeaturesUtil;
use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;

// =====================
// 4. Activation/Deactivation Hooks
// =====================
register_activation_hook(__FILE__, 'ahapaybuynowpaylater_generate_secret_key');

/**
 * Generates a secret key on plugin activation
 */
function ahapaybuynowpaylater_generate_secret_key()
{
    if (!get_option('ahapaybuynowpaylater_secret_key')) {
        $secret_key = wp_generate_password(32, true, true);
        add_option('ahapaybuynowpaylater_secret_key', $secret_key);
    }
}

// =====================
// 5. Plugin Initialization
// =====================
add_action('plugins_loaded', 'ahapaybuynowpaylater_init', 0);

/**
 * Initialize the plugin
 */
function ahapaybuynowpaylater_init()
{
    if (!class_exists('WC_Payment_Gateway')) {
        return;
    }

    // Check dependencies
    if (!ahapaybuynowpaylater_check_dependencies()) {
        return;
    }

    // Include required files
    require_once AHAPAYBUYNOWPAYLATER_PLUGIN_DIR . 'includes/class-ahapay-gateway.php';
    require_once AHAPAYBUYNOWPAYLATER_PLUGIN_DIR . 'includes/class-ahapay-callback-handler.php';
    require_once AHAPAYBUYNOWPAYLATER_PLUGIN_DIR . 'includes/class-ahapay-status-handler.php';

    // Initialize main classes
    Ahapaybuynowpaylater_WC_Gateway::init();

    // Register hooks
    ahapaybuynowpaylater_register_hooks();
}

/**
 * Register all hooks for the plugin
 */
function ahapaybuynowpaylater_register_hooks()
{
    // Register payment gateway
    add_filter('woocommerce_payment_gateways', 'ahapaybuynowpaylater_add_gateway_class', 0);

    // Initialize callback handler
    add_action('init', 'ahapaybuynowpaylater_init_callback_handler');

    // Frontend assets
    add_action('wp_enqueue_scripts', 'ahapaybuynowpaylater_enqueue_scripts');
    add_action('wp_enqueue_scripts', 'ahapaybuynowpaylater_enqueue_styles');

    // Block integration
    add_action('wp_enqueue_scripts', 'ahapaybuynowpaylater_enqueue_block_data');

    // Admin assets
    add_action('admin_enqueue_scripts', 'ahapaybuynowpaylater_admin_enqueue_scripts', 999);

    // Settings link
    add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'ahapaybuynowpaylater_add_plugin_page_settings_link');

    // Checkout minimum amount check
    add_action('woocommerce_before_checkout_form', 'ahapaybuynowpaylater_enqueue_minimum_check_script');

    // Product display features
    add_action('woocommerce_single_product_summary', 'ahapaybuynowpaylater_enqueue_modal_assets');
    add_action('woocommerce_single_product_summary', 'ahapaybuynowpaylater_display_product_popup', 20);
    add_action('woocommerce_single_product_summary', 'ahapaybuynowpaylater_add_image_top_banner', 9);
    add_action('woocommerce_after_shop_loop_item_title', 'ahapaybuynowpaylater_add_custom_shop_badges', 5);

    // AJAX handler
    add_action('wp_ajax_ahapaybuynowpaylater_call_api', 'ahapaybuynowpaylater_handle_api_call');

    // Admin order page
    add_action('woocommerce_admin_order_data_after_order_details', 'ahapaybuynowpaylater_add_check_order_status_button');

    // WooCommerce Blocks compatibility
    add_action('before_woocommerce_init', 'ahapaybuynowpaylater_declare_blocks_compatibility');
    add_filter('woocommerce_blocks_payment_method_data', 'ahapaybuynowpaylater_add_blocks_payment_data', 10, 2);
    add_action('enqueue_block_assets', 'ahapaybuynowpaylater_enqueue_block_styles');
    add_action('wp_enqueue_scripts', 'ahapaybuynowpaylater_enqueue_block_styles', 20);
}

// =====================
// 6. Core Functions
// =====================

/**
 * Check plugin dependencies
 *
 * @return bool True if all dependencies are satisfied
 */
function ahapaybuynowpaylater_check_dependencies()
{
    $dependencies = [
            'WooCommerce' => class_exists('WooCommerce'),
            'OpenSSL' => extension_loaded('openssl')
    ];

    foreach ($dependencies as $name => $satisfied) {
        if (!$satisfied) {
            add_action('admin_notices', function() use ($name) {
                ahapaybuynowpaylater_admin_missing_notice($name);
            });
            deactivate_plugins(plugin_basename(__FILE__));
            return false;
        }
    }
    return true;
}

/**
 * Add AhaPay gateway class to WooCommerce
 *
 * @param array $gateways List of payment gateways
 * @return array Modified list of payment gateways
 */
function ahapaybuynowpaylater_add_gateway_class($gateways)
{
    // Register the new gateway class name; legacy name remains available via class_alias for backward compatibility.
    $gateways[] = 'Ahapaybuynowpaylater_WC_Gateway';
    return $gateways;
}

/**
 * Initialize the AhaPay callback handler
 */
function ahapaybuynowpaylater_init_callback_handler()
{
    new Ahapaybuynowpaylater_Callback_Handler();
}

/**
 * Declare compatibility with WooCommerce blocks
 */
function ahapaybuynowpaylater_declare_blocks_compatibility()
{
    if (class_exists(FeaturesUtil::class)) {
        FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
    }
}

/**
 * Add blocks payment data
 *
 * @param array $data Payment method data
 * @param string $payment_method Payment method name
 * @return array Modified payment method data
 */
function ahapaybuynowpaylater_add_blocks_payment_data($data, $payment_method)
{
    if ($payment_method === 'ahapaybuynowpaylater') {
        $support = new Ahapaybuynowpaylater_WC_Blocks_Support();
        $support->initialize();
        $data['ahapay_data'] = $support->get_payment_method_data();
    }
    return $data;
}

/**
 * Enqueue block styles
 */
function ahapaybuynowpaylater_enqueue_block_styles()
{
    wp_enqueue_style(
            'ahapaybuynowpaylater-block-style',
            AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/css/ahapaybuynowpaylater-block-style.css',
            [],
            AHAPAYBUYNOWPAYLATER_VERSION
    );}

/**
 * Enqueue block data
 */
function ahapaybuynowpaylater_enqueue_block_data()
{
    // Ensure the block script is registered using the build asset if available
    if (!wp_script_is('ahapaybuynowpaylater-block', 'registered')) {
        $asset_path = AHAPAYBUYNOWPAYLATER_PLUGIN_DIR . 'assets/blocks/index.asset.php';
        if (file_exists($asset_path)) {
            $asset = require $asset_path;
            $deps = isset($asset['dependencies']) ? $asset['dependencies'] : array();
            $ver = isset($asset['version']) ? $asset['version'] : filemtime(AHAPAYBUYNOWPAYLATER_PLUGIN_DIR . 'assets/blocks/index.js');
            wp_register_script(
                    'ahapaybuynowpaylater-block',
                    AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/blocks/index.js',
                    $deps,
                    $ver,
                    true
            );
            // Ensure module type if the build expects it
            wp_script_add_data('ahapaybuynowpaylater-block', 'type', 'module');
        }
    }

    wp_localize_script('ahapaybuynowpaylater-block', 'ahapaybuynowpaylater_data', [
            'logoUrl' => AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/images/ahapay-logo.png',
    ]);
    wp_enqueue_script('ahapaybuynowpaylater-block');
}

// =====================
// 7. Frontend Scripts and Styles
// =====================

/**
 * Enqueue frontend scripts
 */
function ahapaybuynowpaylater_enqueue_scripts()
{
    wp_enqueue_script('jquery'); // Ensure jQuery is loaded
    if (is_product() || is_shop()) {
        wp_add_inline_script('jquery', "
        document.addEventListener('DOMContentLoaded', function () {
          const badges = document.querySelectorAll('.custom-overlay-badge');
        
          badges.forEach(badge => {
            const context = badge.dataset.pageContext;
        
            if (context === 'shop') {
              const productCard = badge.closest('li.wc-block-product');
              const imageWrapper = productCard?.querySelector('.wc-block-components-product-image');
        
              if (imageWrapper && !imageWrapper.contains(badge)) {
                imageWrapper.appendChild(badge);
              }
        
            } else if (context === 'single') {
              const imageWrapper = document.querySelector('.woocommerce-product-gallery');
              const saleBadge = imageWrapper?.querySelector('.onsale');
        
              if (imageWrapper && !imageWrapper.contains(badge)) {
                if (saleBadge && saleBadge.parentElement === imageWrapper) {
                  saleBadge.insertAdjacentElement('afterend', badge);
                } else {
                  imageWrapper.appendChild(badge);
                }
              }
            }
          });
        });
        ");
    }

}

/**
 * Enqueue frontend styles
 */
function ahapaybuynowpaylater_enqueue_styles()
{
    wp_enqueue_style('ahapay-label-style', AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/css/ahapay-label.css', [], '1.0.0');

    // Add dynamic inline styles for product labels
    $settings = get_option('woocommerce_ahapaybuynowpaylater_settings');
    if (isset($settings['enabled']) && $settings['enabled'] === 'yes' && isset($settings['enable_product_label']) && $settings['enable_product_label'] === 'yes') {
        $bg_color = $settings['product_label_color'] ?? '#fc642d';
        $text_color = $settings['product_label_text_color'] ?? '#ffffff';

        $custom_css = sprintf(
                '.ahapay-bottom-banner { background-color: %s; color: %s; }',
                esc_attr($bg_color),
                esc_attr($text_color)
        );

        wp_add_inline_style('ahapay-label-style', $custom_css);
    }
}

/**
 * Enqueue minimum amount check script on checkout
 */
function ahapaybuynowpaylater_enqueue_minimum_check_script()
{
    wp_enqueue_script('jquery'); // Ensure jQuery is loaded
    // Get the gateway settings
    $settings = get_option('woocommerce_ahapaybuynowpaylater_settings');
    $minimum_amount = isset($settings['minimum_amount']) ? floatval($settings['minimum_amount']) : 55;
    $disabled = WC()->cart->total < $minimum_amount;
    wp_enqueue_script(
            'ahapay-minimum-check',
            AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/js/ahapay-minimum-check.js',
            ['jquery', 'wc-checkout'],
            AHAPAYBUYNOWPAYLATER_VERSION,
            true
    );

    // Pass data to script
    wp_localize_script('ahapay-minimum-check', 'ahapay_data_minimum', [
            'disabled_message' => __('AhaPay is not available for orders below RM 55', 'ahapay-buy-now-pay-later'),
            'disabled' => $disabled,
    ]);
}

/**
 * Enqueue styles and scripts for the product modal
 */
function ahapaybuynowpaylater_enqueue_modal_assets()
{
    wp_enqueue_script('jquery'); // Ensure jQuery is loaded
    wp_enqueue_style('ahapay-modal-styles', AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/css/modal.css', [], '1.0.0');
    wp_enqueue_script('ahapay-modal-script', AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/js/modal.js', ['jquery'], '1.0.0', true);
}

// =====================
// 8. Admin Scripts and Functions
// =====================

/**
 * Enqueue admin scripts
 *
 * @param string $hook Current admin page hook
 */
function ahapaybuynowpaylater_admin_enqueue_scripts($hook)
{
    wp_enqueue_script('jquery'); // Ensure jQuery is loaded
    if ($hook === 'woocommerce_page_wc-settings' && isset($_GET['tab'], $_GET['section']) && $_GET['tab'] === 'checkout' && $_GET['section'] === 'ahapaybuynowpaylater') {
        wp_add_inline_script('jquery', '
            document.addEventListener("DOMContentLoaded",function(){const input=document.getElementById("woocommerce_ahapaybuynowpaylater_api_key");input.addEventListener("focus",()=>{input.type="text";});input.addEventListener("blur",()=>{input.type="password";});});
        ');
    }

    // Load only on the WooCommerce order edit page
    if ($hook !== 'woocommerce_page_wc-orders') return;

    wp_enqueue_script('ahapaybuynowpaylater-admin-api', AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/js/ahapay-admin-api.js', ['jquery'], AHAPAYBUYNOWPAYLATER_VERSION, true);
    wp_localize_script('ahapaybuynowpaylater-admin-api', 'ahapaybuynowpaylater_api_data', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ahapaybuynowpaylater_api_nonce'),
    ]);

    $custom_css = "
        #ahapay-api-response {
            margin-top: 12px;
            padding: 10px 14px;
            font-weight: 500;
            border-radius: 4px;
            display: inline-block;
            max-width: 100%;
        }
        .ahapay-success {
            background-color: #d1e7dd;
            color: #0f5132;
            border: 1px solid #badbcc;
        }
        .ahapay-error {
            background-color: #f8d7da;
            color: #842029;
            border: 1px solid #f5c2c7;
        }
    ";
    wp_add_inline_style('woocommerce_admin_styles', $custom_css);
}

/**
 * Add settings link on plugins page
 *
 * @param array $links Plugin action links
 * @return array Modified plugin action links
 */
function ahapaybuynowpaylater_add_plugin_page_settings_link($links)
{
    $settings_link = '<a href="' . admin_url('admin.php?page=wc-settings&tab=checkout&section=ahapaybuynowpaylater') . '">' . __('Settings', 'ahapay-buy-now-pay-later') . '</a>';
    array_unshift($links, $settings_link);
    return $links;
}

/**
 * Add button to check order status in admin order details
 *
 * @param WC_Order $order The order object
 */
function ahapaybuynowpaylater_add_check_order_status_button($order)
{
    if (!$order || $order->get_payment_method() !== 'ahapaybuynowpaylater') {
        return;
    }
    $order_id = $order->get_id();
    ?>
    <div class="ahapay-api-wrapper">
        <button class="button button-primary" id="ahapay-api-button" data-order-id="<?php echo esc_attr($order_id); ?>">
            Check AhaPay Order Status
        </button>
        <p id="ahapay-api-response"></p>
    </div>
    <?php
}

/**
 * Admin notice for missing dependencies
 *
 * @param string $reason The missing dependency
 */
function ahapaybuynowpaylater_admin_missing_notice($reason)
{
    echo '<div class="error"><p><strong>AhaPay Payment Gateway</strong> requires ' . esc_html($reason) . ' to be installed and active. The plugin has been deactivated.</p></div>';
}

// =====================
// 9. AJAX and REST API Handlers
// =====================

/**
 * Handle AJAX call to AhaPay API
 */
function ahapaybuynowpaylater_handle_api_call()
{
    check_ajax_referer('ahapaybuynowpaylater_api_nonce', 'nonce');


    $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : '';
    $order = wc_get_order($order_id);

    if (!$order) {
        wp_send_json_error(['message' => 'Invalid order ID']);
    }

    $gateway = new Ahapaybuynowpaylater_WC_Gateway();
    $apiKey = $gateway->get_option('api_key');
    $base_url = $gateway->get_option("environment") === 'sandbox' ? AHAPAYBUYNOWPAYLATER_SANDBOX_BASE_URL : AHAPAYBUYNOWPAYLATER_LIVE_BASE_URL;
    $transaction_id = get_post_meta($order_id, '_ahapaybuynowpaylater_order_id', true);

    // API call for order status
    $response = wp_remote_get($base_url . '/v1/orders/' . $transaction_id . '/status', [
            'headers' => ['Content-Type' => 'application/json', 'X-ApiKey' => $apiKey],
            'timeout' => 15,
    ]);

    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
        wp_send_json_error(['message' => 'API error']);
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);


    if (!(new Ahapaybuynowpaylater_Status_Handler($gateway))->handle_status($order, $data['data']['online_order_status'], $transaction_id)) {
        wp_send_json_error(['message' => 'Error handling status']);
    }

    wp_send_json_success(['message' => 'API call succeeded! Refreshing page...', 'refresh' => true]);
}

/**
 * Send error response with message and status code
 *
 * @param string $message Error message
 * @param int $status_code HTTP status code
 * @return WP_REST_Response
 */
function ahapaybuynowpaylater_send_error_response($message, $status_code)
{
    return wp_send_json([
            'success' => false,
            'message' => $message
    ], $status_code);
}

/**
 * Send success response with order details
 *
 * @param WC_Order $order Order object
 * @param int $order_id Order ID
 * @return WP_REST_Response
 */
function ahapaybuynowpaylater_send_success_response($order, $order_id)
{
    return wp_send_json([
            'success' => true,
            'order_id' => $order_id,
            'status' => $order->get_status(),
            'is_paid' => $order->is_paid(),
            'payment_method' => $order->get_payment_method()
    ]);
}

// Register REST API endpoints
add_action('rest_api_init', function() {
    register_rest_route('ahapaybuynowpaylater/v1', '/check-order-status/(?P<order_id>\d+)', [
            'methods' => 'GET',
            'callback' => 'ahapaybuynowpaylater_check_order_status',
            'permission_callback' => function() {
                return current_user_can('manage_options');
            },
            'args' => [
                    'order_id' => [
                            'validate_callback' => function($param) {
                                return is_numeric($param);
                            }
                    ]
            ]
    ]);

    // Add CORS headers
    add_filter('rest_pre_serve_request', function($served, $result) {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, OPTIONS');
        header('Access-Control-Allow-Credentials: true');
        header('Content-Type: application/json; charset=utf-8');
        return $served;
    }, 10, 2);
});

/**
 * Check the order status via REST API
 *
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function ahapaybuynowpaylater_check_order_status($request)
{
    header('Content-Type: application/json; charset=utf-8');

    try {
        $order_id = (int)$request['order_id'];
        $order = wc_get_order($order_id);

        if (!$order) {
            return ahapaybuynowpaylater_send_error_response('Order not found', 404);
        }

        return ahapaybuynowpaylater_send_success_response($order, $order_id);
    } catch (Exception $e) {
        return ahapaybuynowpaylater_send_error_response($e->getMessage(), 500);
    }
}

// =====================
// 10. Frontend Display Functions
// =====================

/**
 * Display custom shop badges on product listings
 */
function ahapaybuynowpaylater_add_custom_shop_badges()
{
    $settings = get_option('woocommerce_ahapaybuynowpaylater_settings');
    if ($settings['enabled'] == 'no' || $settings['enable_product_label'] == 'no') {
        return;
    }

    $page_context = is_shop() ? 'shop' : 'single';
    $text = $settings['product_label_text'] ?? '0% Installments with AhaPay';

    echo '<div class="custom-overlay-badge" data-page-context="' . esc_attr($page_context) . '">';
    echo '<div class="ahapay-bottom-banner">' . esc_html($text) . '</div>';
    echo '</div>';
}

/**
 * Add image top banner on single product page
 */
function ahapaybuynowpaylater_add_image_top_banner()
{
    $settings = get_option('woocommerce_ahapaybuynowpaylater_settings');

    if ($settings['enabled'] == 'no' || $settings['enable_product_label'] == 'no') return;

    $text = $settings['product_label_text'] ?? '0% Installments with AhaPay';
    $bg_color = $settings['product_label_color'] ?? '#fc642d';
    $text_color = $settings['product_label_text_color'] ?? '#ffffff';

    // Output the banner with a unique ID
    echo '<div id="ahapay-banner-container" class="ahapay-top-image-banner">' . esc_html($text) . '</div>';

    // Inject styling and JavaScript to move the banner to the image container
    $css = '.woocommerce div.product div.images { position: relative !important; } .ahapay-top-image-banner { position: absolute; top: 0; left: 0; width: 60%; background-color: ' . esc_attr($bg_color) . '; color: ' . esc_attr($text_color) . '; text-align: center; padding: 8px 0; font-size: 14px; font-weight: 600; text-transform: uppercase; border-top-left-radius: 6px; border-top-right-radius: 6px; z-index: 10; }';
    wp_register_style('ahapay-banner-inline', false, [], AHAPAYBUYNOWPAYLATER_VERSION);
    wp_enqueue_style('ahapay-banner-inline');
    wp_add_inline_style('ahapay-banner-inline', $css);

    $js = 'document.addEventListener("DOMContentLoaded", function() { const banner = document.getElementById("ahapay-banner-container"); const imageContainer = document.querySelector(".woocommerce-product-gallery"); if (banner && imageContainer) { banner.parentNode.removeChild(banner); imageContainer.insertBefore(banner, imageContainer.firstChild); } });';
    wp_register_script('ahapay-banner-js', false, [], AHAPAYBUYNOWPAYLATER_VERSION, true);
    wp_enqueue_script('ahapay-banner-js');
    wp_add_inline_script('ahapay-banner-js', $js);
}

/**
 * Display product popup on single product page
 */
function ahapaybuynowpaylater_display_product_popup()
{
    global $product;
    $gateway = new Ahapaybuynowpaylater_WC_Gateway();
    if ($gateway->enabled === 'yes' && $gateway->enable_product_payment_info === 'yes') {
        ahapaybuynowpaylater_modal_html($product, $gateway);
    }
}

/**
 * Modal HTML for product page
 *
 * @param WC_Product $product The current product
 * @param Ahapaybuynowpaylater_WC_Gateway $gateway The gateway instance
 */
function ahapaybuynowpaylater_modal_html($product, $gateway)
{
    global $woocommerce;
    $price = (int)$product->get_price();
    $monthly_payment_4 = $price / 4;
    $logo = AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/img/ahapay-logo.svg';
    $cart_icon = AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/img/cart-icon.png';
    $payment_icon = AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/img/payment-icon.png';
    $verification_icon = AHAPAYBUYNOWPAYLATER_PLUGIN_URL . 'assets/img/verification-icon.png';
    ?>
    <div id="ahapay-info">
        <button id="openModalBtn" class="ahapay-payment-button">
            <img src="<?php echo esc_url($logo); ?>" alt="AhaPay" class="ahapay-logo-button"/>
            <span class="ahapay-text"><?php echo esc_html(__("RM", 'ahapay-buy-now-pay-later'));
                echo " ";
                echo esc_html($monthly_payment_4);
                echo esc_html(__(' × 4 payments', 'ahapay-buy-now-pay-later')) ?> </span>
            <span class="ahapay-arrow">›</span>
        </button>

        <!-- Modal -->
        <div id="ahapayModal" class="ahapay-modal">
            <div class="ahapay-modal-content">
                <span class="ahapay-close">&times;</span>
                <img src="<?php echo esc_url($logo); ?>" alt="AhaPay" class="ahapay-logo"/>

                <p class="ahapay-description">
                    <?php echo esc_html(__(' Enjoy smart financial planning and the flexibility of spreading your payments over time, interest-free, and without hidden fees', 'ahapay-buy-now-pay-later')); ?>

                </p>

                <div class="ahapay-steps">
                    <div class="step">
                        <img src="<?php echo esc_url($cart_icon); ?> " alt="basket"/>
                        <p><?php echo esc_html(__('Select your desired product', 'ahapay-buy-now-pay-later')); ?></p>
                    </div>
                    <div class="step">
                        <img src="<?php echo esc_url($verification_icon); ?>" alt="verify"/>
                        <p><?php echo esc_html(__('Complete simple verification', 'ahapay-buy-now-pay-later')); ?></p>
                    </div>
                    <div class="step">
                        <img src="<?php echo esc_url($payment_icon); ?>" alt="confirm"/>
                        <p><?php echo esc_html(__('Confirm your purchase', 'ahapay-buy-now-pay-later')); ?></p>
                    </div>
                </div>

                <button class="ahapay-modal-cta">Got it</button>
                <p class="ahapay-footer">More information you can find on the website <a href="https://ahapay.my"
                                                                                         target="_blank">https://ahapay.my</a>
                </p>
            </div>
        </div>
    </div>
    <?php
}
