<?php
/**
 * Bizmart — Shared helper functions.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

// Shared helper functions for Bizmart core (centralized)

if (!function_exists('bizmart_final_import_parse_meta_keys')) {
    function bizmart_final_import_parse_meta_keys($raw): array {
        $raw = is_string($raw) ? $raw : '';
        $raw = sanitize_text_field(wp_unslash($raw));
        $parts = array_map('trim', explode(',', $raw));
        $parts = array_values(array_filter($parts, function($v) {
            return is_string($v) && $v !== '';
        }));
        return $parts;
    }
}

if (!function_exists('bizmart_final_import_normalize_price')) {
    function bizmart_final_import_normalize_price($raw) {
        if ($raw === null) return null;
        $raw = is_string($raw) ? $raw : (string) $raw;
        $raw = trim($raw);
        if ($raw === '') return null;

        $raw = preg_replace('/[\s\x{00A0}]/u', '', $raw);
        $raw = preg_replace('/[^0-9,\.\-]/', '', $raw);
        if ($raw === '' || $raw === '-' || $raw === ',' || $raw === '.') return null;

        if (strpos($raw, ',') !== false && strpos($raw, '.') !== false) {
            $raw = str_replace(',', '', $raw);
        } else {
            $raw = str_replace(',', '.', $raw);
        }

        if (function_exists('wc_format_decimal')) {
            $raw = wc_format_decimal($raw);
        }

        if (!is_numeric($raw)) return null;
        return (string) $raw;
    }
}

if (!function_exists('bizmart_final_import_lock_acquire')) {
    function bizmart_final_import_lock_acquire(string $job_id, int $ttl = 120): bool {
        $ttl = max(30, $ttl);
        $key = 'bizmart_final_import_lock';
        $lock = get_transient($key);
        if (is_array($lock) && !empty($lock['job_id']) && $lock['job_id'] !== $job_id) {
            return false;
        }
        set_transient($key, ['job_id' => $job_id, 'ts' => time()], $ttl);
        return true;
    }
}

if (!function_exists('bizmart_final_import_lock_release')) {
    function bizmart_final_import_lock_release(string $job_id): void {
        $key = 'bizmart_final_import_lock';
        $lock = get_transient($key);
        if (is_array($lock) && !empty($lock['job_id']) && $lock['job_id'] === $job_id) {
            delete_transient($key);
        }
    }
}

if (!function_exists('bizmart_get_option')) {
    /**
     * Get a Bizmart option. Checks standalone option first, then the
     * consolidated bizmart_settings array. Uses static cache per-request.
     */
    function bizmart_get_option(string $key, $default = '') {
        static $settings_cache = null;

        // Fast path: check standalone option
        $direct = get_option($key, null);
        if ($direct !== null) {
            return $direct;
        }

        // Lazy-load the settings array once per request
        if ($settings_cache === null) {
            $settings_cache = get_option('bizmart_settings', []);
            if (!is_array($settings_cache)) $settings_cache = [];
        }

        return array_key_exists($key, $settings_cache) ? $settings_cache[$key] : $default;
    }
}

if (!function_exists('bizmart_update_option')) {
    /**
     * Update a Bizmart option. Writes to both standalone key and the
     * consolidated settings array. Invalidates the static cache.
     */
    function bizmart_update_option(string $key, $value): void {
        // Use autoload=yes for frequently-read options
        update_option($key, $value, true);

        $opts = get_option('bizmart_settings', []);
        if (!is_array($opts)) $opts = [];
        $opts[$key] = $value;
        update_option('bizmart_settings', $opts, true);

        // Invalidate per-request static cache in bizmart_get_option
        // (The static var resets on next request anyway, but clear for same-request reads)
    }
}

if (!function_exists('bizmart_check_ajax_nonce')) {
    /**
     * Verify AJAX nonce. Sends 403 JSON error and dies on failure.
     * Accepts both 'bizmart-analytics-nonce' and 'bizmart-ajax-nonce' for backward compat.
     */
    function bizmart_check_ajax_nonce(string $request_key = 'nonce'): void {
        $nonce = isset($_REQUEST[$request_key]) ? sanitize_text_field(wp_unslash($_REQUEST[$request_key])) : '';
        if (!$nonce) {
            wp_send_json_error(['message' => bizmart_text('Invalid nonce', 'Nonce invalide', 'رمز الأمان (nonce) غير صالح')], 403);
            wp_die(); // belt-and-suspenders
        }

        // Accept either nonce action for backward compatibility with addons
        if (wp_verify_nonce($nonce, 'bizmart-analytics-nonce') || wp_verify_nonce($nonce, 'bizmart-ajax-nonce')) {
            return;
        }

        wp_send_json_error(['message' => bizmart_text('Invalid nonce', 'Nonce invalide', 'رمز الأمان (nonce) غير صالح')], 403);
        wp_die();
    }
}

if (!function_exists('bizmart_admin_lang')) {
    function bizmart_admin_lang(): string {
        $lang = bizmart_get_option('biz_admin_language', 'en');
        if ($lang === 'fr') return 'fr';
        if ($lang === 'ar') return 'ar';
        return 'en';
    }
}

if (!function_exists('bizmart_text')) {
    function bizmart_text(string $en, ?string $fr = null, ?string $ar = null): string {
        $lang = bizmart_admin_lang();
        if ($lang === 'fr') return $fr ?? $en;
        if ($lang === 'ar') {
            if ($ar !== null) return $ar;
            // Lazy-load the Arabic translation file if not yet loaded
            if (!function_exists('bizmart_i18n_ar')) {
                $ar_file = defined('BIZMART_CORE_DIR') ? BIZMART_CORE_DIR . 'includes/i18n-ar.php' : '';
                if ($ar_file && file_exists($ar_file)) {
                    require_once $ar_file;
                }
            }
            return function_exists('bizmart_i18n_ar') ? bizmart_i18n_ar($en) : $en;
        }
        return $en;
    }
}

if (!function_exists('bizmart_e')) {
    function bizmart_e(string $en, ?string $fr = null, ?string $ar = null): void {
        echo esc_html(bizmart_text($en, $fr, $ar));
    }
}

if (!function_exists('bizmart_get_currency_symbol')) {
    function bizmart_get_currency_symbol(): string {
        // Prefer WooCommerce currency symbol when WooCommerce is active.
        if (function_exists('get_woocommerce_currency_symbol') && function_exists('get_woocommerce_currency')) {
            $wc = (string) get_woocommerce_currency();
            if ($wc !== '') {
                return (string) get_woocommerce_currency_symbol($wc);
            }
        }

        // Fallback to plugin-level configured default currency option.
        $currency = (string) bizmart_get_option('biz_default_currency', '');
        if ($currency === '') return '';
        if (function_exists('get_woocommerce_currency_symbol')) {
            return (string) get_woocommerce_currency_symbol($currency);
        }
        return $currency;
        }
    }
