<?php
/**
 * AuctionForge Site Statistics — Visitor → Email map
 *
 * Bridges the anonymous visitor stream (af_vid) to the user's email at the
 * moment they're observed logged-in. Once a (visitor_hash, email) pair is
 * recorded, every af_stats_* row for that visitor_hash can be resolved to
 * the email by JOIN — turning anonymous browsing history into per-user
 * behaviour for downstream marketing aggregation.
 */

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

class AF_Stats_Visitor_Email_Map {

    const TABLE = 'af_stats_visitor_emails';

    /**
     * Record (or refresh last_seen on) a (visitor_hash, email) pair.
     * Idempotent — safe to call on every authenticated tracker hit.
     */
    public static function record($visitor_hash, $email, $ip = '') {
        if (empty($visitor_hash) || empty($email)) return false;

        $email = strtolower(trim($email));
        if (!is_email($email)) return false;

        global $wpdb;
        $table = $wpdb->prefix . self::TABLE;

        // Defensive: if the migration somehow hasn't run yet on this site
        // (race window on first request after auto-update), skip silently
        // rather than throw a fatal that breaks tracking.
        if (!self::table_exists()) {
            return false;
        }

        $now = current_time('mysql', true);

        $wpdb->query($wpdb->prepare(
            "INSERT INTO $table (visitor_hash, user_email, ip_address, first_seen, last_seen)
             VALUES (%s, %s, %s, %s, %s)
             ON DUPLICATE KEY UPDATE
                last_seen = VALUES(last_seen),
                ip_address = VALUES(ip_address)",
            $visitor_hash,
            $email,
            $ip,
            $now,
            $now
        ));

        return true;
    }

    /**
     * Look up the most recent email for a visitor_hash.
     * Returns null if no mapping exists yet.
     */
    public static function lookup($visitor_hash) {
        if (empty($visitor_hash)) return null;
        if (!self::table_exists()) return null;

        global $wpdb;
        $table = $wpdb->prefix . self::TABLE;

        return $wpdb->get_var($wpdb->prepare(
            "SELECT user_email FROM $table
             WHERE visitor_hash = %s
             ORDER BY last_seen DESC LIMIT 1",
            $visitor_hash
        ));
    }

    /**
     * Look up every visitor_hash ever seen for an email.
     * Used by sync handlers to gather a user's behavioural events across
     * sessions and devices.
     */
    public static function lookup_hashes_for_email($email) {
        if (empty($email)) return array();
        if (!self::table_exists()) return array();

        $email = strtolower(trim($email));

        global $wpdb;
        $table = $wpdb->prefix . self::TABLE;

        $rows = $wpdb->get_col($wpdb->prepare(
            "SELECT DISTINCT visitor_hash FROM $table WHERE user_email = %s",
            $email
        ));

        return $rows ?: array();
    }

    /**
     * Whether the underlying table exists yet.
     * Cached per-request so we don't hit information_schema on every hit.
     */
    private static function table_exists() {
        static $exists = null;
        if ($exists !== null) return $exists;

        global $wpdb;
        $table = $wpdb->prefix . self::TABLE;
        $exists = ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) === $table);
        return $exists;
    }
}
