<?php
/**
 * Shared helpers for Defog Analytics.
 *
 * @package Defog
 */

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

/**
 * Fully-qualified table name for a Defog table.
 *
 * @param string $name Short table key (events|stats_daily|dim_daily).
 * @return string
 */
function defog_table( $name ) {
	global $wpdb;
	return $wpdb->prefix . 'defog_' . $name;
}

/**
 * Read a plugin setting with a sane default.
 *
 * @param string $key     Setting key.
 * @param mixed  $default Fallback.
 * @return mixed
 */
function defog_setting( $key, $default = null ) {
	$settings = get_option( 'defog_settings', array() );
	if ( is_array( $settings ) && array_key_exists( $key, $settings ) ) {
		return $settings[ $key ];
	}
	return $default;
}

/**
 * Default settings used on install and as fallbacks.
 *
 * @return array
 */
function defog_default_settings() {
	return array(
		'exclude_logged_in' => 1,   // Do not track users who can edit content.
		'retention_days'    => 90,  // Raw event retention.
		'respect_dnt'       => 0,   // Honour Do-Not-Track browser header.
		'track_events'      => 1,   // Track user actions (outbound clicks).
	);
}

/**
 * Raw-data retention window in days. Configurable via the `retention_days`
 * setting, or programmatically via the `defog_retention_days` filter.
 *
 * @return int
 */
function defog_retention_days() {
	$days = max( 2, (int) defog_setting( 'retention_days', 90 ) );
	return max( 2, (int) apply_filters( 'defog_retention_days', $days ) );
}

/**
 * Local "today" date (Y-m-d) using the site timezone.
 *
 * @return string
 */
function defog_today() {
	return wp_date( 'Y-m-d' );
}

/**
 * Current local datetime (mysql format), site timezone.
 *
 * @return string
 */
function defog_now() {
	return current_time( 'mysql' );
}

/**
 * Record a conversion-funnel signal (deduplicated per visitor / stage / day).
 *
 * @param string $visitor_hash Cookieless visitor hash.
 * @param string $stage        product|cart|checkout|purchase.
 */
function defog_record_funnel( $visitor_hash, $stage ) {
	if ( ! $visitor_hash || ! $stage ) {
		return;
	}
	global $wpdb;
	$table = defog_table( 'funnel' );
	$wpdb->query(
		$wpdb->prepare(
			"INSERT INTO %i (day, occurred_at, visitor_hash, stage) VALUES (%s, %s, %s, %s)
			 ON DUPLICATE KEY UPDATE occurred_at = VALUES(occurred_at)",
					$table,
			defog_today(),
			defog_now(),
			$visitor_hash,
			$stage
		)
	);
}
