<?php
/*
Plugin Name: TrackFree – All-In-One WooCommerce Order Tracking
Plugin URI: https://trackfree.io/
Description: TrackFree is hassle-free automated shipment tracking plugin for WooCommerce.
Version: 3.2.4
Author: TrackFree
Author URI: https://trackfree.io
Text Domain: trackfree-woocommerce-tracking
Domain Path: /languages
*/

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

define( 'TRACKFREE_VERSION', '3.2.4' );

require_once __DIR__ . '/includes/class-trackfree-plugin.php';

TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ );

register_activation_hook( __FILE__, 'trackfree_activation' );
register_uninstall_hook( __FILE__, 'trackfree_uninstall' );

if ( ! function_exists( 'trackfree_url' ) ) {
	function trackfree_url() {
		return TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->trackfree_url();
	}
}

if ( ! function_exists( 'tfree_sslverify' ) ) {
	function tfree_sslverify() {
		return (bool) apply_filters( 'trackfree_sslverify', true );
	}
}

if ( ! function_exists( 'trackfree_activation' ) ) {
	function trackfree_activation() {
		TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->activation();
	}
}

if ( ! function_exists( 'trackfree_uninstall' ) ) {
	function trackfree_uninstall() {
		TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->uninstall();
	}
}

if ( TrackFree_WooCommerce_Tracking_Plugin::is_woocommerce_active() ) {
	if ( ! function_exists( 'tfree_get_courier_list' ) ) {
		function tfree_get_courier_list() {
			static $couriers = null;
			if ( null !== $couriers ) {
				return $couriers;
			}

			$path = plugin_dir_path( __FILE__ ) . 'assets/js/trackfree_couriers.json';
			$json = @file_get_contents( $path );
			$data = $json ? json_decode( $json, true ) : array();

			$couriers = is_array( $data ) ? $data : array();
			return $couriers;
		}
	}

	if ( ! function_exists( 'tfree_get_order_recommendation_context' ) ) {
		function tfree_get_order_recommendation_context( $order_id ) {
			$exclude_ids   = array();
			$cat_slugs_map = array();
			$cat_names_map = array();

			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				return array( $exclude_ids, array(), array() );
			}

			foreach ( $order->get_items() as $item_values ) {
				$item_data    = $item_values->get_data();
				$product_id   = $item_data['product_id'] ?? 0;
				$product_data = $product_id ? wc_get_product( $product_id ) : null;
				if ( ! empty( $product_data ) ) {
					$exclude_ids[] = (int) $product_id;

					$cat_ids = method_exists( $product_data, 'get_category_ids' ) ? $product_data->get_category_ids() : array();
					if ( $cat_ids ) {
						foreach ( $cat_ids as $category_id ) {
							$term = get_term( $category_id, 'product_cat' );
							if ( $term && ! is_wp_error( $term ) ) {
								$cat_slugs_map[ $term->slug ] = true;
								$cat_names_map[ $term->name ] = true;
							}
						}
					}
				}
			}

			$exclude_ids = array_values( array_unique( array_filter( $exclude_ids ) ) );
			return array( $exclude_ids, array_keys( $cat_slugs_map ), array_keys( $cat_names_map ) );
		}
	}

	if ( ! function_exists( 'tfree_get_recommended_product_ids' ) ) {
		function tfree_get_recommended_product_ids( $exclude_ids, $category_slugs, $category_names, $query_limit = 12 ) {
			$args = array(
				'status'  => 'publish',
				'orderby' => 'rand',
				'limit'   => (int) $query_limit,
				'return'  => 'ids',
				'exclude' => (array) $exclude_ids,
			);

			$product_ids = array();
			if ( $category_slugs ) {
				$args['category'] = (array) $category_slugs;
				$product_ids      = wc_get_products( $args );
			} else {
				$product_ids = wc_get_products( $args );
			}

			if ( count( $product_ids ) < 4 ) {
				if ( $category_slugs && $category_names ) {
					$args['category'] = (array) $category_names;
					$product_ids      = wc_get_products( $args );
				}

				if ( count( $product_ids ) < 4 ) {
					unset( $args['category'] );
					$product_ids = wc_get_products( $args );
				}
			}

			return is_array( $product_ids ) ? $product_ids : array();
		}
	}


	if ( ! function_exists( 'tfree_get_product_image_url' ) ) {
		/**
		 * Resolve product image URL with fallbacks (featured, variation/parent, gallery, placeholder).
		 *
		 * @param WC_Product|int $product_or_id
		 * @param string         $image_size
		 * @param bool           $use_placeholder
		 * @return string
		 */
		function tfree_get_product_image_url( $product_or_id, $image_size = 'full', $use_placeholder = true ) {
			$product = is_numeric( $product_or_id ) ? wc_get_product( (int) $product_or_id ) : $product_or_id;
			if ( ! $product ) {
				return '';
			}

			$image_id = 0;
			if ( method_exists( $product, 'get_image_id' ) ) {
				$image_id = (int) $product->get_image_id();
			}

			if ( ! $image_id && $product->is_type( 'variation' ) && method_exists( $product, 'get_parent_id' ) ) {
				$parent_id = (int) $product->get_parent_id();
				if ( $parent_id ) {
					$parent = wc_get_product( $parent_id );
					if ( $parent && method_exists( $parent, 'get_image_id' ) ) {
						$image_id = (int) $parent->get_image_id();
					}
				}
			}

			if ( ! $image_id && method_exists( $product, 'get_gallery_image_ids' ) ) {
				$gallery_ids = (array) $product->get_gallery_image_ids();
				if ( ! empty( $gallery_ids ) ) {
					$image_id = (int) reset( $gallery_ids );
				}
			}

			if ( ! $image_id && $product->is_type( 'variation' ) && method_exists( $product, 'get_parent_id' ) ) {
				$parent_id = (int) $product->get_parent_id();
				if ( $parent_id ) {
					$parent = wc_get_product( $parent_id );
					if ( $parent && method_exists( $parent, 'get_gallery_image_ids' ) ) {
						$gallery_ids = (array) $parent->get_gallery_image_ids();
						if ( ! empty( $gallery_ids ) ) {
							$image_id = (int) reset( $gallery_ids );
						}
					}
				}
			}

			$image_url = '';
			if ( $image_id ) {
				$image_url = (string) wp_get_attachment_image_url( $image_id, $image_size );
			}

			if ( ! $image_url ) {
				$image_url = (string) get_the_post_thumbnail_url( $product->get_id(), $image_size );
			}

			if ( ! $image_url && $use_placeholder && function_exists( 'wc_placeholder_img_src' ) ) {
				$image_url = (string) wc_placeholder_img_src( $image_size );
			}

			if ( $image_url ) {
				$home_scheme = function_exists( 'home_url' ) ? wp_parse_url( home_url(), PHP_URL_SCHEME ) : '';
				if ( $home_scheme === 'https' && function_exists( 'set_url_scheme' ) ) {
					$image_url = set_url_scheme( $image_url, 'https' );
				}
				$image_url = esc_url_raw( $image_url );
			}

			return $image_url ? (string) $image_url : '';
		}
	}

	if ( ! function_exists( 'tfree_build_recommend_products_payload' ) ) {
		/**
		 * @param int[]  $product_ids
		 * @param int    $max
		 * @param string $image_size 'full'|'medium' etc.
		 * @param string $link_mode  'slug'|'permalink'
		 * @return array[]
		 */
		function tfree_build_recommend_products_payload( $product_ids, $max = 4, $image_size = 'full', $link_mode = 'slug' ) {
			$recommend_products = array();

			foreach ( (array) $product_ids as $product_id ) {
				$product = wc_get_product( $product_id );
				if ( empty( $product ) ) {
					continue;
				}

				$image_url = tfree_get_product_image_url( $product, $image_size, true );
				if ( ! $image_url ) {
					continue;
				}

				$link_value = ( $link_mode === 'permalink' ) ? get_permalink( $product_id ) : $product->get_slug();

				$recommend_products[] = array(
					'product_id' => $product->get_id(),
					'name'       => $product->get_name(),
					'slug'       => $link_value,
					'price'      => $product->get_price(),
					'sku'        => $product->get_sku(),
					'image'      => $image_url,
				);

				if ( count( $recommend_products ) === (int) $max ) {
					break;
				}
			}

			return $recommend_products;
		}
	}

	if ( ! function_exists( 'tfree_get_variation_context' ) ) {
		/**
		 * Fast replacement for scanning get_available_variations().
		 *
		 * Returns:
		 * - image_url: URL of the variation image (or '' if none)
		 * - attribute_qs: string like '&attribute_pa_size=large&attribute_pa_color=red'
		 */
		function tfree_get_variation_context( $variation_id, $image_size = 'full' ) {
			static $cache = array();

			$variation_id = (int) $variation_id;
			$key          = $variation_id . '|' . (string) $image_size;

			if ( array_key_exists( $key, $cache ) ) {
				return $cache[ $key ];
			}

			$image_url = '';
			$qs        = '';

			if ( $variation_id > 0 ) {
				$variation = wc_get_product( $variation_id );
				if ( $variation && method_exists( $variation, 'get_image_id' ) ) {
					$image_id = (int) $variation->get_image_id();
					if ( $image_id ) {
						$image_url = (string) wp_get_attachment_image_url( $image_id, $image_size );
					}
				}

				if ( function_exists( 'wc_get_product_variation_attributes' ) ) {
					$attrs = wc_get_product_variation_attributes( $variation_id );
					if ( is_array( $attrs ) && $attrs ) {
						foreach ( $attrs as $attr_key => $attr_val ) {
							$qs .= '&' . $attr_key . '=' . $attr_val;
						}
					}
				}
			}

			$cache[ $key ] = array( $image_url, $qs );
			return $cache[ $key ];
		}
	}

	if ( ! function_exists( 'trackfree_update_order_status' ) ) {
		function trackfree_update_order_status( $shipment_details, $order_id ) {
			TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->update_order_status( $shipment_details, $order_id );
		}
	}

	if ( ! function_exists( 'trackfree_track_page_url' ) ) {
		function trackfree_track_page_url( $tracking_num = '', $preview = false ) {
			return TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->track_page_url( $tracking_num, $preview );
		}
	}

	if ( ! function_exists( 'trackfree_get_category_by_id' ) ) {
		function trackfree_get_category_by_id( $category_id ) {
			return TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->get_category_by_id( $category_id );
		}
	}

	if ( ! function_exists( 'get_trackfree_order_details' ) ) {
		function get_trackfree_order_details( $data ) {
			return TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->rest_get_order_details( $data );
		}
	}

	if ( ! function_exists( 'update_trackfree_tracking_details' ) ) {
		function update_trackfree_tracking_details( $data ) {
			return TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->rest_update_tracking_details( $data );
		}
	}

	if ( ! function_exists( 'trackfree_create_auto_coupon' ) ) {
		function trackfree_create_auto_coupon( $data ) {
			return TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->rest_create_auto_coupon( $data );
		}
	}

	TrackFree_WooCommerce_Tracking_Plugin::instance( __FILE__ )->boot();
}
