<?php

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

class AIEO_DMM_Marketplace_Taxonomy {

    const SOURCE_GOOGLE   = 'google';
    const SOURCE_FACEBOOK = 'facebook';

    
    private static $cache = array();

    
    private static function file_path($source, $locale = null) {
        $locale = (string) ($locale ?: self::current_locale());
        $base   = plugin_dir_path(__FILE__) . '../../../assets/marketplace-taxonomies/';
        
        
        
        $candidates = array();
        if ($source === self::SOURCE_GOOGLE) {
            $candidates[] = $base . 'google-taxonomy.' . $locale . '.json';
            $candidates[] = $base . 'google-taxonomy.en-US.json';
        } elseif ($source === self::SOURCE_FACEBOOK) {
            
            $candidates[] = $base . 'facebook-taxonomy.en-US.json';
        }
        foreach ($candidates as $p) {
            if (is_readable($p)) { return $p; }
        }
        return '';
    }

    
    public static function current_locale() {
        return (string) apply_filters(
            'aieo_dmm_marketplace_taxonomy_locale',
            get_option('aieo_dmm_marketplace_taxonomy_locale', 'el-GR')
        );
    }

    
    public static function payload($source) {
        if (isset(self::$cache[$source])) { return self::$cache[$source]; }
        $path = self::file_path($source);
        if ($path === '') {
            self::$cache[$source] = null;
            return null;
        }
        $raw = file_get_contents($path);
        if ($raw === false) {
            self::$cache[$source] = null;
            return null;
        }
        $decoded = json_decode($raw, true);
        if (!is_array($decoded) || empty($decoded['nodes'])) {
            self::$cache[$source] = null;
            return null;
        }
        self::$cache[$source] = $decoded;
        return $decoded;
    }

    
    public static function get_node($source, $id) {
        $p = self::payload($source);
        if (!$p) { return null; }
        $key = (string) (int) $id;
        if (!isset($p['by_id'][$key])) { return null; }
        $idx = (int) $p['by_id'][$key];
        return $p['nodes'][$idx] ?? null;
    }

    
    public static function get_children($source, $parent_id) {
        $p = self::payload($source);
        if (!$p) { return array(); }
        $parent_id = (int) $parent_id;
        $out = array();
        if ($parent_id <= 0) {
            foreach ($p['roots'] as $idx) { $out[] = $p['nodes'][$idx]; }
        } else {
            foreach ($p['nodes'] as $n) {
                if ((int) ($n['p'] ?? 0) === $parent_id) { $out[] = $n; }
            }
        }
        usort($out, function ($a, $b) {
            return strcasecmp((string) ($a['n'] ?? ''), (string) ($b['n'] ?? ''));
        });
        return $out;
    }

    
    public static function search($source, $query, $limit = 25) {
        $q = trim((string) $query);
        if ($q === '') { return array(); }
        $needle = function_exists('mb_strtolower') ? mb_strtolower($q, 'UTF-8') : strtolower($q);

        
        
        
        
        $site_locale = self::current_locale();
        $site_payload = self::payload($source); 
        $site_path_by_id = array();
        if ($site_payload && !empty($site_payload['nodes'])) {
            foreach ($site_payload['nodes'] as $n) {
                $site_path_by_id[(int) $n['i']] = (string) $n['h'];
            }
        }

        $hits = array();
        $seen_ids = array();
        
        
        $locales = self::available_locales($source);
        usort($locales, function ($a, $b) use ($site_locale) {
            if ($a === $site_locale) return -1;
            if ($b === $site_locale) return 1;
            return strcmp($a, $b);
        });
        foreach ($locales as $loc) {
            $p = self::payload_for_locale($source, $loc);
            if (!$p) { continue; }
            foreach ($p['nodes'] as $n) {
                $id = (int) $n['i'];
                if (isset($seen_ids[$id])) { continue; }
                $hay = function_exists('mb_strtolower')
                    ? mb_strtolower((string) $n['h'], 'UTF-8')
                    : strtolower((string) $n['h']);
                if (strpos($hay, $needle) === false) { continue; }
                $hits[] = array(
                    'i'              => $id,
                    'n'              => (string) $n['n'],
                    'p'              => $n['p'] ?? null,
                    'd'              => (int) $n['d'],
                    'h'              => (string) $n['h'],
                    'site_path'      => $site_path_by_id[$id] ?? (string) $n['h'],
                    'matched_locale' => $loc,
                );
                $seen_ids[$id] = true;
                if (count($hits) >= $limit) { return $hits; }
            }
        }
        return $hits;
    }

    
    private static function payload_for_locale($source, $locale) {
        $cache_key = $source . '|' . $locale;
        if (isset(self::$cache[$cache_key])) { return self::$cache[$cache_key]; }
        $base = plugin_dir_path(__FILE__) . '../../../assets/marketplace-taxonomies/';
        $path = '';
        if ($source === self::SOURCE_GOOGLE) {
            $path = $base . 'google-taxonomy.' . $locale . '.json';
        } elseif ($source === self::SOURCE_FACEBOOK) {
            $path = $base . 'facebook-taxonomy.' . $locale . '.json';
        }
        if (!is_readable($path)) {
            self::$cache[$cache_key] = null;
            return null;
        }
        $raw = file_get_contents($path);
        if ($raw === false) {
            self::$cache[$cache_key] = null;
            return null;
        }
        $decoded = json_decode($raw, true);
        if (!is_array($decoded) || empty($decoded['nodes'])) {
            self::$cache[$cache_key] = null;
            return null;
        }
        self::$cache[$cache_key] = $decoded;
        return $decoded;
    }

    
    public static function resolve_pair($source, $id) {
        $n = self::get_node($source, $id);
        if (!$n) { return null; }
        return array(
            'id'   => (int) $n['i'],
            'path' => (string) $n['h'],
        );
    }

    
    public static function available_locales($source) {
        $base = plugin_dir_path(__FILE__) . '../../../assets/marketplace-taxonomies/';
        $glob = $source === self::SOURCE_GOOGLE
            ? $base . 'google-taxonomy.*.json'
            : $base . 'facebook-taxonomy.*.json';
        $files = glob($glob) ?: array();
        $out = array();
        foreach ($files as $f) {
            if (preg_match('/-(?:taxonomy)\.([^.]+)\.json$/', basename($f), $m)) {
                $out[] = $m[1];
            }
        }
        sort($out);
        return $out;
    }
}
