<?php
/**
 * Global utility functions for Lean Cart Share and Save
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Returns the plugin version, with a timestamp suffix in WP_DEBUG mode for cache busting.
 * Mirrors Lean Player's leanpl_get_version().
 *
 * @return string
 */
function lean_csns_get_version() {
    $version = LEAN_CSNS_VERSION;

    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        $version .= '-' . time();
    }

    return $version;
}

/**
 * Whether pro features are active. Mirrors Lean Player's leanpl_is_pro_active().
 *
 * Pro is active only when the pro/ loader shipped and its init fn is loaded
 * (Base::load_pro() runs it for the -pro folder or the dev switch).
 *
 * @return bool
 */
function lean_csns_is_pro_active() {
    return file_exists(LEAN_CSNS_PL_DIR . 'pro/pro-loader.php')
        && function_exists('lean_csns_pro_init');
}

/**
 * Global wrapper for accessing plugin settings with smart defaults
 * 
 * @param string|null $key     Setting key (supports dot notation)
 * @param mixed       $default Default value if setting not found
 * @return mixed
 */
function lean_csns_get_option($key = null, $default = null) {
    $settings = get_option('lean_csns_settings', array());
    
    // If no settings exist or they're incomplete, merge with defaults
    if (empty($settings) || lean_csns_settings_need_merge($settings)) {
        $default_settings = include LEAN_CSNS_PL_DIR . 'includes/default-settings.php';
        $settings = lean_csns_merge_settings($default_settings, $settings);
        
        // Update the option with merged settings for future use
        update_option('lean_csns_settings', $settings);
    }
    
    if ($key === null) {
        return $settings; // Return all settings
    }
    
    // Support dot notation: 'cart_share.enable'
    if (strpos($key, '.') !== false) {
        $keys = explode('.', $key);
        $value = $settings;
        
        foreach ($keys as $k) {
            if (!isset($value[$k])) {
                return $default;
            }
            $value = $value[$k];
        }
        
        return $value;
    }
    
    // Direct key access
    return isset($settings[$key]) ? $settings[$key] : $default;
}

/**
 * Update plugin settings
 * 
 * @param array $settings New settings array
 * @return bool
 */
function lean_csns_update_settings($settings) {
    return update_option('lean_csns_settings', $settings);
}

/**
 * Reset settings to default values
 * 
 * @return bool
 */
function lean_csns_reset_settings() {
    $default_settings = include LEAN_CSNS_PL_DIR . 'includes/default-settings.php';
    return lean_csns_update_settings($default_settings);
}

/**
 * Check if settings need to be merged with defaults
 * 
 * @param array $settings Current settings
 * @return bool True if settings are incomplete and need merging
 */
function lean_csns_settings_need_merge($settings) {
    if (empty($settings)) {
        return true;
    }
    
    // Check for required top-level keys
    $required_keys = ['cart_share', 'cart_save', 'data_management'];
    foreach ($required_keys as $key) {
        if (!isset($settings[$key])) {
            return true;
        }
    }
    
    // Check for required cart_share keys
    $required_cart_share = ['enable', 'url_format', 'expiry_days'];
    foreach ($required_cart_share as $key) {
        if (!isset($settings['cart_share'][$key])) {
            return true;
        }
    }
    
    return false;
}

/**
 * Merge user settings with default settings
 *
 * @param array $defaults Default settings structure
 * @param array $user_settings User's current settings
 * @return array Merged settings with all required keys
 */
function lean_csns_merge_settings($defaults, $user_settings) {
    if (empty($user_settings)) {
        return $defaults;
    }

    // Recursive merge that preserves user values but adds missing defaults
    return array_replace_recursive($defaults, $user_settings);
}

/**
 * Single source of truth accessor. Mirrors leanpl_ssot() in the player plugin.
 *
 * @param string      $section Top-level key in ssot.php.
 * @param string|null $key     Sub-key, or null to return the whole section.
 * @return mixed
 */
function lean_csns_ssot( $section, $key = null ) {
	static $data = null;
	if ( $data === null ) {
		$data = include LEAN_CSNS_PL_DIR . 'includes/ssot.php';
	}
	if ( $key === null ) {
		return $data[ $section ] ?? [];
	}
	return $data[ $section ][ $key ] ?? null;
}

/**
 * Build the upgrade URL with UTM params. Mirrors leanpl_get_upgrade_url().
 *
 * @param array $args UTM overrides and scroll_to anchor.
 * @return string
 */
function lean_csns_get_upgrade_url( $args = [] ) {
	$defaults = [
		'utm_source'   => 'plugin-free',
		'utm_medium'   => 'modal',
		'utm_campaign' => 'upgrade',
		'scroll_to'    => '#pricing',
	];

	$args     = wp_parse_args( $args, $defaults );
	$base_url = lean_csns_ssot( 'brand', 'upgrade_base_url' );
	$url      = $base_url . '?utm_source=' . esc_attr( $args['utm_source'] ) . '&utm_medium=' . esc_attr( $args['utm_medium'] ) . '&utm_campaign=' . esc_attr( $args['utm_campaign'] );

	if ( ! empty( $args['scroll_to'] ) ) {
		$url .= $args['scroll_to'];
	}

	return $url;
}

function lean_csns_check_database_version() {
    $current_db_version = get_option('lean_csns_db_version', '0.0.0');

    if (version_compare($current_db_version, LEAN_CSNS_DB_VERSION, '<')) {
        // Run database migration
        Lean_CSNS\Database::get_instance()->create_tables();
        update_option('lean_csns_db_version', LEAN_CSNS_DB_VERSION);
    }
}