<?php

namespace auctionforge\inc\shortcodes;

use Exception;

class CategoriesFilter
{
    public function init() {
        add_shortcode('bp_categories_filter', array($this, 'categories_filter'));
    }

    public function categories_filter()
    {
        $categories = self::collectAuctionsCategories();
        $data = [
            'categories' => $categories
        ];

        do_action('bp_categories_filter_print_action', $data);
    }

    /**
     * @return array
     */
    public static function collectAuctionsCategories()
    {
        global $wpdb;
        $lang = 'en';
        if (function_exists('pll_current_language')) {
            $lang = pll_current_language();
        }

        $sql = "SELECT DISTINCT `meta`.`meta_value`
                FROM " . $wpdb->termmeta . " AS `meta`
                INNER JOIN " . $wpdb->prefix . "bp_meta_data AS `bmeta`
                ON (`meta`.`term_id` = `bmeta`.termId)
                WHERE `meta`.meta_key = '_auction_tags' AND (`bmeta`.lang = '%s')";

        $sql = $wpdb->prepare($sql, $lang);

        $result = $wpdb->get_col($sql);
        $categories = [];
        if (!empty($result)) {
            foreach ($result as $item) {
                try {
                    $data = json_decode($item, true);
                    $data = array_flip($data);
                } catch (Exception $e) {
                    continue;
                }

                if (!empty($data)) {
                    foreach ($data as $key => $value) {
                        $categories[$key][] = $value;
                    }
                }
            }
        }

        return $categories;
    }

    public static function collectAuctionsNumberGrouped($auctionsData)
    {
        $groupedNumbers = [];
        if (!empty($auctionsData)) {
            foreach ($auctionsData as $key => $auctionsDatum) {
                $groupedNumbers[$auctionsDatum][] = $key;
            }
        }
        return $groupedNumbers;
    }
}
//$instance = new CategoriesFilter();
//$instance->init();
