<?php



if (! defined('ABSPATH')) {



    exit; // Exit if accessed directly.



}



// Load email template class

if (! class_exists('SensFRX_email_template')) {

    require_once plugin_dir_path(__FILE__) . 'email-templates/class-sensfrx-email-template.php';

}



class SensFRX_Wp_Login_Track

{



    public function wp_login_track($username, WP_User $user)

    {



        $device_id = null;



        $device_id_1 = null;



        $device_id_2 = null;



        $device_id_3 = null;



        $device_id_4 = null;



        $res_bot = null;



        if (isset($_COOKIE['device0'])) {



            $device_id_1 = sanitize_text_field($_COOKIE['device0']);



        }



        if (isset($_COOKIE['device1'])) {



            $device_id_2 = sanitize_text_field($_COOKIE['device1']);



        }



        if (isset($_COOKIE['device2'])) {



            $device_id_3 = sanitize_text_field($_COOKIE['device2']);



        }



        if (isset($_COOKIE['device3'])) {



            $device_id_4 = sanitize_text_field($_COOKIE['device3']);



        }



        $device_id = $device_id_1 . $device_id_2 . $device_id_3 . $device_id_4;



        if (empty($device_id)) {



            $device_id = null;



        }



        global $wpdb;



        $sensfrx_approve = null;



        $options = get_option('sensfrx_options', SensFRX::default_options());



        $sensfrx_policy_options = get_option('sensfrx_policy_options', SensFRX::default_policy_options());



        require_once SENSFRX_DIR . 'sensfrx-php-sdk/SensFRX/autoload.php';



        $sensfrx_master_fraud_allow = $sensfrx_policy_options['sensfrx_master_fraud'];



        if ($sensfrx_master_fraud_allow) {



            $sensfrx_master_fraud_allow = true;



        } else {



            $sensfrx_master_fraud_allow = false;



        }



        $user_data = ($user && isset($user->data->ID)) ? get_userdata($user->data->ID) : null; // Replace $user_id with actual ID



        $created_at = ($user_data && isset($user_data->user_registered)) ? $user_data->user_registered : ''; // This returns in 'Y-m-d H:i:s' format (UTC)



        if (true == $sensfrx_master_fraud_allow) {



            $sensfrx_login_fraud_allow = $sensfrx_policy_options['sensfrx_login_fraud'];



            if ($sensfrx_login_fraud_allow) {



                $sensfrx_login_fraud_allow = true;



            } else {



                $sensfrx_login_fraud_allow = false;



            }



            if (true == $sensfrx_login_fraud_allow) {



                if (isset($options['sensfrx_property_id']) && isset($options['sensfrx_property_secret'])) {



                    $obj = new SensFRX\SensFRX([



                        'property_id'     => $options['sensfrx_property_id'],



                        'property_secret' => $options['sensfrx_property_secret'],



                    ]);



                    $res = $obj->loginAttempt('login_succeeded', $user->data->ID, $device_id, ['email' => $user->data->user_email, 'username' => $username, 'user_created_at' => $created_at]);



                    $sensfrx_whitelisting_check = null;



                    $sensfrx_whitelisting_check_email = $user->data->user_email;



                    $sensfrx_white_list_admin_users = get_users(['role' => 'administrator']);



                    $sensfrx_white_list_admin_info_array = [];



                    foreach ($sensfrx_white_list_admin_users as $user_data) {



                        if ($user_data->user_email === $sensfrx_whitelisting_check_email) {



                            $sensfrx_whitelisting_check = true;



                            break;



                        }



                    }



                    $sensfrx_whitelisting_check_checkbox_allow = $sensfrx_policy_options['sensfrx_whitle_list_email'];



                    if ($sensfrx_whitelisting_check_checkbox_allow) {



                        $sensfrx_whitelisting_check_checkbox_allow = true;



                    } else {



                        $sensfrx_whitelisting_check_checkbox_allow = false;



                    }



                    if (true === $sensfrx_whitelisting_check && true === $sensfrx_whitelisting_check_checkbox_allow) {



                        return;



                    } else {



                        if (isset($res) && gettype($res) !== 'string') {

                            if (isset($res['status']) && $res['status'] === 'error' && $res['error'] === 'USE_CASE_DISABLED') {

                                $errorMessage = $res['message'] ?? 'Something went wrong';

                                $insert_data  = "Login | " . $user->data->user_email . " | Approved | Reason: " . $errorMessage;

                                SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);

                            } else {

                                $res_shadow = SensFRX_DB_Helper::safe_select(

                                    'sensfrx_shadow_activity',

                                    'sensfrx_shadow_status',

                                    '',

                                    [],

                                    '',

                                    ARRAY_A

                                );

                                if (is_array($res_shadow) && !empty($res_shadow) && isset($res_shadow[0]['sensfrx_shadow_status'])) {



                                    if ('0' == $res_shadow[0]['sensfrx_shadow_status']) {



                                        if (isset($res['status']) && null !== $res['status'] && isset($res['severity']) && null !== $res['severity']) {



                                            $status = $res['status'];



                                            $severity = $res['severity'];



                                            if ($status == 'allow' || $status == 'challenge' || $status == 'low') {



                                                $sensfrx_approve = 'approved';



                                            } else {



                                                $sensfrx_approve = $status;



                                            }



                                            $site_title = get_bloginfo('name');



                                            $first_name = $user->data->display_name;



                                            /* The below code is checking the value of the variable ['sensfrx_medium_email']



											and assigning the value to the variable . If the value is truthy,



											is set to true. Otherwise, it is set to false. */



                                            $checkbox_allow = $sensfrx_policy_options['sensfrx_medium_email'];



                                            if ($checkbox_allow) {



                                                $checkbox_allow = true;



                                            } else {



                                                $checkbox_allow = false;



                                            }



                                            $checkbox_deny = $sensfrx_policy_options['sensfrx_deny_email'];



                                            if ($checkbox_deny) {



                                                $checkbox_deny = true;



                                            } else {



                                                $checkbox_deny = false;



                                            }



                                            $checkbox_challenge = $sensfrx_policy_options['sensfrx_challenge_email'];



                                            if ($checkbox_challenge) {



                                                $checkbox_challenge = true;



                                            } else {



                                                $checkbox_challenge = false;



                                            }



                                            if ('challenge' == $status && 'high' == $severity) {



                                                if (true == $checkbox_challenge) {



                                                    $lost_pass_url = wp_lostpassword_url();



                                                    $device = $res['device'];



                                                    $device = (array) $device;



                                                    $to = $user->data->user_email;



                                                    // Get default email content (no database customization)

                                                    $default_email           = SensFRX_email_template::get_default_message('login_challenge');

                                                    $login_challenge_subject = $default_email['subject'];

                                                    $login_challenge_message = $default_email['message'];



                                                    $date = date('Y M d');



                                                    $time = date('H:i:s');



                                                    $allowurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=1';



                                                    $denyurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=0';



                                                    $replacements = [



                                                        '{$client_full_name}'   => $first_name,



                                                        '{$deny_url}'           => $denyurl,



                                                        '{$allow_url}'          => $allowurl,



                                                        '{$default_brand_name}' => $site_title,



                                                        '{$date}'               => $date,



                                                        '{$time}'               => $time,



                                                    ];



                                                    // Use universal email wrapper for professional formatting



                                                    $mailResult = $mailResult = SensFRX_email_template::wrap_and_send($to, $login_challenge_subject, $login_challenge_message, $site_title, $replacements);



                                                    $insert_data = "Login | " . $user->data->user_email . " | " . ucfirst($sensfrx_approve) . " | Risk: " . $severity;

                                                    SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                                } else {



                                                    $insert_data = "Login | " . $user->data->user_email . " | Approved (Challenge policy off) | Risk: " . $severity;

                                                    SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                                }



                                            } else if ('deny' == $status && 'critical' == $severity) {



                                                if (true == $checkbox_deny) {



                                                    $device = $res['device'];



                                                    $device = (array) $device;



                                                    $to = $user->data->user_email;



                                                    $first_name = $user->data->user_nicename;



                                                    // Get default email content (no database customization)

                                                    $default_email      = SensFRX_email_template::get_default_message('login_deny');

                                                    $login_deny_subject = $default_email['subject'];

                                                    $login_deny_message = $default_email['message'];



                                                    $date = date('Y M d');



                                                    $time = date('H:i:s');



                                                    $replacements = [



                                                        '{$client_full_name}'   => $first_name,



                                                        '{$default_brand_name}' => $site_title,



                                                        '{$date}'               => $date,



                                                        '{$time}'               => $time,



                                                    ];



                                                    // Use universal email wrapper for professional formatting



                                                    $mailResult = $mailResult = SensFRX_email_template::wrap_and_send($to, $login_deny_subject, $login_deny_message, $site_title, $replacements);



                                                    $insert_data = "Login | " . $user->data->user_email . " | " . ucfirst($sensfrx_approve) . " | Risk: " . $severity;

                                                    SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                                    sleep(3);



                                                    $results = retrieve_password($user->data->user_login);



                                                    if (true === $results) {



                                                        $message = 'Your account is blocked due to suspicious activities. We have sent a password reset email, please reset your password to activate your account again.';



                                                    } else {



                                                        $message = $results->get_error_message();



                                                    }



                                                    $login_url = site_url(

                                                        'wp-login.php?action=as_ch_dn&as_msg=' . urlencode($message),

                                                        'login'

                                                    );



                                                    wp_logout();

                                                    wp_safe_redirect($login_url);

                                                    exit;



                                                } else {



                                                    $insert_data = "Login | " . $user->data->user_email . " | Approved (Deny policy off) | Risk: " . $severity;

                                                    SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                                }



                                            } else if ('allow' == $status && 'medium' == $severity) {



                                                if (true == $checkbox_allow) {



                                                    global $wpdb;



                                                    $device = $res['device'];



                                                    $device = (array) $device;



                                                    $to = $user->data->user_email;



                                                    $table_name = $wpdb->prefix . 'sensfrx_sleep';



                                                    $sanitized_table_name = esc_sql($table_name);



                                                    $current_time = gmdate('Y-m-d H:i:s');



                                                    $user_id = $user->data->ID;



                                                    $exist_one = false;



                                                    $results = wp_cache_get('sensfrx_admin_24_data', 'sensfrx_group');



                                                    if ($results !== false) {



                                                        $results = $wpdb->get_results("SELECT * FROM wp_sensfrx_sleep");



                                                        wp_cache_replace('sensfrx_admin_24_data', $results, 'sensfrx_group', 86400);



                                                    } else {



                                                        $results = $wpdb->get_results("SELECT * FROM wp_sensfrx_sleep");



                                                        wp_cache_set('sensfrx_admin_24_data', $results, 'sensfrx_group', 86400);



                                                    }



                                                    // $results = $wpdb->get_results($wpdb->prepare('SELECT * FROM `%s`', $sanitized_table_name));



                                                    if ($results) {



                                                        // Loop through the results and do something with each row



                                                        foreach ($results as $row) {



                                                            $cid = $row->cid;



                                                            if ($cid == $user_id) {



                                                                $exist_one = true; // If record found then update query proceed



                                                                break;



                                                            }



                                                        }



                                                    }



                                                    if (true === $exist_one) {



                                                        global $wpdb;



                                                        $table_name = $wpdb->prefix . 'sensfrx_sleep';



                                                        $sanitized_table_name = esc_sql($table_name);



                                                        $results = wp_cache_get('sensfrx_admin_24_check_data', 'sensfrx_group');



                                                        if ($results !== false) {



                                                            $results = $wpdb->get_results($wpdb->prepare('SELECT * FROM wp_sensfrx_sleep WHERE `cid` = %d', $user_id));



                                                            wp_cache_replace('sensfrx_admin_24_check_data', $results, 'sensfrx_group', 86400);



                                                        } else {



                                                            $results = $wpdb->get_results($wpdb->prepare('SELECT * FROM wp_sensfrx_sleep WHERE `cid` = %d', $user_id));



                                                            wp_cache_set('sensfrx_admin_24_check_data', $results, 'sensfrx_group', 86400);



                                                        }



                                                        $d_time = 23;



                                                        // Check if there are any results



                                                        if ($results) {



                                                            foreach ($results as $row) {



                                                                if ($user_id == $row->cid) {



                                                                    $d_time = $row->c_time;



                                                                }



                                                            }



                                                        }



                                                        $timestamp1 = $current_time;



                                                        $timestamp2 = $d_time;



                                                        // Convert the timestamps to DateTime objects



                                                        $datetime1 = new DateTime($timestamp1);



                                                        $datetime2 = new DateTime($timestamp2);



                                                        // Calculate the difference between the two DateTime objects



                                                        $interval = $datetime1->diff($datetime2);



                                                        // Check if the difference is equal to or greater than 24 hours



                                                        if ($interval->m > 0 || $interval->h >= 24 || $interval->d > 0) {



                                                            $device = $res['device'];



                                                            $device = (array) $device;



                                                            global $wpdb;



                                                            $template_login_medium = 'SensFRX client login login ogin 123';



                                                            $table_name = esc_sql( $wpdb->prefix . 'sensfrx_email_templates' );



                                                            $template_medium_login = $wpdb->get_row(



                                                                $wpdb->prepare(

                                                                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized with esc_sql(). WHERE value is properly prepared with %s placeholder.

                                                                    "SELECT * FROM {$table_name} WHERE name1 = %s",



                                                                    $template_login_medium



                                                                )



                                                            );



                                                            if ($template_medium_login) {



                                                                $login_medium_subject = $template_medium_login->subject1;



                                                                $login_medium_message = $template_medium_login->message1;



                                                            } else {



                                                                $login_medium_subject = 'Default Subject';



                                                                $login_medium_message = 'Default Msesage';



                                                            }



                                                            $date = date('Y M d');



                                                            $time = date('H:i:s');



                                                            $allowurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=1';



                                                            $denyurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=0';



                                                            $replacements = [



                                                                '{$client_name}'        => $first_name,



                                                                '{$device_name}'        => $device['name'],



                                                                '{$ip_address}'         => $device['ip'],



                                                                '{$location}'           => $device['location'],



                                                                '{$date}'               => $date,



                                                                '{$time}'               => $time,



                                                                '{$default_brand_name}' => $site_title,



                                                            ];



                                                            $subject = strtr($login_medium_subject, $replacements);



                                                            $message = strtr($login_medium_message, $replacements);



                                                            $headers = ['Content-Type: text/html; charset=UTF-8'];



                                                            $mailResult = $mailResult = wp_mail($to, $subject, $message, $headers);



                                                            // Update the timestamp



                                                            global $wpdb;



                                                            $table_name = $wpdb->prefix . 'sensfrx_sleep';



                                                            $data = [



                                                                'c_time' => $current_time,



                                                            ];



                                                            // The WHERE clause to specify the rows to be updated (for example, updating the row with 'id' equal to 1)



                                                            $where = [



                                                                'cid' => $user_id,



                                                            ];



                                                            // Execute the update query



                                                            $results = wp_cache_get('sensfrx_admin_24_update_data', 'sensfrx_group');



                                                            if ($results !== false) {



                                                                $updated = $wpdb->update($table_name, $data, $where);



                                                                wp_cache_replace('sensfrx_admin_24_update_data', $results, 'sensfrx_group', 86400);



                                                            } else {



                                                                $updated = $wpdb->update($table_name, $data, $where);



                                                                wp_cache_set('sensfrx_admin_24_update_data', $results, 'sensfrx_group', 86400);



                                                            }



                                                            $insert_data = "Login | " . $user->data->user_email . " | " . ucfirst($sensfrx_approve) . " | Risk: " . $severity;

                                                            SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                                        }



                                                    } else {



                                                        global $wpdb;



                                                        $table_name = $wpdb->prefix . 'sensfrx_sleep';



                                                        // Prepare data for insertion



                                                        $data = [



                                                            [



                                                                'cid'    => $user_id,



                                                                'c_time' => $current_time,



                                                            ],



                                                        ];



                                                        // Insert data into the custom table



                                                        $results = wp_cache_get('sensfrx_admin_24_insert_data', 'sensfrx_group');



                                                        if ($results !== false) {



                                                            foreach ($data as $row) {



                                                                $wpdb->insert($table_name, $row);



                                                            }



                                                            wp_cache_replace('sensfrx_admin_24_insert_data', $results, 'sensfrx_group', 86400);



                                                        } else {



                                                            foreach ($data as $row) {



                                                                $wpdb->insert($table_name, $row);



                                                            }



                                                            wp_cache_set('sensfrx_admin_24_insert_data', $results, 'sensfrx_group', 86400);



                                                        }



                                                        // Mail Trigger



                                                        $device = $res['device'];



                                                        $device = (array) $device;



                                                        // Get default email content (no database customization)

                                                        $default_email        = SensFRX_email_template::get_default_message('login_allow');

                                                        $login_medium_subject = $default_email['subject'];

                                                        $login_medium_message = $default_email['message'];



                                                        $date = date('Y M d');



                                                        $time = date('H:i:s');



                                                        $allowurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=1';



                                                        $denyurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=0';



                                                        $replacements = [



                                                            '{$client_name}'        => $first_name,



                                                            '{$client_full_name}'   => $first_name,



                                                            '{$device_name}'        => $device['name'],



                                                            '{$ip_address}'         => $device['ip'],



                                                            '{$location}'           => $device['location'],



                                                            '{$date}'               => $date,



                                                            '{$time}'               => $time,



                                                            '{$default_brand_name}' => $site_title,



                                                        ];



                                                        // Use universal email wrapper for professional formatting



                                                        $mailResult = $mailResult = SensFRX_email_template::wrap_and_send($to, $login_medium_subject, $login_medium_message, $site_title, $replacements);



                                                        $insert_data = "Login | " . $user->data->user_email . " | " . ucfirst($sensfrx_approve) . " | Risk: " . $severity;

                                                        SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                                    }



                                                } else {



                                                    $insert_data = "Login | " . $user->data->user_email . " | Approved (Allow policy off) | Risk: " . $severity;

                                                    SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                                }



                                            } else if ('allow' == $status && 'low' == $severity) {



                                                $insert_data = "Login | " . $user->data->user_email . " | " . ucfirst($sensfrx_approve) . " | Risk: " . $severity;

                                                SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                            }



                                        } else {



                                            $insert_data = "Login | " . $user->data->user_email . " | Approved | Reason: API error fallback";

                                            SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                        }



                                    } else {



                                        $insert_data = "Login | " . $user->data->user_email . " | Allowed (Shadow Mode) | Risk: " . $res['severity'];

                                        SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                    }



                                } else {



                                    $insert_data = "Login | " . $user->data->user_email . " | Error | Reason: Shadow Mode data fetch failed";

                                    SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                                }

                            }

                        } else {



                            $insert_data = "Login | " . $user->data->user_email . " | Error | Reason: Unformatted API response";

                            SensFRX_DB_Helper::insert_activity_log('Account Security', $insert_data);



                        }



                    }



                }



            }



        }



    }



}

