<?php
/**
 * Plugin Name:         ManiPay Manual Payment Gateway for FluentCart
 * Description:         A manual payment gateway for FluentCart: Mobile Banking (bKash, Nagad, Rocket), Bank Transfer with slip upload, and Crypto (RedotPay). Customers complete payment on a dedicated on-site page; orders stay Pending until you verify the Transaction ID.
 * Version:             1.0.10
 * Author:              pxelcode
 * License:             GPL v2 or later
 * License URI:         https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:         manipay-manual-payment-for-fluentcart
 * Requires at least:   5.6
 * Requires PHP:        7.4
 *
 * @package ManiPay\FluentCart
 */

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

define( 'MANIPAY_FC_FILE', __FILE__ );
define( 'MANIPAY_FC_DIR', plugin_dir_path( __FILE__ ) );
define( 'MANIPAY_FC_URL', plugin_dir_url( __FILE__ ) );
define( 'MANIPAY_FC_VERSION', '1.0.10' );

/**
 * Lightweight PSR-4 autoloader for the ManiPay\FluentCart\ namespace.
 */
spl_autoload_register(
    function ( $class ) {
        $prefix = 'ManiPay\\FluentCart\\';
        if ( 0 !== strpos( $class, $prefix ) ) {
            return;
        }
        $relative = substr( $class, strlen( $prefix ) );
        $path     = MANIPAY_FC_DIR . 'src/' . str_replace( '\\', '/', $relative ) . '.php';
        if ( file_exists( $path ) ) {
            require $path;
        }
    }
);

/**
 * Register the gateway once FluentCart is ready. This is FluentCart's
 * documented, recommended registration hook (rather than 'init').
 */
add_action( 'fluent_cart/register_payment_methods', function () {
    if ( ! function_exists( 'fluent_cart_api' ) ) {
        return;
    }
    fluent_cart_api()->registerCustomPaymentMethod(
        'pxelcode_pay',
        new \ManiPay\FluentCart\Gateway()
    );
} );

/**
 * Show a notice if FluentCart itself isn't active — registration above is a
 * no-op in that case, but a clear notice is more useful than silent failure.
 */
add_action( 'admin_init', function () {
    if ( function_exists( 'fluent_cart_api' ) ) {
        return;
    }
    add_action( 'admin_notices', function () {
        echo '<div class="notice notice-error"><p>' .
            esc_html__( 'ManiPay Manual Payment Gateway for FluentCart requires FluentCart to be installed and activated.', 'manipay-manual-payment-for-fluentcart' ) .
            '</p></div>';
    } );
} );

/**
 * Boot the standalone on-site payment page handler (independent of the
 * gateway lifecycle so it works even before FluentCart finishes loading).
 */
add_action( 'plugins_loaded', function () {
    if ( class_exists( \ManiPay\FluentCart\PaymentPage::class ) ) {
        \ManiPay\FluentCart\PaymentPage::boot();
    }
} );

/**
 * FluentCart's settings screen computes which fields to show (bank/crypto
 * detail fields) server-side in Gateway::fields() each time it's loaded,
 * but doesn't re-fetch that list after a save completes — so newly-relevant
 * fields only appear after a manual page refresh. This automates that: after
 * clicking "Save Settings" anywhere in FluentCart's admin (a Vue single-page
 * app, so the URL alone can't be used to scope this to just the payment
 * settings screen), the page reloads on its own once the save request has
 * had time to complete.
 */
/**
 * FluentCart's settings screen computes which fields to show (bank/crypto
 * detail fields) server-side in Gateway::fields() each time it's loaded, but
 * doesn't re-fetch that list after a save completes — so newly-relevant
 * fields only appear after a manual page refresh. This automates that: after
 * clicking "Save Settings" anywhere in FluentCart's admin (a Vue single-page
 * app, so the URL alone can't be used to scope this to just the payment
 * settings screen), the page reloads on its own once the save request has
 * had time to complete.
 *
 * Registered as a proper (empty-src) script handle and attached via
 * wp_add_inline_script(), per WordPress's recommended enqueuing approach,
 * rather than a raw <script> tag.
 */
add_action( 'admin_enqueue_scripts', function () {
    if ( empty( $_GET['page'] ) || 0 !== strpos( (string) $_GET['page'], 'fluent-cart' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        return;
    }

    wp_register_script( 'manipay-fc-admin-reload', '', array(), MANIPAY_FC_VERSION, true );
    wp_enqueue_script( 'manipay-fc-admin-reload' );
    wp_add_inline_script(
        'manipay-fc-admin-reload',
        "(function () {
            document.addEventListener('click', function (e) {
                var el = e.target.closest('button, [role=\"button\"], a');
                if (!el) return;
                var text = (el.textContent || '').replace(/\\s+/g, ' ').trim();
                if (text === 'Save Settings') {
                    setTimeout(function () { window.location.reload(); }, 1500);
                }
            }, true);
        })();"
    );
} );
