<?php
/**
 * Plugin Name: Wayl Checkout
 * Description: Payment facilitator for WooCommerce. Accept payments via Wayl Checkout - Iraqi local and international Visa/MasterCard, ZainCash, FIB, FastPay and more. Support for IQD and USD with Arabic and English language support.
 * Version:     1.0.0
 * Author:      Wayl Payment
 * Author URI:  https://www.wayl.io/
 * License:     GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: wayl-checkout
 * Requires at least: 5.0
 * Tested up to: 6.9
 * Requires PHP: 7.4
 * WC requires at least: 5.0
 * WC tested up to: 8.5
 */

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

/**
 * Main plugin initialization function
 *
 * @return void
 */
function waylchp_init_plugin() {
	// Check if WooCommerce is active
	if ( ! class_exists( 'WooCommerce' ) ) {
		add_action( 'admin_notices', 'waylchp_woocommerce_missing_notice' );
		return;
	}

	// Check WooCommerce version
	if ( version_compare( WC()->version, '5.0', '<' ) ) {
		add_action( 'admin_notices', 'waylchp_woocommerce_version_notice' );
		return;
	}

	// Define constants
	if ( ! defined( 'WAYLCHP_PLUGIN_PATH' ) ) {
		define( 'WAYLCHP_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
	}
	if ( ! defined( 'WAYLCHP_PLUGIN_URL' ) ) {
		define( 'WAYLCHP_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
	}
	if ( ! defined( 'WAYLCHP_PLUGIN_VERSION' ) ) {
		define( 'WAYLCHP_PLUGIN_VERSION', '1.0.0' );
	}

	// Autoload plugin classes
	require_once WAYLCHP_PLUGIN_PATH . 'includes/class-waylchp-payment-gateway.php';
	require_once WAYLCHP_PLUGIN_PATH . 'includes/class-waylchp-api.php';
	require_once WAYLCHP_PLUGIN_PATH . 'includes/class-waylchp-webhook-handler.php';
	require_once WAYLCHP_PLUGIN_PATH . 'includes/class-waylchp-logger.php';

	// Initialize logger
	WaylCHP_Logger::init();

	// Initialize webhook handler
	WaylCHP_Webhook_Handler::init();

	// Register payment method with WooCommerce
	add_filter( 'woocommerce_payment_gateways', 'waylchp_register_payment_gateway' );

	// Declare WooCommerce HPOS (High-Performance Order Storage) compatibility
	add_action( 'before_woocommerce_init', 'waylchp_declare_hpos_compatibility' );

	// Add admin notices for configuration
	add_action( 'admin_notices', 'waylchp_admin_notices' );

	// Add notice on plugins page if not configured
	add_action( 'admin_notices', 'waylchp_plugins_page_notice' );
}

/**
 * Declare WooCommerce HPOS (High-Performance Order Storage) compatibility
 *
 * @return void
 */
function waylchp_declare_hpos_compatibility() {
	if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
		\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
	}
}

/**
 * Register Wayl payment gateway
 *
 * @param array $methods Existing payment methods
 * @return array Updated payment methods array
 */
function waylchp_register_payment_gateway( $methods ) {
	$methods[] = 'WaylCHP_Checkout_Gateway';
	return $methods;
}

/**
 * Display notice if WooCommerce is not active
 *
 * @return void
 */
function waylchp_woocommerce_missing_notice() {
	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}
	?>
	<div class="notice notice-error">
		<p>
			<strong><?php esc_html_e( 'Wayl Checkout', 'wayl-checkout' ); ?></strong>: 
			<?php esc_html_e( 'This plugin requires WooCommerce to be installed and activated.', 'wayl-checkout' ); ?>
		</p>
	</div>
	<?php
}

/**
 * Display notice if WooCommerce version is too old
 *
 * @return void
 */
function waylchp_woocommerce_version_notice() {
	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}
	?>
	<div class="notice notice-error">
		<p>
			<strong><?php esc_html_e( 'Wayl Checkout', 'wayl-checkout' ); ?></strong>: 
			<?php
			printf(
				/* translators: %s: Minimum WooCommerce version required */
				esc_html__( 'This plugin requires WooCommerce version %s or higher.', 'wayl-checkout' ),
				'5.0'
			);
			?>
		</p>
	</div>
	<?php
}

/**
 * Display admin notices for configuration
 *
 * @return void
 */
function waylchp_admin_notices() {
	// Check user capabilities
	if ( ! current_user_can( 'manage_woocommerce' ) ) {
		return;
	}

	// Only show on WooCommerce settings pages
	// Note: Nonce verification not needed here as we're only reading GET parameter
	// for display purposes, not processing form submission
	if ( ! isset( $_GET['page'] ) || sanitize_text_field( wp_unslash( $_GET['page'] ) ) !== 'wc-settings' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return;
	}

	// Check if Wayl payment method is configured
	$waylchp_gateway = new WaylCHP_Checkout_Gateway();
	if ( empty( $waylchp_gateway->api_key ) ) {
		?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e( 'Wayl Checkout Payment', 'wayl-checkout' ); ?>:</strong> 
				<?php
				$settings_url = esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=wayl' ) );
				printf(
					/* translators: %s: Settings page URL */
					wp_kses_post( __( 'Please configure your API key in <a href="%s">WooCommerce Settings > Payments > Wayl</a>.', 'wayl-checkout' ) ),
					esc_url( $settings_url )
				);
				?>
			</p>
		</div>
		<?php
	}
}

/**
 * Display notice on plugins page if Wayl is not configured
 *
 * @return void
 */
function waylchp_plugins_page_notice() {
	// Check user capabilities
	if ( ! current_user_can( 'manage_woocommerce' ) ) {
		return;
	}

	// Check if WooCommerce is active
	if ( ! class_exists( 'WooCommerce' ) ) {
		return;
	}

	// Only show on plugins page or plugin install page
	$screen = get_current_screen();
	$pagenow = isset( $GLOBALS['pagenow'] ) ? $GLOBALS['pagenow'] : '';
	
	// Check if we're on plugins page or plugin install page
	$is_plugins_page = false;
	
	if ( $screen ) {
		// Check screen ID
		$allowed_screens = array( 'plugins', 'plugin-install' );
		if ( in_array( $screen->id, $allowed_screens, true ) ) {
			$is_plugins_page = true;
		}
		// Also check screen base as fallback
		if ( ! $is_plugins_page && isset( $screen->base ) ) {
			if ( in_array( $screen->base, array( 'plugins', 'plugin-install' ), true ) ) {
				$is_plugins_page = true;
			}
		}
	}
	
	// Fallback: check pagenow if screen is not available
	if ( ! $is_plugins_page && $pagenow ) {
		if ( in_array( $pagenow, array( 'plugins.php', 'plugin-install.php' ), true ) ) {
			$is_plugins_page = true;
		}
	}
	
	if ( ! $is_plugins_page ) {
		return;
	}

	// Check if Wayl payment method is configured
	$waylchp_gateway = new WaylCHP_Checkout_Gateway();
	if ( empty( $waylchp_gateway->api_key ) ) {
		$settings_url = esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=wayl' ) );
		$logo_url     = plugins_url( 'assets/images/wayl-logo.png', __FILE__ );
		?>
		<div class="notice notice-info is-dismissible waylchp-plugins-notice" style="border-left-color: #343433; padding: 15px 20px;">
			<div style="display: flex; align-items: center; gap: 15px;">
				<div style="flex-shrink: 0;">
					<img src="<?php echo esc_url( $logo_url ); ?>" alt="Wayl" style="height: 50px; width: auto;" />
				</div>
				<div style="flex: 1;">
					<h3 style="margin: 0 0 8px 0; font-size: 16px; color: #333;">
						<?php esc_html_e( 'Setup Wayl Checkout', 'wayl-checkout' ); ?>
					</h3>
					<p style="margin: 0 0 10px 0; color: #666;">
						<?php esc_html_e( 'Wayl Checkout is installed but not configured. Complete the setup to start accepting payments from your customers.', 'wayl-checkout' ); ?>
					</p>
					<p style="margin: 0;">
						<a href="<?php echo esc_url( $settings_url ); ?>" class="button button-primary" style="margin-right: 10px;">
							<?php esc_html_e( 'Configure Now', 'wayl-checkout' ); ?>
						</a>
						<a href="https://www.wayl.io" target="_blank" rel="noopener noreferrer" class="button button-secondary">
							<?php esc_html_e( 'Learn More About Wayl', 'wayl-checkout' ); ?>
						</a>
					</p>
				</div>
			</div>
		</div>
		<?php
	} else {
		// Plugin configured - show simple active notice
		$logo_url = plugins_url( 'assets/images/wayl-app-logo.png', __FILE__ );
		?>
		<div class="notice notice-success is-dismissible waylchp-plugins-notice" style="border-left-color: #46a049; padding: 15px 20px;">
			<div style="display: flex; align-items: center; gap: 15px;">
				<div style="flex-shrink: 0;">
					<img src="<?php echo esc_url( $logo_url ); ?>" alt="Wayl" style="height: 40px; width: auto;" />
				</div>
				<div style="flex: 1;">
					<p style="margin: 0; color: #333; font-size: 14px;">
						<?php esc_html_e( 'Wayl Checkout is active and configured.', 'wayl-checkout' ); ?>
					</p>
				</div>
			</div>
		</div>
		<?php
	}
}

// Load plugin after WooCommerce is loaded
add_action( 'plugins_loaded', 'waylchp_init_plugin', 10 );

/**
 * Send welcome email to merchant on plugin activation
 *
 * @return void
 */
function waylchp_send_activation_email() {
	$admin_email = get_option( 'admin_email' );
	if ( ! $admin_email ) {
		return;
	}

	$site_name = get_bloginfo( 'name' );
	$site_url  = home_url();
	$settings_url = admin_url( 'admin.php?page=wc-settings&tab=checkout&section=wayl' );

	$subject = sprintf(
		/* translators: %s: Site name */
		__( 'Welcome to Wayl Checkout - %s', 'wayl-checkout' ),
		$site_name
	);

	$message = sprintf(
		/* translators: 1: Site name, 2: Site URL, 3: Settings URL, 4: Support email, 5: Support WhatsApp */
		__( 'Hello,

Thank you for installing the Wayl Checkout plugin on %1$s!

**About Wayl:**
Wayl is Iraq\'s first payment facilitator. We enable online Iraqi merchants to accept online payments via Local and International payment methods. Wayl Checkout aggregates all payment methods in one solution, making it easy for your customers to pay using their preferred method.

**Accepted Payment Methods:**
- Visa/MasterCard
- ZainCash
- FIB (First Iraqi Bank)
- FastPay

**Setup Steps:**
1. Register your account on Wayl and submit your information via dashboard.thewayl.com
2. Contact Wayl Support to obtain your Merchant Token API Key:
   - Email: %4$s
   - WhatsApp: %5$s
3. Add your API key to the plugin: %3$s
4. Configure your preferred language and currency settings
5. Go live and monitor your received payments via Wayl dashboard

**Features:**
- All payment methods in one solution
- Secure payment processing
- Real-time payment notifications
- Support for IQD and USD currencies
- Arabic and English language support
- Easy setup and configuration

**Need Help?**
Our support team is here to assist you:
- Email: %4$s
- WhatsApp: %5$s
- Website: https://www.wayl.io
- Dashboard: https://dashboard.thewayl.com

We\'re here to help you get started. If you have any questions, please don\'t hesitate to contact our support team.

Best regards,
Wayl Support Team

---
This email was sent from %1$s (%2$s)', 'wayl-checkout' ),
		$site_name,
		$site_url,
		$settings_url,
		'support@wayl.io',
		'+964 775 227 7781'
	);

	$headers = array(
		'Content-Type: text/plain; charset=UTF-8',
		'From: ' . $site_name . ' <' . $admin_email . '>',
	);

	wp_mail( $admin_email, $subject, $message, $headers );
}

/**
 * Plugin activation handler
 *
 * @return void
 */
function waylchp_activate_plugin() {
	// Generate webhook secret if not exists
	$option_name = 'waylchp_webhook_secret';
	if ( ! get_option( $option_name ) ) {
		$secret = bin2hex( random_bytes( 32 ) );
		add_option( $option_name, $secret, '', false );
	}

	// Create logs directory on activation
	$upload_dir = wp_upload_dir();
	$log_directory = $upload_dir['basedir'] . '/wayl-checkout/';
	if ( ! file_exists( $log_directory ) ) {
		wp_mkdir_p( $log_directory );
	}

	// Send welcome email to merchant (only on first activation)
	$activation_email_sent = get_option( 'waylchp_activation_email_sent', false );
	if ( ! $activation_email_sent ) {
		// Send email after a short delay to ensure WordPress is fully loaded
		add_action( 'admin_init', 'waylchp_send_activation_email_once', 1 );
		update_option( 'waylchp_activation_email_sent', true );
	}
}

/**
 * Send activation email once (called on admin_init)
 *
 * @return void
 */
function waylchp_send_activation_email_once() {
	// Only send once
	if ( get_transient( 'waylchp_email_sending' ) ) {
		return;
	}
	set_transient( 'waylchp_email_sending', true, 60 ); // Prevent duplicate sends
	waylchp_send_activation_email();
	delete_transient( 'waylchp_email_sending' );
}

register_activation_hook( __FILE__, 'waylchp_activate_plugin' );
