<?php
/**
 * Core Functions
 *
 * Holds core functions for kkart-admin.
 *
 * @package Kkart\Admin\Functions
 */

use \Automattic\Kkart\Admin\Loader;

/**
 * Format a number using the decimal and thousands separator settings in Kkart.
 *
 * @param mixed $number Number to be formatted.
 * @return string
 */
function kkart_admin_number_format( $number ) {
	$currency_settings = Loader::get_currency_settings();
	return number_format(
		$number,
		0,
		$currency_settings['decimalSeparator'],
		$currency_settings['thousandSeparator']
	);
}

/**
 * Retrieves a URL to relative path inside Kkart admin with
 * the provided query parameters.
 *
 * @param  string $path Relative path of the desired page.
 * @param  array  $query Query parameters to append to the path.
 *
 * @return string       Fully qualified URL pointing to the desired path.
 */
function kkart_admin_url( $path = null, $query = array() ) {
	if ( ! empty( $query ) ) {
		$query_string = http_build_query( $query );
		$path         = $path ? '&path=' . $path . '&' . $query_string : '';
	}

	return admin_url( 'admin.php?page=kkart-admin' . $path, dirname( __FILE__ ) );
}

/**
 * Record an event using Tracks.
 *
 * @internal Kkart core only includes Tracks in admin, not the REST API, so we need to include it.
 * @param string $event_name Event name for tracks.
 * @param array  $properties Properties to pass along with event.
 */
function kkart_admin_record_tracks_event( $event_name, $properties = array() ) {
	// KKART post types must be registered first for KKART_Tracks to work.
	if ( ! post_type_exists( 'product' ) ) {
		return;
	}

	if ( ! class_exists( 'KKART_Tracks' ) ) {
		if ( ! defined( 'KKART_ABSPATH' ) || ! file_exists( KKART_ABSPATH . 'includes/tracks/class-kkart-tracks.php' ) ) {
			return;
		}

		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks-event.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks-client.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks-footer-pixel.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-site-tracking.php';
	}

	KKART_Tracks::record_event( $event_name, $properties );
}
