<?php

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

class AIEO_Identity_Bridge {

    const META_AUDIENCE        = 'aieo_audience_key';
    const META_EFFECTIVE_TIER  = 'aieo_effective_tier';
    const META_LOYALTY_CLASS   = 'aieo_loyalty_class';
    const META_DEFAULT_ROLE    = 'aieo_default_role_pricing_tier';
    const META_VERSION         = 'aieo_identity_version';

    const SCHEMA_VERSION       = 1;

    
    private static $hooks_registered = false;

    
    public static function bootstrap() {
        if (self::$hooks_registered) { return; }
        self::$hooks_registered = true;

        
        
        add_action('profile_update',   array(__CLASS__, 'on_user_change'), 25, 1);
        add_action('user_register',    array(__CLASS__, 'on_user_change'), 25, 1);
        add_action('set_user_role',    array(__CLASS__, 'on_user_change'), 25, 1);
        add_action('add_user_role',    array(__CLASS__, 'on_user_change'), 25, 1);
        add_action('remove_user_role', array(__CLASS__, 'on_user_change'), 25, 1);
        add_action('wp_login', function ($login, $user) {
            if ($user instanceof WP_User) {
                self::on_user_change($user->ID);
            }
        }, 25, 2);

        
        
        add_action('aieo_dmm_loyalty_assignment_saved', array(__CLASS__, 'on_user_change'), 10, 1);
        add_action('aieo_dmm_loyalty_assignment_deleted', array(__CLASS__, 'on_user_change'), 10, 1);
    }

    
    public static function on_user_change($user_id) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) { return; }
        self::recompute($user_id);
    }

    
    public static function recompute($user_id) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) {
            return self::guest_facts();
        }

        $user = get_userdata($user_id);
        if (!$user) {
            return self::guest_facts();
        }

        $effective_tier  = self::resolve_effective_tier($user_id);
        $loyalty_class   = self::resolve_loyalty_class_slug($user_id);
        $default_role    = self::resolve_default_role($user);
        $audience_key    = self::compose_audience_key($effective_tier, $default_role);

        update_user_meta($user_id, self::META_AUDIENCE,        $audience_key);
        update_user_meta($user_id, self::META_EFFECTIVE_TIER,  $effective_tier);
        update_user_meta($user_id, self::META_LOYALTY_CLASS,   $loyalty_class);
        update_user_meta($user_id, self::META_DEFAULT_ROLE,    $default_role);
        update_user_meta($user_id, self::META_VERSION,         self::SCHEMA_VERSION);

        return array(
            'audience_key'   => $audience_key,
            'effective_tier' => $effective_tier,
            'loyalty_class'  => $loyalty_class,
            'default_role'   => $default_role,
        );
    }

    
    public static function audience_key_for_current_user() {
        if (!is_user_logged_in()) {
            return 'guest';
        }
        $user_id = get_current_user_id();
        $cached  = get_user_meta($user_id, self::META_AUDIENCE, true);
        if (is_string($cached) && $cached !== '') {
            return $cached;
        }
        $facts = self::recompute($user_id);
        return $facts['audience_key'];
    }

    
    public static function known_audience_keys() {
        global $wpdb;

        $keys = array('guest');

        
        
        
        if (class_exists('AIEO_DMM_Settings')) {
            $enabled_roles = (array) AIEO_DMM_Settings::get('enabled_roles', array());
            foreach ($enabled_roles as $r) {
                $r = (string) $r;
                if ($r !== '') { $keys[] = 'role:' . $r; }
            }
        }

        
        $defs = $wpdb->prefix . 'aieo_dmm_loyalty_classes';
        $tier_ids = array();
        if ($wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s",
            $defs
        ))) {
            
            $tier_ids = $wpdb->get_col("SELECT id FROM {$defs} WHERE enabled = 1");
        }
        foreach ($tier_ids as $id) {
            $keys[] = 'tier:' . (int) $id;
        }

        return array_values(array_unique($keys));
    }

    
    
    

    private static function guest_facts() {
        return array(
            'audience_key'   => 'guest',
            'effective_tier' => 0,
            'loyalty_class'  => '',
            'default_role'   => '',
        );
    }

    
    private static function compose_audience_key($effective_tier, $default_role) {
        $effective_tier = (int) $effective_tier;
        if ($effective_tier > 0) {
            return 'tier:' . $effective_tier;
        }
        if (is_string($default_role) && $default_role !== '') {
            return 'role:' . $default_role;
        }
        return 'role:customer';
    }

    
    private static function resolve_effective_tier($user_id) {
        global $wpdb;
        $assign = $wpdb->prefix . 'aieo_dmm_loyalty_assignments';
        $defs   = $wpdb->prefix . 'aieo_dmm_loyalty_classes';

        $exists = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (%s, %s)",
            $assign, $defs
        ));
        if ($exists < 2) { return 0; }

        
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT d.id, d.extra_percent
             FROM {$assign} a
             INNER JOIN {$defs} d ON d.id = a.class_id
             WHERE a.user_id = %d AND d.enabled = 1
             ORDER BY d.extra_percent DESC, d.id ASC
             LIMIT 1",
            $user_id
        ), ARRAY_A);

        return $row ? (int) $row['id'] : 0;
    }

    
    private static function resolve_loyalty_class_slug($user_id) {
        global $wpdb;
        $assign = $wpdb->prefix . 'aieo_dmm_loyalty_assignments';
        $defs   = $wpdb->prefix . 'aieo_dmm_loyalty_classes';

        $exists = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (%s, %s)",
            $assign, $defs
        ));
        if ($exists < 2) { return ''; }

        
        $name = $wpdb->get_var($wpdb->prepare(
            "SELECT d.slug
             FROM {$assign} a
             INNER JOIN {$defs} d ON d.id = a.class_id
             WHERE a.user_id = %d AND d.enabled = 1
             ORDER BY d.extra_percent DESC, d.id ASC
             LIMIT 1",
            $user_id
        ));

        
        
        if ($name === null) {
            $cols = $wpdb->get_col("SHOW COLUMNS FROM {$defs}");
            if (is_array($cols) && in_array('name', $cols, true) && !in_array('slug', $cols, true)) {
                
                $name = $wpdb->get_var($wpdb->prepare(
                    "SELECT d.name
                     FROM {$assign} a
                     INNER JOIN {$defs} d ON d.id = a.class_id
                     WHERE a.user_id = %d AND d.enabled = 1
                     ORDER BY d.extra_percent DESC, d.id ASC
                     LIMIT 1",
                    $user_id
                ));
            }
        }
        return is_string($name) ? sanitize_key($name) : '';
    }

    
    private static function resolve_default_role(WP_User $user) {
        $roles = is_array($user->roles) ? $user->roles : array();
        if (empty($roles)) { return ''; }

        $enabled_roles = array();
        if (class_exists('AIEO_DMM_Settings')) {
            $enabled_roles = (array) AIEO_DMM_Settings::get('enabled_roles', array());
        }
        if (empty($enabled_roles)) {
            
            return (string) reset($roles);
        }

        sort($roles);
        foreach ($roles as $r) {
            if (in_array($r, $enabled_roles, true)) {
                return (string) $r;
            }
        }
        return (string) reset($roles);
    }
}

if (!function_exists('aieo_audience_key_for_current_user')) {
    function aieo_audience_key_for_current_user() {
        return AIEO_Identity_Bridge::audience_key_for_current_user();
    }
}
