<?php
/**
 * Plugin Name: Startbutton for WooCommerce
 * Plugin URI: https://startbutton.africa
 * Description: Startbutton payment gateway for WooCommerce.
 * Version: 1.1.9
 * Author: Sommysab
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 * Requires Plugins: woocommerce
 * Requires at least: 6.2
 * Requires PHP: 7.4
 * WC requires at least: 8.0
 * WC tested up to: 9.1
 */

use Automattic\WooCommerce\Admin\Notes\Note;
use Automattic\WooCommerce\Admin\Notes\Notes;

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

define( 'STARTBUTTON_WC_FILE', __FILE__ );
define( 'STARTBUTTON_WC_URL', untrailingslashit( plugins_url( '/', __FILE__ ) ) );
define( 'STARTBUTTON_WC_SITE_URL', 'https://startbutton.africa');
define( 'STARTBUTTON_WC_API_URL', [
  'test' => 'https://api-dev.startbutton.tech',
  'prod' => 'https://api.startbutton.tech',
]);
define( 'STARTBUTTON_WC_VERSION', '1.1.9' );

/**
 * Initialize Startbutton WooCommerce payment gateway.
 */
function startbutton_wc_init_gateway_class() {

	if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
		add_action( 'admin_notices', 'startbutton_wc_missing_notice' );
		return;
	}

	add_action( 'admin_init', 'startbutton_wc_testmode_notice' );

	require_once __DIR__ . '/includes/class-wc-gateway-startbutton.php';

	add_filter( 'woocommerce_payment_gateways', 'startbutton_wc_add_gateway_class', 99 );
	add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'startbutton_wc_plugin_action_links' );
  add_action( 'woocommerce_admin_order_data_after_order_details', 'startbutton_wc_add_txn_details_to_admin_order_page' );
  add_action( 'woocommerce_order_details_after_order_table', 'startbutton_wc_add_txn_details_to_customer_order_page' );

}
add_action( 'plugins_loaded', 'startbutton_wc_init_gateway_class', 99 );

/**
 * Add Settings link to the plugin entry in the plugins menu.
 *
 * @param array $links Plugin action links.
 *
 * @return array
 **/
function startbutton_wc_plugin_action_links( $links ) {

	$settings_link = array(
		'settings' => '<a href="' . esc_url(admin_url( 'admin.php?page=wc-settings&tab=checkout&section=startbutton' )) . '" title="View Startbutton WooCommerce Settings">Settings</a>',
	);

	return array_merge( $settings_link, $links );

}

/**
 * Add Startbutton Gateway to WooCommerce.
 *
 * @param array $methods WooCommerce payment gateways methods.
 *
 * @return array
 */
function startbutton_wc_add_gateway_class( $methods ) {
	$methods[] = 'Startbutton_WC_Payment_Gateway';

	return $methods;

}

/**
 * Display a notice if WooCommerce is not installed
 */
function startbutton_wc_missing_notice() {
	echo '<div class="error"><p><strong>' . sprintf( 'Startbutton requires WooCommerce to be installed and active. Click %s to install WooCommerce.', '<a href="' . esc_url( admin_url( 'plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true&width=772&height=539' ) ) . '" class="thickbox open-plugin-details-modal">here</a>' ) . '</strong></p></div>';
}

/**
 * Display the test mode notice.
 **/
function startbutton_wc_testmode_notice() {
    
	if ( ! class_exists( Notes::class ) ) {
		return;
	}
    
	if ( ! class_exists( WC_Data_Store::class ) ) {
		return;
	}
    
	if ( ! method_exists( Notes::class, 'get_note_by_name' ) ) {
		return;
	}

	$test_mode_note = Notes::get_note_by_name( 'startbutton-sandbox-mode' );
    
	if ( false === $test_mode_note ) {
		return;
	}

	$startbutton_settings = get_option( 'woocommerce_startbutton_settings' );
	$test_mode         = $startbutton_settings['environment'] ?? '';
    
	if ( 'test' !== $test_mode ) {
		Notes::delete_notes_with_name( 'startbutton-sandbox-mode' );

		return;
	}
    
	$note = new Note();
	$note->set_title( 'Startbutton sandbox mode enabled');
	$note->set_content( 'Startbutton sandox mode is currently enabled. Remember to change the environment when you want to start accepting live payment on your site.' );
	$note->set_type( Note::E_WC_ADMIN_NOTE_INFORMATIONAL );
	$note->set_layout( 'plain' );
	$note->set_is_snoozable( false );
	$note->set_name( 'startbutton-sandbox-mode' );
	$note->set_source( 'woo-startbutton' );
	$note->add_action( 'disable-startbutton-sandbox-mode', 'Disable Startbutton test mode', admin_url( 'admin.php?page=wc-settings&tab=checkout&section=startbutton' ));
	$note->save();
}

add_action(
	'before_woocommerce_init',
	function () {
		if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
		}
	}
);

/**
 * Registers WooCommerce Blocks integration.
 */
function startbutton_wc_woocommerce_block_support() {
	if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
		require_once __DIR__ . '/includes/class-wc-gateway-startbutton-blocks-support.php';
		add_action(
			'woocommerce_blocks_payment_method_type_registration',
			static function( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
				$payment_method_registry->register( new Startbutton_WC_Gateway_Blocks_Support() );
			}
		);
	}
}
add_action( 'woocommerce_blocks_loaded', 'startbutton_wc_woocommerce_block_support' );


/**
 * Ensure payment gateways (including Startbutton) are instantiated early so
 * their enqueue hooks are registered before wp_enqueue_scripts fires.
 */
function startbutton_wc_prime_gateways_early() {
    // If enqueuing has already started, skip.
    if ( did_action( 'wp_enqueue_scripts' ) ) {
        return;
    }

    if ( function_exists( 'WC' ) && class_exists( 'WC_Payment_Gateway' ) ) {
        // This initializes and registers gateways early.
        if ( WC() && method_exists( WC(), 'payment_gateways' ) ) {
            WC()->payment_gateways();
        }
    }
}
add_action( 'init', 'startbutton_wc_prime_gateways_early', 5 );


function startbutton_wc_add_txn_details_to_admin_order_page( $order ) {
    
    $txn_ref = $order->get_meta( '_startbutton_tx_ref' ); 
    $txn_id  = $order->get_meta( '_startbutton_tx_id' );  

    if ( $txn_ref || $txn_id ) {
        echo '<div class="form-field form-field-wide">';
        echo '<h4>Startbutton Transaction Details</h4>';
        echo '<p><strong>Transaction Reference:</strong> ' . esc_html( $txn_ref ) . '</p>';
        echo '<p><strong>Transaction ID:</strong> ' . esc_html( $txn_id ) . '</p>';
        echo '</div>';
    }
}

function startbutton_wc_add_txn_details_to_customer_order_page( $order ) {
    
    $txn_ref = $order->get_meta( '_startbutton_tx_ref' ); 
    $txn_id  = $order->get_meta( '_startbutton_tx_id' );  

    if ( $txn_ref || $txn_id ) {
        echo '<section class="woocommerce-order-details">';
        echo '<h2>Startbutton Transaction Details</h2>';
        echo '<p><strong>Transaction Reference:</strong> ' . esc_html( $txn_ref ) . '</p>';
        echo '<p><strong>Transaction ID:</strong> ' . esc_html( $txn_id ) . '</p>';
        echo '</section>';
    }
}

/**
 * Ensure the admin AJAX action for refreshing exchange rates is always registered,
 * even when WooCommerce doesn't instantiate the gateway during admin-ajax requests.
 */
function startbutton_wc_ajax_refresh_exchange_rates() {
    // Make sure the gateway class is available.
    if ( ! class_exists( 'Startbutton_WC_Payment_Gateway' ) ) {
        require_once __DIR__ . '/includes/class-wc-gateway-startbutton.php';
    }

    $gateway = new Startbutton_WC_Payment_Gateway();
    $gateway->ajax_refresh_exchange_rates();
}

add_action( 'wp_ajax_startbutton_refresh_exchange_rates', 'startbutton_wc_ajax_refresh_exchange_rates' );