<?php
/**
 * Plugin Name: Bexio Connector by Helvy
 * Version: 0.5.3
 * Description: Save time by synchronizing your shop with bexio!
 * Author: Helvy Sàrl
 * Author URI: https://helvy.ch
 * Text Domain: bexio-connector-by-helvy
 * Domain Path: /languages
 * Requires at least: 5.9
 * Tested up to: 6.1
 * Requires PHP: 7.3
 * Requires Plugins: woocommerce
 * 
 * License: GNU General Public License v3.0
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 *
 * @package extension
 */

defined( 'ABSPATH' ) || exit;

if ( ! defined( 'MAIN_PLUGIN_FILE' ) ) {
	define( 'MAIN_PLUGIN_FILE', __FILE__ );
}

if (!function_exists('bccomp')) {
    function bccomp($left_operand, $right_operand, $scale = 0) {
        $left_operand = number_format($left_operand, $scale, '.', '');
        $right_operand = number_format($right_operand, $scale, '.', '');
        return strcmp($left_operand, $right_operand);
    }
}

/**
 * Current process ID for lock metadata. getmypid() is frequently listed in
 * disable_functions on shared hosting, where calling it is a fatal error.
 */
if (!function_exists('_bcbh_getpid')) {
    function _bcbh_getpid() {
        return function_exists('getmypid') ? getmypid() : 0;
    }
}

/**
 * Plugin-wide logging function for Bexio Connector by Helvy
 */
if (!function_exists('_bcbh_log')) {
    function _bcbh_log($message, $level = 'INFO') {
        // Check if logging is enabled (could be made configurable via admin settings)
        $logging_enabled = get_option('bexio_connector_by_helvy_enable_logging', false);
        if (!$logging_enabled) {
			error_log($message); // log to error_log
            return;
        }
        
        $log_file = plugin_dir_path(__FILE__) . 'bexio-connector-by-helvy.log';
        $timestamp = date('Y-m-d H:i:s');
        $log_entry = "[$timestamp] [$level] $message" . PHP_EOL;
        
        // Check file size and rotate if too large (5MB limit)
        if (file_exists($log_file) && filesize($log_file) > 5 * 1024 * 1024) {
            $backup_file = plugin_dir_path(__FILE__) . 'bexio-connector-by-helvy.log.old';
            if (file_exists($backup_file)) {
                unlink($backup_file);
            }
            rename($log_file, $backup_file);
        }
        
        file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
    }
}

require_once plugin_dir_path( __FILE__ ) . '/vendor/autoload_packages.php';
require_once plugin_dir_path( __FILE__ ) . '/config.php';
require_once plugin_dir_path( __FILE__ ) . '/plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
use BexioConnectorByHelvy\Admin\Setup;

// phpcs:disable WordPress.Files.FileName

/**
 * WooCommerce fallback notice.
 *
 * @since 0.1.0
 */
function bexio_connector_by_helvy_missing_wc_notice() {
	/* translators: %s WC download URL link. */
	echo '<div class="error"><p><strong>' . sprintf( esc_html__( 'Bexio Connector by Helvy requires WooCommerce to be installed and active. You can download %s here.', 'bexio_connector_by_helvy' ), '<a href="https://woo.com/" target="_blank">WooCommerce</a>' ) . '</strong></p></div>';
}

$crons = new BexioConnectorByHelvy\Crons();
register_activation_hook(__FILE__, array($crons, 'register_batch_products_sync_event'));
register_deactivation_hook(__FILE__, array($crons, 'clear_batch_products_sync_event'));

register_activation_hook( __FILE__, 'bexio_connector_by_helvy_activate' );

/**
 * Activation hook.
 *
 * @since 0.1.0
 */
function bexio_connector_by_helvy_activate() {
	if ( ! class_exists( 'WooCommerce' ) ) {
		add_action( 'admin_notices', 'bexio_connector_by_helvy_missing_wc_notice' );
		return;
	}
}

if ( ! class_exists( 'bexio_connector_by_helvy' ) ) :
	/**
	 * The bexio_connector_by_helvy class.
	 */
	class bexio_connector_by_helvy {
		/**
		 * This class instance.
		 *
		 * @var \bexio_connector_by_helvy single instance of this class.
		 */
		private static $instance;

		/**
		 * Constructor.
		 */
		public function __construct() {
			$this->includes();
		}

		private function includes() {
			if (current_user_can('administrator') || current_user_can('manage_woocommerce')) {
				new BexioConnectorByHelvy\AdminMenu();
				new BexioConnectorByHelvy\BulkActions();
				new BexioConnectorByHelvy\AdminPanelAssets();
				PucFactory::buildUpdateChecker(
					BexioConnectorByHelvy\API::getApiDomain() . '/public/plugin-details.json',
					__FILE__,
					'bexio-connector-by-helvy'
				);
			}
			new BexioConnectorByHelvy\AdminAPIAuth();
			new BexioConnectorByHelvy\AdminAPISettings();
			new BexioConnectorByHelvy\AdminAPISynchronization();
			new BexioConnectorByHelvy\WooCommerceWebhooks();
			new BexioConnectorByHelvy\BatchSync();
		}

        /**
         * Add a new integration to WooCommerce.
         */
        public function add_integration( $integrations ) {
            $integrations[] = 'Bexio_Connector_Integration';
            return $integrations;
        }

		/**
		 * Cloning is forbidden.
		 */
		public function __clone() {
			wc_doing_it_wrong( __FUNCTION__, __( 'Cloning is forbidden.', 'bexio_connector_by_helvy' ), BEXIO_CONNECTOR_BY_HELVY_VERSION );
		}

		/**
		 * Unserializing instances of this class is forbidden.
		 */
		public function __wakeup() {
			wc_doing_it_wrong( __FUNCTION__, __( 'Unserializing instances of this class is forbidden.', 'bexio_connector_by_helvy' ), BEXIO_CONNECTOR_BY_HELVY_VERSION );
		}

		/**
		 * Gets the main instance.
		 *
		 * Ensures only one instance can be loaded.
		 *
		 * @return \bexio_connector_by_helvy
		 */
		public static function instance() {

			if ( null === self::$instance ) {
				self::$instance = new self();
			}

			return self::$instance;
		}
	}
endif;

add_action( 'plugins_loaded', 'bexio_connector_by_helvy_init', 10 );

/**
 * Initialize the plugin.
 *
 * @since 0.1.0
 */
function bexio_connector_by_helvy_init() {
	load_plugin_textdomain( 'bexio-connector-by-helvy', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
	if ( ! class_exists( 'WooCommerce' ) ) {
		add_action( 'admin_notices', 'bexio_connector_by_helvy_missing_wc_notice' );
		_bcbh_log("BexioConnector: Plugin init - WooCommerce not available");
		return;
	}

	_bcbh_log("BexioConnector: Plugin init - starting main instance");
	bexio_connector_by_helvy::instance();
	_bcbh_log("BexioConnector: Plugin init - main instance created");
}

add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'add_custom_plugin_link');

/**
 * Add a custom links to the plugin actions
 *
 * @param array $links Existing plugin action links
 * @return array Modified plugin action links
 */
function add_custom_plugin_link($links)
{
	$settings_link = '<a href="admin.php?page=bexio-connector-by-helvy&section=settings">'.__('Settings').'</a>';
	array_unshift($links, $settings_link);

	$view_link = '<a href="admin.php?page=bexio-connector-by-helvy">'.__('View').'</a>';
	array_unshift($links, $view_link);

	return $links;
}

/**
 * Add custom emails to WooCommerce
 */
function add_bexio_custom_emails($email_classes) {
    // Only register when WooCommerce is fully loaded
    if (!class_exists('WooCommerce') || !class_exists('WC_Email')) {
        return $email_classes;
    }
    
    require_once plugin_dir_path( __FILE__ ) . 'includes/admin/class.custom-invoice-email.php';
    
    // Register the custom email class with key matching email ID
    $email_classes['bexio_invoice_email'] = new BexioConnectorByHelvy\CustomInvoiceEmail();
    
    return $email_classes;
}

// Register the filter much earlier - right after plugins are loaded
add_action('plugins_loaded', function() {
    // Only proceed if WooCommerce exists
    if (class_exists('WooCommerce') && class_exists('WC_Email')) {
        add_filter('woocommerce_email_classes', 'add_bexio_custom_emails', 10, 1);
    } else {
        _bcbh_log("BexioConnector: WooCommerce not available on plugins_loaded");
    }
}, 25); // Run after our main plugin init (priority 10)

// Also register immediately when WooCommerce initializes with early priority
add_action('woocommerce_init', function() {
    add_filter('woocommerce_email_classes', 'add_bexio_custom_emails', 10, 1);
}, 5); // Very early priority

// Simple debug hook to verify order completion events are firing - register immediately
_bcbh_log("BexioConnector: Registering order completion debug hooks");
add_action('woocommerce_order_status_completed', function($order_id) {
    _bcbh_log("DEBUG: Basic order completion hook fired for order {$order_id}");
}, 5, 1);

// Add broader hook to catch ANY order status changes
add_action('woocommerce_order_status_changed', function($order_id, $old_status, $new_status) {
    _bcbh_log("DEBUG: Order {$order_id} status changed from {$old_status} to {$new_status}");
    if ($new_status === 'completed') {
        _bcbh_log("DEBUG: Order {$order_id} was marked as completed via status change hook");
    }
}, 5, 3);

// Check the custom invoice email setting immediately when plugin loads
$email_setting_value = get_option('bexio_connector_by_helvy_custom_invoice_email_enabled', false);
_bcbh_log("BexioConnector: Custom invoice email setting check on plugin load: " . ($email_setting_value ? 'ENABLED' : 'DISABLED'));
_bcbh_log("BexioConnector: Setting value type: " . gettype($email_setting_value) . ", raw value: " . var_export($email_setting_value, true));

// Additionally, hook directly into order status change to manually trigger if needed
add_action('woocommerce_order_status_completed', function($order_id, $order) {
    _bcbh_log("BexioConnector: Manual check for custom invoice email on order completion: {$order_id}");
    
    // Check if the setting is enabled first
    $email_enabled = get_option('bexio_connector_by_helvy_custom_invoice_email_enabled', false);
    _bcbh_log("BexioConnector: Custom invoice email setting enabled: " . ($email_enabled ? 'true' : 'false'));
    
    if (!$email_enabled) {
        _bcbh_log("BexioConnector: Custom invoice email is disabled, skipping manual trigger");
        return;
    }
    
    // Check if WooCommerce is available - use defensive approach
    if (!class_exists('WooCommerce')) {
        _bcbh_log("BexioConnector: WooCommerce class not available");
        return;
    }
    
    global $woocommerce;
    if (!$woocommerce || !method_exists($woocommerce, 'mailer')) {
        _bcbh_log("BexioConnector: WooCommerce mailer not available via global");
        return;
    }
    
    // Try to get our custom email instance from WooCommerce
    $mailer = $woocommerce->mailer();
    if (!$mailer) {
        _bcbh_log("BexioConnector: WooCommerce mailer instance not available");
        return;
    }
    
    $email_classes = $mailer->get_emails();
    _bcbh_log("BexioConnector: Available email classes: " . implode(', ', array_keys($email_classes)));
    
    if (isset($email_classes['bexio_invoice_email'])) {
        _bcbh_log("BexioConnector: Found custom email class, triggering manually");
        $email_classes['bexio_invoice_email']->trigger($order_id, $order);
    } else {
        _bcbh_log("BexioConnector: Custom email class 'bexio_invoice_email' not found in WooCommerce mailer");
        
        // Debug: Check if our filter is actually working
        $test_classes = apply_filters('woocommerce_email_classes', array());
        _bcbh_log("BexioConnector: Email classes from filter: " . implode(', ', array_keys($test_classes)));
    }
}, 20, 2);

// Debug hook to check if our email classes filter is being called
add_filter('woocommerce_email_classes', function($email_classes) {
    _bcbh_log("DEBUG: woocommerce_email_classes filter called with classes: " . implode(', ', array_keys($email_classes)));
    return $email_classes;
}, 999);
