<?php

/**
 * Plugin Name:       Bob Pay
 * Plugin URI:        https://wordpress.org/plugins/bobpay-plugin/
 * Description:       Bob Pay is a payment processing framework developed by Bob Group
 * Author:            Bob Group
 * Requires at least: 5.0
 * Requires PHP:      7.0
 * Version:           2.1.131
 * License:           GPLv2 or later
 * Tested up to:      6.9
 */

// Keep public users out of .php files, no funny business allowed
defined('ABSPATH') || exit;

define('WC_BOBPAY_PLUGIN_VERSION', '2.1.131');
define('WC_BOBPAY_PLUGIN_URL', untrailingslashit(plugins_url(basename(plugin_dir_path(__FILE__)), basename(__FILE__))));
define('WC_BOBPAY_PLUGIN_PATH', untrailingslashit(plugin_dir_path(__FILE__)));

function bobpay_init()
{
	if (!class_exists('WC_Payment_Gateway')) {
		return;
	}

	require_once(plugin_basename('includes/class-wc-bobpay-plugin.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-credit-card.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-instant-eft.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-manual-eft.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-capitec-pay.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-scan-to-pay.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-pay-shap.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-nedbank-direct-eft.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-absa-pay.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-apple-pay.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-google-pay.php'));
	require_once(plugin_basename('includes/class-wc-bobpay-plugin-privacy.php'));
	add_filter('woocommerce_payment_gateways', 'bobpay_add_gateway');
}
add_action('plugins_loaded', 'bobpay_init', 0);

function bobpay_add_gateway($methods)
{
	$methods[] = 'WC_BobPay_Plugin';

	$settings = get_option('woocommerce_bobpay_settings');

	if (empty($settings)) {
		return $methods;
	}

	if (isset($settings['card_enabled']) && $settings['card_enabled'] === 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Credit_Card';
		$card_settings = get_option('woocommerce_bobpay_credit_card_settings');
		if (!empty($card_settings)) {
			$card_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_credit_card_settings', $card_settings);
		}
	}

	if (isset($settings['instant_eft_enabled']) && $settings['instant_eft_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Instant_EFT';
		$instant_eft_settings = get_option('woocommerce_bobpay_instant_eft_settings');
		if (!empty($instant_eft_settings)) {
			$instant_eft_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_instant_eft_settings', $instant_eft_settings);
		}
	}

	if (isset($settings['manual_eft_enabled']) && $settings['manual_eft_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Manual_EFT';
		$manual_eft_settings = get_option('woocommerce_bobpay_manual_eft_settings');
		if (!empty($manual_eft_settings)) {
			$manual_eft_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_manual_eft_settings', $manual_eft_settings);
		}
	}

	if (isset($settings['capitec_pay_enabled']) && $settings['capitec_pay_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Capitec_Pay';
		$capitec_pay_settings = get_option('woocommerce_bobpay_capitec_pay_settings');
		if (!empty($capitec_pay_settings)) {
			$capitec_pay_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_capitec_pay_settings', $capitec_pay_settings);
		}
	}

	if (isset($settings['scan_to_pay_enabled']) && $settings['scan_to_pay_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Scan_To_Pay';
		$scan_to_pay_settings = get_option('woocommerce_bobpay_scan_to_pay_settings');
		if (!empty($scan_to_pay_settings)) {
			$scan_to_pay_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_scan_to_pay_settings', $scan_to_pay_settings);
		}
	}

	if (isset($settings['pay_shap_enabled']) && $settings['pay_shap_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Pay_Shap';
		$pay_shap_settings = get_option('woocommerce_bobpay_pay_shap_settings');
		if (!empty($pay_shap_settings)) {
			$pay_shap_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_pay_shap_settings', $pay_shap_settings);
		}
	}

	if (isset($settings['nedbank_direct_eft_enabled']) && $settings['nedbank_direct_eft_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Nedbank_Direct_EFT';
		$nedbank_direct_eft_settings = get_option('woocommerce_bobpay_nedbank_direct_eft_settings');
		if (!empty($nedbank_direct_eft_settings)) {
			$nedbank_direct_eft_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_nedbank_direct_eft_settings', $nedbank_direct_eft_settings);
		}
	}

	if (isset($settings['absa_pay_enabled']) && $settings['absa_pay_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Absa_Pay';
		$absa_settings = get_option('woocommerce_bobpay_absa_pay_settings');
		if (!empty($absa_settings)) {
			$absa_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_absa_pay_settings', $absa_settings);
		}
	}

	if (isset($settings['apple_pay_enabled']) && $settings['apple_pay_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Apple_Pay';
		$apple_pay_settings = get_option('woocommerce_bobpay_apple_pay_settings');
		if (!empty($apple_pay_settings)) {
			$apple_pay_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_apple_pay_settings', $apple_pay_settings);
		}
	}

	if (isset($settings['google_pay_enabled']) && $settings['google_pay_enabled'] == 'yes') {
		$methods[] = 'WC_BobPay_Plugin_Google_Pay';
		$google_pay_settings = get_option('woocommerce_bobpay_google_pay_settings');
		if (!empty($google_pay_settings)) {
			$google_pay_settings['enabled'] = 'yes';
			update_option('woocommerce_bobpay_google_pay_settings', $google_pay_settings);
		}
	}

	return $methods;
}

function bobpay_plugin_links($links)
{
	$settings_url = add_query_arg(
		array(
			'page' => 'wc-settings',
			'tab' => 'checkout',
		),
		admin_url('admin.php')
	);

	$plugin_links = array(
		'<a href="' . esc_url($settings_url) . '">' . esc_html__('Settings', 'bobpay-woo') . '</a>',
		'<a href="https://www.woocommerce.com/my-account/tickets/">' . esc_html__('Support', 'bobpay-woo') . '</a>',
	);

	return array_merge($plugin_links, $links);
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'bobpay_plugin_links');


function bobpay_blocks_support()
{
	if (class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) {
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-credit-card-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-scan-to-pay-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-pay-shap-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-capitec-pay-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-instant-eft-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-manual-eft-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-nedbank-direct-eft-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-absa-pay-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-apple-pay-blocks-support.php';
		require_once dirname(__FILE__) . '/includes/blocks-support/class-wc-bobpay-google-pay-blocks-support.php';
		add_action(
			'woocommerce_blocks_payment_method_type_registration',
			function (Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry) {
				$payment_method_registry->register(new WC_Bobpay_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Credit_Card_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Scan_To_Pay_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Capitec_Pay_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Instant_EFT_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Manual_EFT_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Pay_Shap_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Nedbank_Direct_EFT_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Absa_Pay_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Apple_Pay_Blocks_Support);
				$payment_method_registry->register(new WC_Bobpay_Google_Pay_Blocks_Support);
			}
		);
	}
}
add_action('woocommerce_blocks_loaded', 'bobpay_blocks_support');


function bobpay_log_order_status_change($order_id, $old_status, $new_status)
{
	$credit_card_settings = get_option('woocommerce_bobpay_credit_card_settings');
	if (empty($credit_card_settings)) {
		return;
	}

	if (empty($credit_card_settings['enable_logging']) || 'no' === $credit_card_settings['enable_logging']) {
		return;
	}

	$logger = wc_get_logger();
	$context = ['source' => 'bobpay-logs'];

	$message = sprintf("Order ID: %d Status changed from %s to %s", $order_id, $old_status, $new_status);
	$logger->info($message, $context);
}
add_action('woocommerce_order_status_changed', 'bobpay_log_order_status_change', 10, 3);

function bobpay_download_logs()
{
    // Check if this is a direct form submission (backward compatibility)
    $is_direct_form = isset($_POST['download_log']) &&
                      isset($_POST['download_log_nonce']);

    // Check if this is an AJAX request
    $is_ajax_request = isset($_POST['action']) &&
                       sanitize_text_field(wp_unslash($_POST['action'])) == 'bobpay_download_logs' &&
                       isset($_POST['nonce']);

    // Validate the request
    if ($is_direct_form) {
        if (!check_admin_referer('bobpay_download_log_action', 'download_log_nonce')) {
            return;
        }
    } elseif ($is_ajax_request) {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bobpay_download_log_action')) {
            wp_die('Security check failed');
            return;
        }
    } else {
        return;
    }

    $log_dir = WC_LOG_DIR;
    $log_files = glob($log_dir . 'bobpay-logs*.log');

    if (empty($log_files)) {
        wp_die('No Bob Pay log files found. Please enable logging in the Bob Pay settings.');
    }

    usort($log_files, function($a, $b) {
        return filemtime($b) - filemtime($a);
    });

    $log_files = array_slice($log_files, 0, 5); // Limit to 5 latest

    $tmp_zip = tempnam(sys_get_temp_dir(), 'bobpay_logs_') . '.zip';
    $zip = new ZipArchive();

    if ($zip->open($tmp_zip, ZipArchive::CREATE) !== true) {
        WC_Logger::log('bobpay-logs', 'Failed to create zip file for Bob Pay logs download.');
        return;
    }

    foreach ($log_files as $file) {
        $zip->addFile($file, basename($file));
    }

    $zip->close();

    global $wp_filesystem;
    if ( empty( $wp_filesystem ) ) {
        require_once ABSPATH . '/wp-admin/includes/file.php';
        WP_Filesystem();
    }

    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="bobpay-woocommerce-logs.zip"');
    header('Content-Length: ' . filesize($tmp_zip));
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary zip file output for download, escaping would corrupt the data.
    echo $wp_filesystem->get_contents( $tmp_zip );
    wp_delete_file($tmp_zip);
    exit;
}
add_action('admin_init', 'bobpay_download_logs');

// AJAX action for log download
add_action('wp_ajax_bobpay_download_logs', 'bobpay_download_logs');

// API key test
function bobpay_test_api_key() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bobpay_test_api_key_action')) {
        wp_send_json_error(array('message' => 'Security check failed'));
        return;
    }

    // Get the gateway instance
    $gateway = WC()->payment_gateways->payment_gateways()['bobpay'];

    if (!$gateway) {
        wp_send_json_error(array('message' => 'BobPay gateway not found'));
        return;
    }

	$gateway->log('Testing API key...');

	$api_key = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : '';

	if (empty($api_key)) {
		wp_send_json_error(array('message' => 'API key is required'));
		return;
	}

	$dev_mode = isset($_POST['dev_mode']) && 'yes' === sanitize_text_field(wp_unslash($_POST['dev_mode'])) ? 'yes' : 'no';
	$error_code = $gateway->validate_integration($api_key, $dev_mode);

    if ($error_code === 200) {
		// Save the API key
		$gateway->update_option('api_key', $api_key);
        wp_send_json_success(array('message' => 'API key is valid'));
    } else {
        wp_send_json_error(array('message' => 'API key is invalid'));
    }
}
add_action('wp_ajax_bobpay_test_api_key', 'bobpay_test_api_key');

// Enqueue checkout icons CSS for non block checkout
add_action('wp_enqueue_scripts', function () {
	if (!is_checkout()) {
		return;
	}

	wp_enqueue_style(
		'bobpay-checkout-style',
		WC_BOBPAY_PLUGIN_URL . '/assets/css/checkout-icons.css',
		array(),
		WC_BOBPAY_PLUGIN_VERSION
	);
}, 99);

// Add more than one icon for credit card for non block checkout
add_filter('woocommerce_gateway_icon', function ($icon, $gateway_id= '') {
	if (!empty($gateway_id) && $gateway_id === 'bobpay_credit_card') {
		$plugin_url = WC_BOBPAY_PLUGIN_URL . '/assets/images/';
		$icon  = '<img src="' . esc_url($plugin_url . 'mastercard.png') . '" class="payment-icon" />';
		$icon .= '<img src="' . esc_url($plugin_url . 'visa.png') . '" class="payment-icon" />';
	}
	return $icon;
}, 10, 2);
