<?php
/**
 * @package Wetail Shipping
 * @link https://wetail.io/
 * @wordpress-plugin
 * Plugin Name: Wetail Shipping
 * Plugin URI: https://wetail.io/integrationer/wetail-shipping/
 * Description: Wetail Shipping
 * Author: Wetail AB
 * Version: 1.3.0
 * Tested up to: 7.0
 * WC tested up to: 10.5
 * License: GPL-3.0
 * License URI: http://www.gnu.org/licenses/gpl-3.0.txt
 * Author URI: https://wetail.io/
 */



namespace Wetail\Shipping\Engine;

defined( 'ABSPATH' ) or die();

/**
 * Local constants
 */
define( __NAMESPACE__ . '\PATH', dirname( __FILE__ ) );
define( __NAMESPACE__ . '\SLUG', 'wetail-shipping' );
define( __NAMESPACE__ . '\INDEX', __FILE__ );
define( __NAMESPACE__ . '\NAME', basename( __DIR__ ) );
define( __NAMESPACE__ . '\PLUGIN_ID', basename( __DIR__ ) . 'plugin.php/' . basename( INDEX ) );
define( __NAMESPACE__ . '\URL', dirname( plugins_url() ) . '/' . basename( dirname( __DIR__ ) ) . '/' . NAME );
define( __NAMESPACE__ . '\VERSION', 1.30 );

/**
 * Autoloader init
 */
require_once "autoload.php";

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 );
	}
} );

add_action( 'plugins_loaded', function () {
	load_plugin_textdomain( 'wetail-shipping', false, dirname( plugin_basename( __FILE__ ) ) . '/language' );
} );
/**
 * Load the plugin
 */
Wetail_Shipping::load();

if ( ! function_exists( 'wetail_shipping_write_log' ) ) {

	// Recursively truncate string values in arrays/objects
	function wetail_truncate_deep( $value, $limit = 50, &$seen = null ) {
		// multibyte-safe truncation
		$truncate = static function ( $s ) use ( $limit ) {
			if ( ! is_string( $s ) ) return $s;
			if ( function_exists( 'mb_strlen' ) ) {
				return mb_strlen( $s, 'UTF-8' ) > $limit
					? mb_substr( $s, 0, $limit, 'UTF-8' ) . '...'
					: $s;
			}
			return strlen( $s ) > $limit ? substr( $s, 0, $limit ) . '...' : $s;
		};

		// Scalars
		if ( is_string( $value ) ) {
			return $truncate( $value );
		}
		if ( ! is_array( $value ) && ! is_object( $value ) ) {
			return $value;
		}

		// Prevent infinite loops on circular object graphs
		if ( is_null( $seen ) ) $seen = new \SplObjectStorage();

		// Arrays
		if ( is_array( $value ) ) {
			$out = [];
			foreach ( $value as $k => $v ) {
				$out[ $k ] = wetail_truncate_deep( $v, $limit, $seen );
			}
			return $out;
		}



		// Objects -> return as array (safe for json_encode + private/protected props)
		if ( is_object( $value ) ) {
			if ( $seen->contains( $value ) ) {
				return '*recursion*';
			}
			$seen->attach( $value );

			$props = get_object_vars( $value ); // public properties
			$out   = [];
			foreach ( $props as $k => $v ) {
				$out[ $k ] = wetail_truncate_deep( $v, $limit, $seen );
			}
			return $out;
		}

		return $value;
	}

	function wetail_shipping_write_log( $log ) {
		// Preprocess: truncate deeply
		$processed = wetail_truncate_deep( $log, 50 );

		// Prepare message
		if ( is_array( $processed ) || is_object( $processed ) ) {
			$message = json_encode( $processed, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
		} else {
			$message = esc_html( (string) $processed );
		}

		// Caller info
		$bt            = debug_backtrace();
		$caller_line   = $bt[0]['line'] ?? 0;
		$caller_class  = $bt[1]['class'] ?? '';
		$caller_method = $bt[1]['function'] ?? 'unknown closure';

		$message = $caller_class . '::' . $caller_method . '(' . $caller_line . '): ' . $message;
		$message = str_replace( PHP_EOL, ' ', $message );

		// Log with WooCommerce logger
		$logger  = wc_get_logger();
		$context = array( 'source' => 'wetail-shipping' );
		$logger->debug( $message, $context );
	}
}


// Hook into plugin activation to check for the table
register_activation_hook(__FILE__, __NAMESPACE__ . '\\ws_create_labels_table');

function ws_create_labels_table() {
	global $wpdb;

	// Table name
	$table_name = $wpdb->prefix . 'wetail_shipping_labels';

	// Check if the table exists already
	if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) {

		// SQL to create the table
		$charset_collate = $wpdb->get_charset_collate();
		$sql = "CREATE TABLE $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            wc_order_id INT(11) NOT NULL,
            date_created DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
            data MEDIUMTEXT NOT NULL,
            PRIMARY KEY (id),
            KEY idx_wc_order_id (wc_order_id)
        ) $charset_collate;";

		// Load the upgrade functions
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

		// Execute the table creation
		dbDelta($sql);
	}
}

function ws_do_migrations(){
	global $wpdb;

	//region 869ac4x4e
	/**
	 * Add index to labels table if it exists
	 *
	 * @since 1.3.0
	 * @clickup https://app.clickup.com/t/869ac4x4e
	 */
	$table_name     = $wpdb->prefix . 'wetail_shipping_labels';
	$migration_flag = $wpdb->prefix . 'wetail_shipping_labels_migration_869ac4x4e';
	if ( ( ! get_option( $migration_flag ) ) && ( $wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" ) == $table_name ) ) {
		$wpdb->query( "ALTER TABLE $table_name ADD INDEX idx_wetail_labels_wc_order_id (wc_order_id)" );

		// Add migration flag to prevent reruns
		add_option( $migration_flag, time() );
	}
	//endregion
}

// Optional: You can also check for the table on every init in case of plugin updates without activation
add_action( 'plugins_loaded', __NAMESPACE__ . '\\ws_create_labels_table');
add_action( 'plugins_loaded', __NAMESPACE__ . '\\ws_do_migrations', 100);

register_activation_hook(__FILE__, function(){
	global $wpdb;
	$charset_collate = $wpdb->get_charset_collate();
	$table_name = $wpdb->prefix . Wetail_Shipping_Product_Packing_Dimensions::TABLE_NAME;

	$sql = "CREATE TABLE $table_name (
        id int(11) NOT NULL AUTO_INCREMENT,
        wc_product_id int(11) NOT NULL,
        height DECIMAL(10,2),
        width DECIMAL(10,2),
        length DECIMAL(10,2),
        weight DECIMAL(10,2),
    	PRIMARY KEY (id)
    ) $charset_collate;";
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	dbDelta($sql);
});
