<?php

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

class AIEO_Customer_Intelligence_Query {

    const CI_TABLE = 'aieo_customer_intelligence';
    const CACHE_GROUP = 'aieo_ci_query';
    const CACHE_TTL   = 5 * MINUTE_IN_SECONDS;

    
    public static function get_top_brands($user_id, $limit = 5) {
        $user_id = (int) $user_id;
        $limit   = max(1, (int) $limit);
        if ($user_id <= 0) { return array(); }

        $cache_key = "top_brands:{$user_id}:{$limit}";
        $cached    = wp_cache_get($cache_key, self::CACHE_GROUP);
        if (is_array($cached)) { return $cached; }

        global $wpdb;
        $table = $wpdb->prefix . self::CI_TABLE;
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT brand_affinity_json, top_brand_id
               FROM {$table}
              WHERE wp_user_id = %d
              ORDER BY updated_at DESC
              LIMIT 1",
            $user_id
        ), ARRAY_A);

        $out = array();
        if (is_array($row)) {
            if (!empty($row['brand_affinity_json'])) {
                $decoded = json_decode((string) $row['brand_affinity_json'], true);
                if (is_array($decoded)) {
                    
                    arsort($decoded, SORT_NUMERIC);
                    $out = array_map('intval', array_keys($decoded));
                }
            }
            
            $top = (int) ($row['top_brand_id'] ?? 0);
            if ($top > 0 && !in_array($top, $out, true)) {
                array_unshift($out, $top);
            }
        }
        $out = array_values(array_filter(array_slice($out, 0, $limit), function ($v) { return $v > 0; }));

        wp_cache_set($cache_key, $out, self::CACHE_GROUP, self::CACHE_TTL);
        return $out;
    }

    
    public static function get_wishlisted_brands($user_id) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) { return array(); }
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_wishlist';
        
        
        
        $rows = $wpdb->get_col($wpdb->prepare(
            "SELECT DISTINCT item_id FROM {$table}
              WHERE user_id = %d AND item_type = 'brand'
              ORDER BY date_added DESC",
            $user_id
        ));
        if (!is_array($rows)) { return array(); }
        return array_values(array_filter(array_map('intval', $rows), function ($v) { return $v > 0; }));
    }

    
    public static function get_rated_brands($user_id) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) { return array(); }
        global $wpdb;
        $events = $wpdb->prefix . 'aieo_ratings';
        
        
        $has_object_type = (string) $wpdb->get_var("SHOW COLUMNS FROM `{$events}` LIKE 'object_type'") !== '';
        if (!$has_object_type) { return array(); }

        
        
        
        
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT product_id AS brand_id, rating
               FROM {$events}
              WHERE user_id = %d AND object_type = 'brand'
              ORDER BY product_id, created_at DESC, id DESC",
            $user_id
        ), ARRAY_A);

        $out  = array();
        $seen = array();
        if (is_array($rows)) {
            foreach ($rows as $r) {
                $bid = (int) $r['brand_id'];
                if ($bid <= 0 || isset($seen[$bid])) { continue; }
                $seen[$bid] = true;
                $rating = (int) $r['rating'];
                if ($rating > 0) { $out[$bid] = $rating; }
            }
        }
        return $out;
    }

    
    public static function has_brand_affinity($user_id) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) { return false; }
        global $wpdb;
        $table = $wpdb->prefix . self::CI_TABLE;
        $top = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT top_brand_id FROM {$table} WHERE wp_user_id = %d LIMIT 1",
            $user_id
        ));
        return $top > 0;
    }

    
    public static function get_brand_preferences($user_id, $limit = 10) {
        $user_id = (int) $user_id;
        $limit   = max(1, (int) $limit);
        if ($user_id <= 0) { return array(); }

        $explicit = self::get_wishlisted_brands($user_id);   
        $derived  = self::get_top_brands($user_id, $limit);   

        $out  = array();
        $seen = array();
        foreach (array_merge($explicit, $derived) as $bid) {
            $bid = (int) $bid;
            if ($bid <= 0 || isset($seen[$bid])) { continue; }
            $seen[$bid] = true;
            $out[] = $bid;
            if (count($out) >= $limit) { break; }
        }
        return $out;
    }
}
