<?php

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

class AIEO_Push_Identity {

    
    public static function identify_by_email($email, $name = '') {
        global $wpdb;

        $email = sanitize_email((string) $email);
        $out   = array('matched' => false, 'user_id' => 0, 'rows' => 0);
        if ($email === '' || !is_email($email)) {
            return $out;
        }

        $session_token = self::session_token();
        if ($session_token === '') {
            return $out; 
        }

        
        $user    = get_user_by('email', $email);
        $user_id = ($user instanceof WP_User) ? (int) $user->ID : 0;
        $out['user_id'] = $user_id;
        $out['matched'] = $user_id > 0;

        $table = $wpdb->prefix . 'aieo_push_subscriptions';
        $now   = current_time('mysql', true);

        
        
        if ($user_id > 0) {
            $out['rows'] = (int) $wpdb->query($wpdb->prepare(
                "UPDATE {$table}
                    SET identified_email = %s, identified_at = %s,
                        user_id = IF(user_id = 0, %d, user_id)
                  WHERE session_token = %s",
                $email, $now, $user_id, $session_token
            ));
        } else {
            $out['rows'] = (int) $wpdb->query($wpdb->prepare(
                "UPDATE {$table}
                    SET identified_email = %s, identified_at = %s
                  WHERE session_token = %s",
                $email, $now, $session_token
            ));
        }

        
        do_action('aieo_push_identity_recognised', $email, $user_id, $name);

        return $out;
    }

    
    private static function session_token() {
        if (empty($_COOKIE['aieo_push_session'])) {
            return '';
        }
        $raw = preg_replace('/[^a-z0-9]/i', '', (string) wp_unslash($_COOKIE['aieo_push_session']));
        return $raw === '' ? '' : substr($raw, 0, 64);
    }
}
