<?php

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

class AIEO_Push_Trigger_NewArrivalLovedBrand extends AIEO_Push_Trigger_Base {

    public function get_id()    { return 'new_arrival_loved_brand'; }
    public function get_label() { return __('New arrival from a loved brand', 'ai-eshop-optimizer'); }
    public function dedup_days() { return 14; }
    public function cap_per_day() { return 1; }
    public function cap_per_week() { return 2; }

    public function produce_candidates($limit = 200) {
        global $wpdb;
        $tbl_ci  = $wpdb->prefix . 'aieo_customer_intelligence';
        $tbl_sub = $wpdb->prefix . 'aieo_push_subscriptions';
        $tbl_tr  = $wpdb->prefix . 'term_relationships';
        $tbl_tt  = $wpdb->prefix . 'term_taxonomy';
        $tbl_t   = $wpdb->prefix . 'terms';
        $tbl_p   = $wpdb->posts;

        $limit = max(1, (int) $limit);

        
        
        
        
        $subs = $wpdb->get_results(
            "SELECT sub.subscription_id, sub.user_id, ci.top_brand_id
             FROM {$tbl_sub} sub
             JOIN {$tbl_ci} ci ON ci.wp_user_id = sub.user_id
             WHERE sub.status = 'active'
               AND sub.user_id > 0
               AND ci.top_brand_id > 0
             LIMIT 5000",
            ARRAY_A
        );
        if (empty($subs)) { return array(); }

        
        
        
        $brand_ids = array_values(array_unique(array_map(
            static function ($row) { return (int) $row['top_brand_id']; },
            $subs
        )));
        if (empty($brand_ids)) { return array(); }
        $in = implode(',', $brand_ids); 

        $brand_rows = $wpdb->get_results(
            "SELECT tt.term_id AS brand_id, t.name AS brand_name,
                    p.ID AS target_product_id, p.post_title AS product_name, p.post_date
             FROM {$tbl_tt} tt
             JOIN {$tbl_t}  t  ON t.term_id = tt.term_id
             JOIN {$tbl_tr} tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
             JOIN {$tbl_p}  p
                  ON p.ID = tr.object_id
                 AND p.post_type   = 'product'
                 AND p.post_status = 'publish'
                 AND p.post_date  >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 14 DAY)
             WHERE tt.term_id IN ({$in})
               AND tt.taxonomy = 'product_brand'
             ORDER BY tt.term_id ASC, p.post_date DESC",
            ARRAY_A
        );
        if (empty($brand_rows)) { return array(); }

        
        $latest_by_brand = array();
        foreach ($brand_rows as $r) {
            $bid = (int) $r['brand_id'];
            if (!isset($latest_by_brand[$bid])) {
                $latest_by_brand[$bid] = $r;
            }
        }

        
        $out = array();
        foreach ($subs as $s) {
            $bid = (int) $s['top_brand_id'];
            if (!isset($latest_by_brand[$bid])) { continue; }
            $b   = $latest_by_brand[$bid];
            $pid = (int) $b['target_product_id'];
            $url = (string) get_permalink($pid);
            $out[] = array(
                'subscription_id'   => (int) $s['subscription_id'],
                'user_id'           => (int) $s['user_id'],
                'target_product_id' => $pid,
                'target_url'        => $url ?: home_url('/'),
                'payload_data'      => array(
                    'product_name' => (string) $b['product_name'],
                    'brand_name'   => (string) $b['brand_name'],
                ),
                '_post_date'        => (string) $b['post_date'],
            );
        }

        
        usort($out, static function ($a, $b) {
            return strcmp($b['_post_date'], $a['_post_date']);
        });
        if (count($out) > $limit) {
            $out = array_slice($out, 0, $limit);
        }
        foreach ($out as &$o) { unset($o['_post_date']); }
        unset($o);

        return $out;
    }
}
