<?php
include 'pagename.php';
include $session;
Session::checkSession_app();
include '../config.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$user_id = $_SESSION['id'];

$evp_options_sql = "SELECT option_name, option_value FROM evp_options";
$evp_options_read = $db->select($evp_options_sql);
if ($evp_options_read) {
    $evp_options_check = mysqli_num_rows($evp_options_read);
    if ($evp_options_check > 0) {
        while ($row = $evp_options_read->fetch_assoc()) {
            $option_name[$row['option_name']] = $row['option_value'];
        }
        $evp_options_read->free();
        $s_url = $option_name['site_url'];
        $a_url = $option_name['app_url'];
        $s_path = $option_name['script_path'];
        $site_title = $option_name['site_title'];
        $access_tier = $option_name['access_tier'];
        $system_email = $option_name['system_email'];
    }
}

function sanitize_input($data)
{
    global $db;
    return mysqli_real_escape_string($db->link, htmlspecialchars(stripslashes(trim((string) $data))));
}

function RandomString($length = 20)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function dataAddDomain($domain, $type, $user_id)
{
    global $db;
    $save = false;
    $type = ucwords($type);
    $catch_all_check = ($type == 'Free Account') ? 0 : 1;
    $domain_check_sql = "SELECT * FROM evp_domain_filter_list WHERE user_id = '$user_id' AND name = '$domain' ";
    $domain_check_read = $db->select($domain_check_sql);
    if ($domain_check_read) {
        $count = mysqli_num_rows($domain_check_read);
        if ($count <= 0) {
            $query_insert = "INSERT INTO evp_domain_filter_list ( name, e_type, catch_all_check, user_id) VALUES ('$domain','$type','$catch_all_check','$user_id')";
            $read_insert = $db->insert($query_insert);
            if ($read_insert) {
                $save = true;
            }
        }
    }
    return $save;
}

function dataUpdateDomain($domain, $type, $target_id, $user_id)
{
    global $db;
    $update = false;
    $type = ucwords($type);
    $catch_all_check = ($type == 'Free Account') ? 0 : 1;
    $data_update_sql = "UPDATE evp_domain_filter_list SET name = '$domain', e_type = '$type', catch_all_check = '$catch_all_check' WHERE user_id = '$user_id' AND id = '$target_id' ";
    $data_update_read = $db->update($data_update_sql);
    if ($data_update_read) {
        $update = true;
    }
    return $update;
}

function dataAddProduct($item_name, $item_price, $credit_amount)
{
    global $db;
    $save = false;
    $prod_item_check_sql = "SELECT * FROM evp_products WHERE item_name = '$item_name' ";
    $prod_item_check_read = $db->select($prod_item_check_sql);
    if ($prod_item_check_read) {
        $prod_item_count = mysqli_num_rows($prod_item_check_read);
        if ($prod_item_count <= 0) {
            $query_insert = "INSERT INTO evp_products ( item_name, item_price, credit_amount) VALUES ('$item_name','$item_price','$credit_amount')";
            $read_insert = $db->insert($query_insert);
            if ($read_insert) {
                $save = true;
            }
        }
    }
    return $save;
}

function dataUpdateProduct($item_name, $item_price, $credit_amount, $target_id_item)
{
    global $db;
    $update = false;
    $prod_item_update_sql = "UPDATE evp_products SET item_name = '$item_name', item_price = '$item_price', credit_amount = '$credit_amount' WHERE id = '$target_id_item' ";
    $prod_item_update_read = $db->update($prod_item_update_sql);
    if ($prod_item_update_read) {
        $update = true;
    }
    return $update;
}

function dataAddMX($mx_server)
{
    global $db;
    $save = false;
    $mx_server_check_sql = "SELECT * FROM evp_mx_skiplist WHERE mx_server = '$mx_server'";
    $mx_server_check_read = $db->select($mx_server_check_sql);
    if ($mx_server_check_read) {
        $mx_server_count = mysqli_num_rows($mx_server_check_read);
        if ($mx_server_count <= 0) {
            $query_insert = "INSERT INTO evp_mx_skiplist (mx_server) VALUES ('$mx_server')";
            $read_insert = $db->insert($query_insert);
            if ($read_insert) {
                $save = true;
            }
        }
    }
    return $save;
}

function dataUpdateMX($mx_server, $target_id)
{
    global $db;
    $update = false;
    $mx_server_update_sql = "UPDATE evp_mx_skiplist SET mx_server = '$mx_server' WHERE id = '$target_id' ";
    $mx_server_update_read = $db->update($mx_server_update_sql);
    if ($mx_server_update_read) {
        $update = true;
    }
    return $update;
}

$error = false;
$message = '';
$action_std = false;
$action_cat = '';

if (isset($_POST['email_campaigns']) || isset($_POST['inbox_checker']) || isset($_POST['multi_scan']) || isset($_POST['blacklist_check']) || isset($_POST['ver_check']) || isset($_POST['warmup_status']) || isset($_POST['bgColor']) || isset($_POST['system_email']) || isset($_POST['system_debug']) || isset($_POST['smtp_debug']) || isset($_POST['scan_debug']) || isset($_POST['sys_smtp'])) {
    $action_std = true;
    $action_cat = 'theme_options';

    if (isset($_SESSION['auth_log']) && $_SESSION['auth_log'] == true) {
        $email_campaigns = $_POST['email_campaigns'] ?? '';
        $inbox_checker = $_POST['inbox_checker'] ?? '';
        $multi_scan = $_POST['multi_scan'] ?? '';
        $blacklist_check = $_POST['blacklist_check'] ?? '';
        $ver_check = $_POST['ver_check'] ?? '';
        $warmup_status = $_POST['warmup_status'] ?? '';
        $bgColor = $_POST['bgColor'] ?? '';
        $system_email = sanitize_input($_POST['system_email'] ?? '');
        $sys_smtp = $_POST['sys_smtp'] ?? '';
        $smtp_host = sanitize_input($_POST['smtp_host'] ?? '');
        $smtp_port = sanitize_input($_POST['smtp_port'] ?? '');
        $smtp_security = mysqli_real_escape_string($db->link, $_POST['smtp_security'] ?? '');
        $smtp_auth = mysqli_real_escape_string($db->link, $_POST['smtp_auth'] ?? '');
        $smtp_ssl_verify = mysqli_real_escape_string($db->link, $_POST['smtp_ssl_verify'] ?? '');
        $smtp_user = mysqli_real_escape_string($db->link, $_POST['smtp_user'] ?? '');
        $smtp_pass = mysqli_real_escape_string($db->link, $_POST['smtp_pass'] ?? '');
        $system_debug = $_POST['system_debug'] ?? '';
        $scan_debug = $_POST['scan_debug'] ?? '';
        $smtp_debug = $_POST['smtp_debug'] ?? '';

        if ($email_campaigns === 'true') {
            $email_campaigns = 'true';
        } elseif ($email_campaigns === 'false') {
            $email_campaigns = 'false';
        }

        if ($inbox_checker === 'true') {
            $inbox_checker = 'true';
        } elseif ($inbox_checker === 'false') {
            $inbox_checker = 'false';
        }

        if ($sys_smtp === 'true') {
            $sys_smtp = 'true';
        } elseif ($sys_smtp === 'false') {
            $sys_smtp = 'false';
        }

        if ($smtp_ssl_verify == 'false') {
            $smtp_ssl_verify = 'false';
        } elseif ($smtp_ssl_verify == 'true') {
            $smtp_ssl_verify = 'true';
        }

        if ($smtp_auth == 'false') {
            $smtp_auth = 'false';
        } elseif ($smtp_auth == 'true') {
            $smtp_auth = 'true';
        }

        if ($multi_scan === 'true') {
            $multi_scan = 'true';
        } elseif ($multi_scan === 'false') {
            $del_all_process = "DELETE FROM evp_task WHERE status = 'running'";
            $db->delete($del_all_process);
            $multi_scan = 'false';
        }

        if ($blacklist_check === 'true') {
            $blacklist_check = 'true';
        } elseif ($blacklist_check === 'false') {
            $blacklist_check = 'false';
        }

        if ($ver_check === 'true') {
            $ver_check = 'true';
        } elseif ($ver_check === 'false') {
            $ver_check = 'false';
        }

        if ($warmup_status === 'true') {
            $warmup_status = 'true';
        } elseif ($warmup_status === 'false') {
            $warmup_status = 'false';
        }

        $system_email = filter_var($system_email, FILTER_SANITIZE_EMAIL);
        if (filter_var($system_email, FILTER_VALIDATE_EMAIL) || empty($system_email)) {
        } else {
            $error = true;
            $message = 'Invalid email format!';
            $response = array(
                'system_email' => $system_email,
                'error' => $message
            );
            exit(json_encode($response));
        }

        if ($system_debug === 'true') {
            fopen('../tmp/logs/system_debug.log', 'w');
            $inifile = '../.user.ini';
            $c_file = "error_reporting = E_ALL;\n";
            $c_file .= "display_errors = 1;\n";
            $c_file .= "display_startup_errors = 1;\n";
            $c_file .= "log_errors = 1;\n";
            $c_file .= "error_log = '../tmp/logs/system_debug.log';";
            file_put_contents($inifile, $c_file);
            $system_debug = 'true';
        } elseif ($system_debug === 'false') {
            if (file_exists('../.user.ini')) {
                unlink('../.user.ini');
            }
            if (file_exists('../tmp/logs/system_debug.log')) {
                unlink('../tmp/logs/system_debug.log');
            }
            $system_debug = 'false';
        }

        if ($scan_debug === 'true') {
            fopen('../tmp/logs/scan_debug.log', 'w');
            $scan_debug = 'true';
        } elseif ($scan_debug === 'false') {
            if (file_exists('../tmp/logs/scan_debug.log')) {
                unlink('../tmp/logs/scan_debug.log');
            }
            $scan_debug = 'false';
        }

        if ($smtp_debug === 'true') {
            fopen('../tmp/logs/smtp_debug.log', 'w');
            $smtp_debug = 'true';
        } elseif ($smtp_debug === 'false') {
            if (file_exists('../tmp/logs/smtp_debug.log')) {
                unlink('../tmp/logs/smtp_debug.log');
            }
            $smtp_debug = 'false';
        }

        $evp_options_query = "SELECT * FROM evp_options";
        $evp_options_read = $db->select($evp_options_query);
        if ($evp_options_read) {
            $evp_options_count = mysqli_num_rows($evp_options_read);
            if ($evp_options_count > 0) {
                while ($row = $evp_options_read->fetch_assoc()) {
                    $option_name[$row['option_name']] = $row['option_value'];
                }
                $evp_options_read->free();
                $sys_smtp_data = $option_name['sys_smtp'];
                $sys_smtp_data = unserialize($sys_smtp_data);
                $sys_smtp_data['sys_smtp'] = $sys_smtp;
                $sys_smtp_data[0]['smtp_host'] = $smtp_host;
                $sys_smtp_data[0]['smtp_port'] = $smtp_port;
                $sys_smtp_data[0]['smtp_security'] = $smtp_security;
                $sys_smtp_data[0]['smtp_auth'] = $smtp_auth;
                $sys_smtp_data[0]['smtp_user'] = $smtp_user;
                $sys_smtp_data[0]['smtp_pass'] = $smtp_pass;
                $sys_smtp_data[0]['smtp_ssl_verify'] = $smtp_ssl_verify;

                $sys_smtp_data = serialize($sys_smtp_data);

                $evp_options_update_sql = "UPDATE evp_options
                    SET option_value = CASE option_name
                        WHEN 'email_campaigns' THEN '$email_campaigns'
                        WHEN 'inbox_checker' THEN '$inbox_checker'
                        WHEN 'multi_scan' THEN '$multi_scan'
                        WHEN 'blacklist_check' THEN '$blacklist_check'
                        WHEN 'ver_check' THEN '$ver_check'
                        WHEN 'warmup_status' THEN '$warmup_status'
                        WHEN 'bgColor' THEN '$bgColor'
                        WHEN 'system_email' THEN '$system_email'
                        WHEN 'sys_smtp' THEN '$sys_smtp_data'
                        WHEN 'system_debug' THEN '$system_debug'
                        WHEN 'scan_debug' THEN '$scan_debug'
                        WHEN 'smtp_debug' THEN '$smtp_debug'
                    END
                    WHERE option_name IN ('email_campaigns', 'inbox_checker', 'multi_scan', 'blacklist_check', 'ver_check', 'warmup_status', 'bgColor', 'system_email', 'sys_smtp', 'system_debug', 'scan_debug', 'smtp_debug')";
            } else {
                $evp_options_update_sql = "INSERT INTO `evp_options` (`option_name`, `option_value`) VALUES ('email_campaigns', '$email_campaigns'), ('inbox_checker', '$inbox_checker'), ('multi_scan', '$multi_scan'), ('blacklist_check', '$blacklist_check'), ('ver_check', '$ver_check'), ('warmup_status', '$warmup_status'), ('bgColor', '$bgColor'), ('system_email', '$system_email'), ('sys_smtp', '$sys_smtp_data'), ('system_debug', '$system_debug'), ('scan_debug', '$scan_debug'), ('smtp_debug', '$smtp_debug')";
            }
            $evp_options_update_read = $db->update($evp_options_update_sql);
            if ($evp_options_update_read) {
                $error = false;
                $message = "New changes saved!";
                $response = array(
                    'email_campaigns' => $email_campaigns,
                    'inbox_checker' => $inbox_checker,
                    'multi_scan' => $multi_scan,
                    'blacklist_check' => $blacklist_check,
                    'ver_check' => $ver_check,
                    'warmup_status' => $warmup_status,
                    'bgColor' => $bgColor,
                    'system_email' => $system_email,
                    'sys_smtp' => $sys_smtp,
                    'smtp_host' => $smtp_host,
                    'smtp_port' => $smtp_port,
                    'smtp_security' => $smtp_security,
                    'smtp_auth' => $smtp_auth,
                    'smtp_user' => $smtp_user,
                    'smtp_pass' => $smtp_pass,
                    'smtp_ssl_verify' => $smtp_ssl_verify,
                    'system_debug' => $system_debug,
                    'scan_debug' => $scan_debug,
                    'smtp_debug' => $smtp_debug,
                    'success' => $message
                );
                exit(json_encode($response));
            } else {
                $error = true;
                $message = "Database connection failed";
                $response = array(
                    'error' => $message
                );
                exit(json_encode($response));
            }
        } else {
            $error = false;
            $message = 'Database Connection Error';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    }
} elseif (isset($_POST['system_email'])) {
    $action_std = true;
    $action_cat = 'notify_options';
    $system_email = sanitize_input($_POST['system_email']);
    if (isset($_SESSION['auth_log']) && $_SESSION['auth_log'] == true) {
        $evp_options_query = "SELECT * FROM evp_options";
        $evp_options_read = $db->select($evp_options_query);
        if ($evp_options_read) {
            $evp_options_count = mysqli_num_rows($evp_options_read);
            $system_email = filter_var($system_email, FILTER_SANITIZE_EMAIL);
            if (filter_var($system_email, FILTER_VALIDATE_EMAIL) || empty($system_email)) {
                if ($evp_options_count > 0) {
                    $evp_options_update_sql = "UPDATE evp_options
                        SET option_value = CASE option_name
                            WHEN 'system_email' THEN '$system_email'
                        END
                        WHERE option_name IN ('system_email')";
                } else {
                    $evp_options_update_sql = "INSERT INTO `evp_options` (`option_name`, `option_value`) VALUES ('system_email', '$system_email')";
                }
            } else {
                $error = true;
                $message = 'Invalid email format!';
                $response = array(
                    'system_email' => $system_email,
                    'error' => $message
                );
                exit(json_encode($response));
            }
            $evp_options_update_read = $db->update($evp_options_update_sql);
            if ($evp_options_update_read) {
                $error = false;
                $message = "Update successfully.";
                echo json_encode(array(
                    'system_email' => $system_email,
                    'success' => $message
                ));
                exit();
            } else {
                $error = true;
                $message = "Database connection failed";
            }
        } else {
            $error = false;
            $message = 'Database Connection Error';
        }
    }
} elseif (isset($_POST['fname']) || isset($_POST['lname']) || isset($_POST['username']) || isset($_POST['email']) || isset($_POST['addline1']) || isset($_POST['addline2']) || isset($_POST['city']) || isset($_POST['postalcode']) || isset($_POST['state']) || isset($_POST['country']) || isset($_POST['locale'])) {
    $action_std = true;
    $action_cat = 'profile_options';
    $fname = sanitize_input($_POST['fname'] ?? '');
    $lname = sanitize_input($_POST['lname'] ?? '');
    $user_name = $fname . " " . $lname;
    $username = sanitize_input($_POST['username'] ?? '');
    $email = sanitize_input($_POST['email'] ?? '');
    $addline1 = sanitize_input($_POST['addline1'] ?? '');
    $addline2 = sanitize_input($_POST['addline2'] ?? '');
    $city = sanitize_input($_POST['city'] ?? '');
    $postalcode = sanitize_input($_POST['postalcode'] ?? '');
    $state = sanitize_input($_POST['state'] ?? '');
    $country = sanitize_input($_POST['country'] ?? '');
    $locale = sanitize_input($_POST['locale'] ?? '');
    $token = RandomString(20);

    if (strlen($state) != 2) {
        $error = true;
        $message = "Select your country/region";
        $response = array(
            'fname' => $fname,
            'lname' => $lname,
            'username' => $username,
            'email' => $email,
            'addline1' => $addline1,
            'addline2' => $addline2,
            'city' => $city,
            'postalcode' => $postalcode,
            'state' => $state,
            'country' => $country,
            'locale' => $locale,
            'error' => $message
        );
        exit(json_encode($response));
    }

    if ((!empty($fname) || !empty($lname) || !empty($username) || !empty($user_id)) && !empty($email)) {
        $same_email_check_sql = "SELECT option_name, option_value FROM evp_options";
        $same_email_check_read = $db->select($same_email_check_sql);
        if ($same_email_check_read) {
            $same_email_check_count = mysqli_num_rows($same_email_check_read);
            if ($same_email_check_count > 0) {
                while ($row = $same_email_check_read->fetch_assoc()) {
                    $option_name[$row['option_name']] = $row['option_value'];
                }
                $same_email_check_read->free();
                $get_email = $option_name['email'];
                $get_uid = $option_name['user_id'];
            }

            if ($get_email != $email) {
                if ($get_email != $email) {
                    $isert_email_request_sql = "UPDATE evp_options
                        SET option_value = CASE option_name
                            WHEN 'fname' THEN '$fname'
                            WHEN 'lname' THEN '$lname'
                            WHEN 'username' THEN '$username'
                            WHEN 'verify_email_token' THEN '$token'
                            WHEN 'email_change_to' THEN '$email'
                        END
                        WHERE option_name IN ('fname', 'lname', 'username', 'verify_email_token', 'email_change_to')";
                    $isert_email_request_read = $db->update($isert_email_request_sql);
                    if ($isert_email_request_read) {
                        $sendmail = new SendMail;
                        $sendmail->notify_user_account_updates($user_name, $email, $token, 'email_update');
                        $error = false;
                        $message = "A confirmation email sent! please check your new email address.";
                        $response = array(
                            'fname' => $fname,
                            'lname' => $lname,
                            'username' => $username,
                            'email' => $email,
                            'success' => $message
                        );
                        exit(json_encode($response));
                    } else {
                        $error = true;
                        $message = "Database connection error!";
                    }
                } else {
                    $user_update_sql = "UPDATE evp_options
                        SET option_value = CASE option_name
                            WHEN 'fname' THEN '$fname'
                            WHEN 'lname' THEN '$lname'
                            WHEN 'username' THEN '$username'
                            WHEN 'verify_email_token' THEN '$token'
                            WHEN 'email_change_to' THEN '$email'
                        END
                        WHERE option_name IN ('fname', 'lname', 'username', 'verify_email_token', 'email_change_to')";
                    $user_insert_read = $db->update($user_update_sql);
                    if ($user_insert_read) {
                        $sendmail = new SendMail;
                        $sendmail->notify_user_account_updates($user_name, $email, $token, 'email_update');
                        $error = false;
                        $message = "A confirmation email send on your requested email! please check your email";
                        $response = array(
                            'fname' => $fname,
                            'lname' => $lname,
                            'username' => $username,
                            'email' => $email,
                            'success' => $message
                        );
                        exit(json_encode($response));
                    } else {
                        $error = true;
                        $message = "Database connection error!";
                    }
                }
            } else {
                $req_delete_sql = "UPDATE evp_options
                    SET option_value = CASE option_name
                        WHEN 'fname' THEN '$fname'
                        WHEN 'lname' THEN '$lname'
                        WHEN 'username' THEN '$username'
                        WHEN 'addline1' THEN '$addline1'
                        WHEN 'addline2' THEN '$addline2'
                        WHEN 'city' THEN '$city'
                        WHEN 'postalcode' THEN '$postalcode'
                        WHEN 'state' THEN '$state'
                        WHEN 'country' THEN '$country'
                        WHEN 'locale' THEN '$locale'
                        WHEN 'verify_email_token' THEN NULL
                        WHEN 'email_change_to' THEN NULL
                    END
                    WHERE option_name IN ('fname', 'lname', 'username', 'addline1', 'addline2', 'city', 'postalcode', 'state', 'country', 'locale', 'verify_email_token', 'email_change_to')";
                $req_delete_read = $db->update($req_delete_sql);
                $translator->saveLanguage();
                if ($req_delete_read) {
                    $error = false;
                    $message = "Profile data update successful";
                    $response = array(
                        'fname' => $fname,
                        'lname' => $lname,
                        'username' => $username,
                        'email' => $email,
                        'addline1' => $addline1,
                        'addline2' => $addline2,
                        'city' => $city,
                        'postalcode' => $postalcode,
                        'state' => $state,
                        'country' => $country,
                        'locale' => $locale,
                        'success' => $message
                    );
                    exit(json_encode($response));
                } else {
                    $error = true;
                    $message = "Database connection error!";
                }
            }
        } else {
            $error = true;
            $message = "Database Connection error!";
        }
    } else {
        $error = true;
        $message = 'Profile new data not found!';
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    }
} elseif (isset($_POST['apitoken'])) {
    $genToken = bin2hex(random_bytes(12));
    $sql = "UPDATE evp_options
        SET option_value = CASE option_name
            WHEN 'api_token' THEN '$genToken'
        END
        WHERE option_name IN ('api_token')";
    $sql_read = $db->update($sql);
    if ($sql_read) {
        $message = "API Token Updated";
        $response = array(
            'apitoken' => $genToken,
            'message' => $message,
            'status' => 'success'
        );
    } else {
        $message = "Update failed";
        $response = array(
            'message' => $message,
            'status' => 'error'
        );
    }
    exit(json_encode($response));
} elseif (isset($_POST['currpass']) || isset($_POST['newpass']) || isset($_POST['conpass'])) {
    $action_std = true;
    $action_cat = 'pass';
    $currpass = sanitize_input($_POST['currpass'] ?? '');
    $currpass = md5($currpass);
    $newpass = sanitize_input($_POST['newpass'] ?? '');
    $conpass = sanitize_input($_POST['conpass'] ?? '');
    if (strlen($newpass) < 6) {
        $error = true;
        $message = 'Password should be minimum 6 characters';
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    } elseif ($newpass == $conpass) {
        $pass_check_sql = "SELECT * FROM evp_options";
        $pass_check_read = $db->select($pass_check_sql);
        if ($pass_check_read) {
            $count_user = mysqli_num_rows($pass_check_read);
            if ($count_user > 0) {
                while ($row = $pass_check_read->fetch_assoc()) {
                    $option_name[$row['option_name']] = $row['option_value'];
                }
                $pass_check_read->free();
                $oldPass = $option_name['password'];
                if ($oldPass == $currpass) {
                    $newpass = md5($newpass);
                    $user_update_sql = "UPDATE evp_options
                        SET option_value = CASE option_name
                            WHEN 'password' THEN '$newpass'
                        END
                        WHERE option_name IN ('password')";
                    $user_insert_read = $db->update($user_update_sql);
                    if ($user_insert_read) {
                        $error = false;
                        $message = "Password change successfully.";
                        $response = array(
                            'password' => $newpass,
                            'success' => $message
                        );
                        exit(json_encode($response));
                    } else {
                        $error = true;
                        $message = "Database connection error!";
                        $response = array(
                            'error' => $message
                        );
                        exit(json_encode($response));
                    }
                } else {
                    $error = true;
                    $message = "Wrong Password";
                    $response = array(
                        'error' => $message
                    );
                    exit(json_encode($response));
                }
            } else {
                $error = true;
                $message = "Password Field Not Found";
                $response = array(
                    'error' => $message
                );
                exit(json_encode($response));
            }
        } else {
            $error = true;
            $message = "Database connection error!";
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } else {
        $error = true;
        $message = "confirm password not match";
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    }
} elseif (isset($_POST['camp_smtp_test']) || isset($_POST['sys_smtp_test']) || isset($_POST['ic_smtp_test'])) {
    require_once("$s_path/lib/phpmailer/Exception.php");
    require_once("$s_path/lib/phpmailer/PHPMailer.php");
    require_once("$s_path/lib/phpmailer/SMTP.php");
    $mail = new PHPMailer();
    $mail->CharSet = "UTF-8";
    if (isset($_POST['camp_smtp_test']) && !empty($_POST['camp_smtp_test']) && isset($_POST['target_id']) && !empty($_POST['target_id'])) {
        $target_id = $_POST['target_id'];
        $smtps_data_q = "SELECT * FROM evp_smtp_server_list WHERE id = '$target_id' AND user_id = '$user_id'";
        $smtps_data_r = $db->select($smtps_data_q);
        if ($smtps_data_r) {
            $smtps_data_check = mysqli_num_rows($smtps_data_r);
            if ($smtps_data_check > 0) {
                $smtps_data_row = $smtps_data_r->fetch_assoc();
            }
            $smtps_data_r->free();
            $smtp_from_email = $smtps_data_row['smtp_email'];
            $smtp_host = $smtps_data_row['smtp_host'];
            $smtp_port = $smtps_data_row['smtp_port'];
            $smtp_security = $smtps_data_row['smtp_security'];
            $smtp_auth = $smtps_data_row['smtp_auth'];
            $smtp_user = $smtps_data_row['smtp_user'];
            $smtp_to_email = $_POST['camp_smtp_test'];
            $smtp_pass = $smtps_data_row['smtp_pass'];
            $smtp_ssl_verify = $smtps_data_row['smtp_ssl_verify'];
            $mail->isSMTP();
        } else {
            $result = array(
                'title' => 'Error',
                'text' => 'SMTP Data Not Found',
                'type' => 'error'
            );
            return print_r(json_encode($result));
        }
    } elseif (isset($_POST['sys_smtp_test']) && !empty($_POST['sys_smtp_test'])) {
        $evp_options_sql = "SELECT option_name, option_value FROM evp_options";
        $evp_options_read = $db->select($evp_options_sql);
        if ($evp_options_read) {
            $evp_options_check = mysqli_num_rows($evp_options_read);
            if ($evp_options_check > 0) {
                while ($row = $evp_options_read->fetch_assoc()) {
                    $option_name[$row['option_name']] = $row['option_value'];
                }
                $evp_options_read->free();
                $sys_smtp_data = $option_name['sys_smtp'];
                $system_email = $option_name['system_email'];
                $sys_smtp_data = unserialize($sys_smtp_data);
                $sys_smtp = $sys_smtp_data['sys_smtp'];
                foreach ($sys_smtp_data as $smtp_data) {
                }
                ;
                $smtp_host = $smtp_data['smtp_host'];
                $smtp_port = $smtp_data['smtp_port'];
                $smtp_security = $smtp_data['smtp_security'];
                $smtp_auth = $smtp_data['smtp_auth'];
                $smtp_user = $smtp_data['smtp_user'];
                $smtp_pass = $smtp_data['smtp_pass'];
                $smtp_ssl_verify = $smtp_data['smtp_ssl_verify'];
                $smtp_to_email = $_POST['sys_smtp_test'];
                $smtp_from_email = $system_email;
                if ($sys_smtp == 'false') {
                    $mail->IsMail();
                } else {
                    $mail->isSMTP();
                }
            }
        }
    } elseif (isset($_POST['ic_smtp_test']) && !empty($_POST['ic_smtp_test'])) {
        $evp_options_sql = "SELECT option_name, option_value FROM evp_options";
        $evp_options_read = $db->select($evp_options_sql);
        if ($evp_options_read) {
            $evp_options_check = mysqli_num_rows($evp_options_read);
            if ($evp_options_check > 0) {
                while ($row = $evp_options_read->fetch_assoc()) {
                    $option_name[$row['option_name']] = $row['option_value'];
                }
                $evp_options_read->free();
                $ic_smtp_data = $option_name['ic_smtp'];
                $ic_send_mail = $option_name['ic_send_mail'];
                $ic_smtp_data = unserialize($ic_smtp_data);
                $ic_smtp = $ic_smtp_data['ic_smtp'];
                foreach ($ic_smtp_data as $smtp_data) {
                }
                ;
                $smtp_host = $smtp_data['smtp_host'];
                $smtp_port = $smtp_data['smtp_port'];
                $smtp_security = $smtp_data['smtp_security'];
                $smtp_auth = $smtp_data['smtp_auth'];
                $smtp_user = $smtp_data['smtp_user'];
                $smtp_pass = $smtp_data['smtp_pass'];
                $smtp_ssl_verify = $smtp_data['smtp_ssl_verify'];
                $smtp_to_email = $_POST['ic_smtp_test'];
                $smtp_from_email = $ic_send_mail;
                if ($ic_smtp == 'false') {
                    $mail->IsMail();
                } else {
                    $mail->isSMTP();
                }
            }
        }
    }
    if ($smtp_ssl_verify == 'false') {
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
    }
    if ($smtp_debug == 'true') {
        $mail->SMTPDebug = 3;
        $mail->Debugoutput = function ($str, $level) {
            file_put_contents('../tmp/logs/smtp_debug.log', gmdate('Y-m-d H:i:s') . "\t$level\t$str\n", FILE_APPEND | LOCK_EX);
        };
    }
    $emailFrom = $smtp_from_email;
    $emailFromName = 'SMTP TESTER';
    $emailToName = '';
    $emailTo = $smtp_to_email;
    $email_sub = 'SMTP Connection Test Succeed';
    $email_body = 'SMTP CONNECTION WORKING PROPERLY!';
    $mail->Host = $smtp_host;
    $mail->Port = $smtp_port;
    $mail->SMTPSecure = $smtp_security;
    $mail->SMTPAuth = $smtp_auth;
    $mail->Username = $smtp_user;
    $mail->Password = $smtp_pass;
    $mail->setFrom($emailFrom, $emailFromName);
    $mail->addAddress($emailTo, $emailToName);
    $mail->Subject = $email_sub;
    $mail->msgHTML($email_body);
    if (!$mail->send()) {
        $result = array(
            'title' => 'Error',
            'text' => 'Mailer Error:' . $mail->ErrorInfo,
            'type' => 'error'
        );
        return print_r(json_encode($result));
    } else {
        $result = array(
            'title' => 'Success',
            'text' => 'Message sent.',
            'type' => 'success'
        );
        return print_r(json_encode($result));
    }
} elseif (isset($_POST['scan_from']) || isset($_POST['timeout']) || isset($_POST['scan_timeout_lock']) || isset($_POST['scan_port']) || isset($_POST['batch_limit']) || isset($_POST['total_workers']) || isset($_POST['smtp_cmd']) || isset($_POST['list_import_limit']) || isset($_POST['filter_skipMX']) || isset($_POST['filter_skipEmail']) || isset($_POST['file_size_limit']) || isset($_POST['cc_data']) || isset($_POST['ic_smtp_errors']) || isset($_POST['ic_send_mail']) || isset($_POST['ic_smtp']) || isset($_POST['ic_smtp_host']) || isset($_POST['ic_smtp_port']) || isset($_POST['ic_imap_host']) || isset($_POST['ic_imap_port']) || isset($_POST['ic_smtp_security']) || isset($_POST['ic_smtp_auth']) || isset($_POST['ic_smtp_user']) || isset($_POST['ic_smtp_pass']) || isset($_POST['ic_smtp_ssl_verify'])) {
    $action_std = true;
    $action_cat = 'email_scanner_options';
    $scan_from = sanitize_input($_POST['scan_from']);
    $timeout = sanitize_input($_POST['timeout']);
    $scan_timeout_lock = sanitize_input($_POST['scan_timeout_lock']);
    $batch_limit = sanitize_input($_POST['batch_limit']);
    $total_workers = sanitize_input($_POST['total_workers']);
    $scan_port = sanitize_input($_POST['scan_port']);
    $smtp_cmd = sanitize_input($_POST['smtp_cmd']);
    $list_import_limit = sanitize_input($_POST['list_import_limit']);
    $file_size_limit = sanitize_input($_POST['file_size_limit']);
    $filter_skipMX = sanitize_input($_POST['filter_skipMX']);
    $filter_skipEmail = sanitize_input($_POST['filter_skipEmail']);
    $cc_data_add = isset($_POST['cc_data']) ? $_POST['cc_data'] : [];
    if (!is_array($cc_data_add)) {
        $cc_data_add = [];
    }
    $cc_data_get = isset($cc_data) ? $cc_data : [];
    if (!is_array($cc_data_get)) {
        $maybe_unserialized = @unserialize($cc_data_get);
        $cc_data_get = is_array($maybe_unserialized) ? $maybe_unserialized : [];
    }
    function cname($str)
    {
        return strtolower(str_replace(" ", "_", $str));
    }
    $cc_data_add = array_map('cname', $cc_data_add);
    $cc_data_get = array_map('cname', $cc_data_get);
    if (empty($cc_data_add) && !empty($cc_data_get)) {
        $results_del = $cc_data_get;
    } else {
        $results_del = array_diff($cc_data_get, $cc_data_add);
    }
    $results_add = array_diff($cc_data_add, $cc_data_get);
    if (!empty($results_add)) {
        foreach ($results_add as $val) {
            $sql = "SELECT COUNT(*) as C
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE table_schema = '" . DB_NAME . "'
                AND table_name = 'evp_email_list' 
                AND column_name = '$val'";
            if ($result = $db->update($sql)) {
                $row = $result->fetch_assoc();
                if ($row["C"] == 0) {
                    $sql = "ALTER TABLE evp_email_list 
                        ADD COLUMN $val varchar(255) DEFAULT NULL AFTER `csv_file_name`";
                }
            }
            $db->update($sql);
        }
    }
    if (!empty($results_del)) {
        foreach ($results_del as $val) {
            $sql = "SELECT COUNT(*) as C
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE table_schema = '" . DB_NAME . "' 
                AND table_name = 'evp_email_list' 
                AND column_name = '$val'";
            $log->system_debug($sql);
            if ($result = $db->select($sql)) {
                $row = $result->fetch_assoc();
                if ($row["C"] == 1) {
                    $sql = "ALTER TABLE evp_email_list 
                        DROP COLUMN `$val`";
                    $log->system_debug($sql);
                    if ($db->update($sql) === false) {
                        $log->system_debug("Failed to execute ALTER TABLE statement: " . $db->error);
                    }
                }
            } else {
                $log->system_debug("Failed to execute SELECT statement: " . $db->error);
            }
        }
    }
    $cc_data = serialize($cc_data_add);
    if ($cc_data_add == NULL) {
        $cc_data = 'a:0:{}';
    }
    $ic_smtp_errors = sanitize_input(isset($_POST['ic_smtp_errors']) ? $_POST['ic_smtp_errors'] : '');
    $ic_send_mail = sanitize_input(isset($_POST['ic_send_mail']) ? $_POST['ic_send_mail'] : '');
    $ic_smtp = sanitize_input(isset($_POST['ic_smtp']) ? $_POST['ic_smtp'] : '');
    $ic_imap_host = sanitize_input(isset($_POST['ic_imap_host']) ? $_POST['ic_imap_host'] : '');
    $ic_imap_port = sanitize_input(isset($_POST['ic_imap_port']) ? $_POST['ic_imap_port'] : '');
    $ic_smtp_host = sanitize_input(isset($_POST['ic_smtp_host']) ? $_POST['ic_smtp_host'] : '');
    $ic_smtp_port = sanitize_input(isset($_POST['ic_smtp_port']) ? $_POST['ic_smtp_port'] : '');
    $ic_smtp_security = isset($_POST['ic_smtp_security']) ? mysqli_real_escape_string($db->link, $_POST['ic_smtp_security']) : '';
    $ic_smtp_auth = isset($_POST['ic_smtp_auth']) ? mysqli_real_escape_string($db->link, $_POST['ic_smtp_auth']) : '';
    $ic_smtp_ssl_verify = isset($_POST['ic_smtp_ssl_verify']) ? mysqli_real_escape_string($db->link, $_POST['ic_smtp_ssl_verify']) : '';
    $ic_smtp_user = isset($_POST['ic_smtp_user']) ? mysqli_real_escape_string($db->link, $_POST['ic_smtp_user']) : '';
    $ic_smtp_pass = isset($_POST['ic_smtp_pass']) ? mysqli_real_escape_string($db->link, $_POST['ic_smtp_pass']) : '';
    if ($ic_smtp === 'true') {
        $ic_smtp = 'true';
    } elseif ($ic_smtp === 'false') {
        $ic_smtp = 'false';
    }
    if ($ic_smtp_ssl_verify == 'false') {
        $ic_smtp_ssl_verify = 'false';
    } elseif ($ic_smtp_ssl_verify == 'true') {
        $ic_smtp_ssl_verify = 'true';
    }
    if ($ic_smtp_auth == 'false') {
        $ic_smtp_auth = 'false';
    } elseif ($ic_smtp_auth == 'true') {
        $ic_smtp_auth = 'true';
    }
    $ic_send_mail = filter_var($ic_send_mail, FILTER_SANITIZE_EMAIL);
    if (filter_var($ic_send_mail, FILTER_VALIDATE_EMAIL) || empty($ic_send_mail)) {
    } else {
        $error = true;
        $message = 'Invalid email format!';
        $response = array(
            'ic_send_mail' => $ic_send_mail,
            'error' => $message
        );
        exit(json_encode($response));
    }
    $ic_smtp_data = $option_name['ic_smtp'];
    $ic_smtp_data = unserialize($ic_smtp_data);
    $ic_smtp_data['ic_smtp'] = $ic_smtp;
    $ic_smtp_data[0]['imap_host'] = $ic_imap_host;
    $ic_smtp_data[0]['imap_port'] = $ic_imap_port;
    $ic_smtp_data[0]['smtp_host'] = $ic_smtp_host;
    $ic_smtp_data[0]['smtp_port'] = $ic_smtp_port;
    $ic_smtp_data[0]['smtp_security'] = $ic_smtp_security;
    $ic_smtp_data[0]['smtp_auth'] = $ic_smtp_auth;
    $ic_smtp_data[0]['smtp_user'] = $ic_smtp_user;
    $ic_smtp_data[0]['smtp_pass'] = $ic_smtp_pass;
    $ic_smtp_data[0]['smtp_ssl_verify'] = $ic_smtp_ssl_verify;
    $ic_smtp_data = serialize($ic_smtp_data);
    if (!empty($timeout) && !empty($scan_port) && !empty($batch_limit) && !empty($total_workers) && !empty($smtp_cmd)) {
        $evp_options_query = "SELECT * FROM evp_options";
        $evp_options_read = $db->select($evp_options_query);
        if ($evp_options_read) {
            $evp_options_count = mysqli_num_rows($evp_options_read);
            if ($evp_options_count > 0) {
                $evp_options_update_sql = "UPDATE evp_options
                    SET option_value = CASE option_name
                        WHEN 'scan_time_out' THEN '$timeout'
                        WHEN 'scan_timeout_lock' THEN '$scan_timeout_lock'
                        WHEN 'scan_port' THEN '$scan_port'
                        WHEN 'scan_mail' THEN '$scan_from'
                        WHEN 'batch_limit' THEN '$batch_limit'
                        WHEN 'total_workers' THEN '$total_workers'
                        WHEN 'smtp_cmd' THEN '$smtp_cmd'
                        WHEN 'list_import_limit' THEN '$list_import_limit'
                        WHEN 'filter_skip_mx' THEN '$filter_skipMX'
                        WHEN 'filter_skip_email' THEN '$filter_skipEmail'
                        WHEN 'file_size_limit' THEN '$file_size_limit'
                        WHEN 'cc_data' THEN '$cc_data'
                        WHEN 'smtp_errors' THEN '$ic_smtp_errors'
                        WHEN 'ic_send_mail' THEN '$ic_send_mail'
                        WHEN 'ic_smtp' THEN '$ic_smtp_data'
                    END
                    WHERE option_name in ('scan_time_out','scan_timeout_lock','scan_port','scan_mail','batch_limit','total_workers','smtp_cmd','list_import_limit','filter_skip_mx','filter_skip_email','file_size_limit','cc_data','smtp_errors','ic_send_mail','ic_smtp')";
            } else {
                $evp_options_update_sql = "INSERT INTO `evp_options` (`option_name`, `option_value`) VALUES ('scan_time_out', '$timeout'),('scan_timeout_lock', '$scan_timeout_lock'),('scan_port', '$scan_port'),('scan_mail', '$scan_from'),('batch_limit','$batch_limit'),('total_workers','$total_workers'),('smtp_cmd','$smtp_cmd'),('list_import_limit', '$list_import_limit'),('filter_skip_mx', '$filter_skipMX'),('filter_skip_email', '$filter_skipEmail'),('file_size_limit', '$file_size_limit'),('smtp_errors', '$ic_smtp_errors'),('cc_data', '$cc_data'),('ic_send_mail', '$ic_send_mail'),('ic_smtp', '$ic_smtp_data')";
            }
            $evp_options_update_read = $db->update($evp_options_update_sql);
            if ($evp_options_update_read) {
                $error = false;
                $message = "New changes saved!";
                echo json_encode(array(
                    'timeout' => $timeout,
                    'scan_timeout_lock' => $scan_timeout_lock,
                    'scan_port' => $scan_port,
                    'scan_from' => $scan_from,
                    'batch_limit' => $batch_limit,
                    'total_workers' => $total_workers,
                    'smtp_cmd' => $smtp_cmd,
                    'list_import_limit' => $list_import_limit,
                    'filter_skipMX' => $filter_skipMX,
                    'filter_skipEmail' => $filter_skipEmail,
                    'file_size_limit' => $file_size_limit,
                    'cc_data' => $cc_data,
                    'ic_smtp_errors' => $ic_smtp_errors,
                    'ic_send_mail' => $ic_send_mail,
                    'ic_smtp' => $ic_smtp,
                    'ic_imap_host' => $ic_imap_host,
                    'ic_imap_port' => $ic_imap_port,
                    'ic_smtp_host' => $ic_smtp_host,
                    'ic_smtp_port' => $ic_smtp_port,
                    'ic_smtp_security' => $ic_smtp_security,
                    'ic_smtp_auth' => $ic_smtp_auth,
                    'ic_smtp_user' => $ic_smtp_user,
                    'ic_smtp_pass' => $ic_smtp_pass,
                    'ic_smtp_ssl_verify' => $ic_smtp_ssl_verify,
                    'success' => $message
                ));
                exit();
            } else {
                $error = true;
                $message = "Database connection failed";
            }
        } else {
            $error = false;
            $message = 'Database Connection Error';
        }
    } else {
        $error = true;
        $message = 'Cannot be empty!';
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    }
} elseif (isset($_POST['gen_apiKeys'])) {
    $action = sanitize_input($_POST['gen_apiKeys']);
    $response = array();
    $evp_options_sql = "SELECT option_name, option_value FROM evp_options WHERE option_name = 'apiKeys'";
    $evp_options_read = $db->select($evp_options_sql);
    if ($evp_options_read) {
        $row = $evp_options_read->fetch_assoc();
        $apiKeys = unserialize($row['option_value']);
    } else {
        $apiKeys = array(
            'apiKey_scanner' => '',
            'apiKey_opt' => '',
            'apiKey_campaign' => ''
        );
    }
    switch ($action) {
        case 'apiKey_scanner':
            $apiKeys['apiKey_scanner'] = md5($s_url . $access_tier . $s_path . rand(10, 999));
            break;
        case 'apiKey_opt':
            $apiKeys['apiKey_opt'] = md5($s_url . $access_tier . $s_path . rand(10, 999));
            break;
        case 'apiKey_campaign':
            $apiKeys['apiKey_campaign'] = md5($s_url . $access_tier . $s_path . rand(10, 999));
            break;
        default:
            $response = array(
                'error' => 'Invalid action!'
            );
            echo json_encode($response);
            exit;
    }
    $apiKeys_serialized = serialize($apiKeys);
    $update_sql = "UPDATE evp_options SET option_value = '$apiKeys_serialized' WHERE option_name = 'apiKeys'";
    $update_read = $db->update($update_sql);
    if ($update_read) {
        $response = array(
            'success' => 'API Key generated successfully!',
            'apiKeys' => $apiKeys
        );
    } else {
        $response = array(
            'error' => 'Failed to generate API Key!'
        );
    }
    echo json_encode($response);
    exit;
} elseif (isset($_POST['site_options'])) {
    $action_std = true;
    $action_cat = 'taskrun_options';
    $tasker_hash = md5($s_url . $access_tier . $s_path . rand(10, 999));
    if (isset($_SESSION['auth_log']) && $_SESSION['auth_log'] == true) {
        $evp_options_query = "SELECT * FROM evp_options";
        $evp_options_read = $db->select($evp_options_query);
        if ($evp_options_read) {
            $evp_options_count = mysqli_num_rows($evp_options_read);
            if (!empty($tasker_hash)) {
                if ($evp_options_count > 0) {
                    $evp_options_update_sql = "UPDATE evp_options
                        SET option_value = CASE option_name
                            WHEN 'tasker_hash' THEN '$tasker_hash'
                        END
                        WHERE option_name IN ('tasker_hash')";
                } else {
                    $evp_options_update_sql = "INSERT INTO `evp_options` (`option_name`, `option_value`) VALUES ('tasker_hash', '$tasker_hash')";
                }
            } else {
                $error = true;
                $message = 'Invalid hash format!';
                $response = array(
                    'tasker_hash' => $tasker_hash,
                    'error' => $message
                );
                exit(json_encode($response));
            }
            $evp_options_update_read = $db->update($evp_options_update_sql);
            if ($evp_options_update_read) {
                $error = false;
                $message = "Update successfully.";
                echo json_encode(array(
                    'tasker_hash' => $tasker_hash,
                    'success' => $message
                ));
                exit();
            } else {
                $error = true;
                $message = "Database connection failed";
            }
        } else {
            $error = false;
            $message = 'Database Connection Error';
        }
    }
} elseif (isset($_POST['domain_filter_save_btn'])) {
    $action_std = true;
    $action_cat = 'domain_filter_options';
    $listing_value = $_POST['listing_value'];
    $user_id = sanitize_input($_POST['user_id']);
    $std = false;
    $correct = 0;
    $wrong = 0;
    foreach ($listing_value as $value) {
        $value = sanitize_input($value);
        $domain = 'name_' . $value;
        $type = 'type_' . $value;
        $domain = sanitize_input($_POST[$domain]);
        $type = sanitize_input($_POST[$type]);
        if (!empty($domain) && !empty($type) && !empty($user_id)) {
            $std = true;
            $result = dataAddDomain($domain, $type, $user_id);
            if ($result) {
                $correct++;
            } else {
                $wrong++;
            }
        } else {
            $wrong++;
        }
    }
    if ($std) {
        $error = ($correct > 0) ? false : true;
        $message = (($correct > 0) ? $correct . ' data save successfully, ' : '') . (($wrong > 0) ? $wrong . ' data not save!' : '');
    } else {
        $error = true;
        $message = 'No Data Found';
    }
} elseif (isset($_POST['domain_filter_edit_btn'])) {
    $action_std = true;
    $action_cat = 'domain_filter_options';
    $user_id = sanitize_input($_POST['user_id']);
    $target_id = sanitize_input($_POST['target_id']);
    $name = sanitize_input($_POST['name']);
    $type = sanitize_input($_POST['type']);
    if (!empty($name) && !empty($type) && !empty($target_id) && !empty($user_id)) {
        $result = dataUpdateDomain($name, $type, $target_id, $user_id);
        if ($result) {
            $error = false;
            $message = 'Update successfull';
        } else {
            $error = true;
            $message = 'Update is not successfull';
        }
    } else {
        $error = true;
        $message = 'Data Not Found';
    }
} elseif (isset($_POST['domain_filter_del_btn'])) {
    $action_std = true;
    $action_cat = 'domain_filter_options';
    $user_id = sanitize_input($_POST['user_id']);
    $target_id = sanitize_input($_POST['target_id']);
    if (!empty($user_id) && !empty($target_id)) {
        $delete_data_sql = "DELETE FROM evp_domain_filter_list WHERE user_id = '$user_id' AND id = '$target_id' ";
        $delete_data_read = $db->delete($delete_data_sql);
        if ($delete_data_read) {
            $error = false;
            $message = 'Delete successfull';
        } else {
            $error = true;
            $message = 'Database connection failed';
        }
    } else {
        $error = true;
        $message = 'Data Not Found';
    }
} elseif (isset($_POST['smtp_server']) && !empty($_POST['smtp_server'])) {
    $smtp_server = sanitize_input($_POST['smtp_server']);
    $target_id = sanitize_input($_POST['target_id']);
    $smtp_data = $_POST['smtp_data'];
    if ($smtp_server == 'delete' && !empty($target_id)) {
        $delete_data_sql = "DELETE FROM evp_smtp_server_list WHERE id = '$target_id' AND user_id = '$user_id'";
        $delete_data_read = $db->delete($delete_data_sql);
        if ($delete_data_read) {
            $error = false;
            $message = 'Successfully deleted';
            $response = array(
                'success' => $message
            );
            exit(json_encode($response));
        } else {
            $error = true;
            $message = 'Database connection failed';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } elseif ($smtp_server == 'update' && !empty($smtp_data)) {
        $smtp_limit = sanitize_input($smtp_data[0]);
        $smtp_email = sanitize_input($smtp_data[1]);
        $smtp_host = sanitize_input($smtp_data[2]);
        $smtp_port = sanitize_input($smtp_data[3]);
        $smtp_security = sanitize_input($smtp_data[4]);
        $smtp_ssl_verify = sanitize_input($smtp_data[5]);
        $smtp_auth = sanitize_input($smtp_data[6]);
        $smtp_user = sanitize_input($smtp_data[7]);
        $smtp_pass = sanitize_input($smtp_data[8]);
        $smtp_data_query = "SELECT * FROM evp_smtp_server_list";
        $smtp_data_read = $db->select($smtp_data_query);
        if ($smtp_data_read) {
            $smtp_data_count = mysqli_num_rows($smtp_data_read);
            if (($smtp_data_count > 0) && !empty($target_id)) {
                $smtp_data_update_sql = "UPDATE `evp_smtp_server_list` SET 
                    `smtp_limit` = '$smtp_limit',
                    `smtp_email` = '$smtp_email',
                    `smtp_host` = '$smtp_host',
                    `smtp_port` = '$smtp_port',
                    `smtp_security` = '$smtp_security',
                    `smtp_ssl_verify` = '$smtp_ssl_verify',
                    `smtp_auth` = '$smtp_auth',
                    `smtp_user` = '$smtp_user',
                    `smtp_pass` = '$smtp_pass'
                    WHERE id = '$target_id' AND user_id = '$user_id'";
            } else {
                $smtp_data_update_sql = "INSERT INTO `evp_smtp_server_list` (`user_id`, `smtp_limit`, `smtp_email`, `smtp_host`, `smtp_port`, `smtp_security`, `smtp_ssl_verify`, `smtp_auth`, `smtp_user`, `smtp_pass`) VALUES ('$user_id', '$smtp_limit', '$smtp_email', '$smtp_host', '$smtp_port', '$smtp_security', '$smtp_ssl_verify', '$smtp_auth', '$smtp_user', '$smtp_pass')";
            }
            $smtp_data_update_read = $db->update($smtp_data_update_sql);
            if ($smtp_data_update_read) {
                if (empty($target_id)) {
                    $target_id = mysqli_insert_id($db->link);
                }
                $error = false;
                $message = "New changes saved!";
                $response = array(
                    'smtp_limit' => $smtp_limit,
                    'smtp_email' => $smtp_email,
                    'smtp_host' => $smtp_host,
                    'smtp_port' => $smtp_port,
                    'smtp_security' => $smtp_security,
                    'smtp_ssl_verify' => $smtp_ssl_verify,
                    'smtp_auth' => $smtp_auth,
                    'smtp_user' => $smtp_user,
                    'smtp_pass' => $smtp_pass,
                    'target_id' => $target_id,
                    'success' => $message
                );
                exit(json_encode($response));
            } else {
                $error = true;
                $message = "Database connection failed";
                $response = array(
                    'error' => $message
                );
                exit(json_encode($response));
            }
        } else {
            $error = false;
            $message = 'Database Connection Error';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } else {
        $error = true;
        $message = 'Data Not Found';
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    }
} elseif (isset($_POST['mx_filter']) && !empty($_POST['mx_filter'])) {
    $mx_filter = sanitize_input($_POST['mx_filter']);
    $user_id = isset($_POST['user_id']) ? sanitize_input($_POST['user_id']) : $user_id;
    $target_id = isset($_POST['target_id']) ? sanitize_input($_POST['target_id']) : '';
    $mx_data = isset($_POST['mx_data']) ? $_POST['mx_data'] : [];
    if ($mx_filter == 'delete' && !empty($target_id)) {
        $delete_data_sql = "DELETE FROM evp_mx_skiplist WHERE id = '$target_id' ";
        $delete_data_read = $db->delete($delete_data_sql);
        if ($delete_data_read) {
            $error = false;
            $message = 'Successfully deleted';
            $response = array(
                'success' => $message
            );
            exit(json_encode($response));
        } else {
            $error = true;
            $message = 'Database connection failed';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } elseif ($mx_filter == 'delete_all') {
        $delete_all_sql = "DELETE FROM evp_mx_skiplist";
        $delete_all_read = $db->delete($delete_all_sql);
        if ($delete_all_read) {
            $error = false;
            $message = 'All MX filters deleted successfully';
            $response = array(
                'success' => $message
            );
            exit(json_encode($response));
        } else {
            $error = true;
            $message = 'Database connection failed';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } elseif ($mx_filter == 'update' && !empty($mx_data)) {
        $mx_server = sanitize_input($mx_data[0]);
        $reason = sanitize_input($mx_data[1]);
        $mx_filter_query = "SELECT * FROM evp_mx_skiplist";
        $mx_filter_read = $db->select($mx_filter_query);
        if ($mx_filter_read) {
            $mx_filter_count = mysqli_num_rows($mx_filter_read);
            if (($mx_filter_count > 0) && !empty($target_id)) {
                $mx_filter_update_sql = "UPDATE evp_mx_skiplist SET mx_server = '$mx_server', reason = '$reason' WHERE id = $target_id";
            } else {
                $mx_filter_update_sql = "INSERT INTO `evp_mx_skiplist` (`mx_server`, `reason`) VALUES ('$mx_server', '$reason')";
            }
            $mx_filter_update_read = $db->update($mx_filter_update_sql);
            if ($mx_filter_update_read) {
                if (empty($target_id)) {
                    $target_id = mysqli_insert_id($db->link);
                }
                $error = false;
                $message = "New changes saved!";
                $response = array(
                    'target_id' => $target_id,
                    'mx_server' => $mx_server,
                    'reason' => $reason,
                    'success' => $message
                );
                exit(json_encode($response));
            } else {
                $error = true;
                $message = "Database connection failed";
                $response = array(
                    'error' => $message
                );
                exit(json_encode($response));
            }
        } else {
            $error = true;
            $message = 'Database Connection Error';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } else {
        $error = true;
        $message = 'Data Not Found';
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    }
} elseif (isset($_POST['ea_filter']) && !empty($_POST['ea_filter'])) {
    $ea_filter = sanitize_input($_POST['ea_filter']);
    $user_id = sanitize_input($user_id);
    $target_id = sanitize_input($_POST['target_id']);
    $ea_data = sanitize_input($_POST['ea_data']);
    if (!empty($_FILES['file']['name'])) {
        $file_data = fopen($_FILES['file']['tmp_name'], 'r');
        fgetcsv($file_data);
        $i = 0;
        $success_count = 0;
        $error_count = 0;
        $ignored_count = 0;
        $error_messages = [];
        while ($row = fgetcsv($file_data)) {
            $i++;
            $email = $row[$_REQUEST['get_column']];
            $pattern = "/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/";
            if (preg_match($pattern, $email)) {
                $ea_filter_query = "SELECT * FROM evp_email_filter_list WHERE email_address = '$email' AND uid = '$user_id'";
                $ea_filter_read = $db->select($ea_filter_query);
                if ($ea_filter_read && $ea_filter_read->num_rows > 0) {
                    $ignored_count++;
                } else {
                    $ea_filter_query = "INSERT INTO evp_email_filter_list (email_address, uid) VALUES ('$email', '$user_id')";
                    $ea_filter_read = $db->insert($ea_filter_query);
                    if ($ea_filter_read) {
                        $success_count++;
                    } else {
                        $error_messages[] = "$i. $email - (Failed to Insert)";
                        $error_count++;
                    }
                }
            } else {
                $error_messages[] = "$i. $email - (Invalid Format)";
                $error_count++;
            }
        }
        fclose($file_data);
        $response = [
            'status' => 'success',
            'message' => "$success_count emails imported successfully. $ignored_count emails ignored. $error_count errors occurred.",
            'errors' => $error_messages
        ];
        exit(json_encode($response));
    } elseif (isset($_POST['ea_filter']) && $ea_filter == "delete_email" && !empty($_POST['selected_ids'])) {
        $selected_rows = $_POST['selected_ids'];
        $count_deleted_rows = 0;
        foreach ($selected_rows as $row) {
            $ea_filter_query = "DELETE FROM evp_email_filter_list WHERE id = '$row' AND uid = '$user_id'";
            $ea_filter_read = $db->delete($ea_filter_query);
            if ($ea_filter_read) {
                $count_deleted_rows++;
            }
        }
        if ($count_deleted_rows > 0) {
            $error = false;
            $message = 'Successfully deleted';
            $response = array(
                'msg' => $message
            );
            exit(json_encode($response));
        } else {
            $error = true;
            $message = 'error';
            $response = array(
                'msg' => $message
            );
            exit(json_encode($response));
        }
    } elseif ($ea_filter == 'delete' && !empty($target_id)) {
        $delete_data_sql = "DELETE FROM evp_email_filter_list WHERE id = '$target_id' ";
        $delete_data_read = $db->delete($delete_data_sql);
        if ($delete_data_read) {
            $error = false;
            $message = 'Successfully deleted';
            $response = array(
                'success' => $message
            );
            exit(json_encode($response));
        } else {
            $error = true;
            $message = 'Database connection failed';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } elseif ($ea_filter == 'update' && !empty($ea_data)) {
        $email_add = filter_var($ea_data, FILTER_SANITIZE_EMAIL);
        $reason_add = sanitize_input($_POST['reason_add']);
        if (!filter_var($email_add, FILTER_VALIDATE_EMAIL)) {
            $response = [
                'msg' => 'error',
                'error' => 'Invalid email format!'
            ];
            exit(json_encode($response));
        }
        $ea_filter_query = "SELECT * FROM evp_email_filter_list";
        $ea_filter_read = $db->select($ea_filter_query);
        if ($ea_filter_read) {
            $ea_filter_count = mysqli_num_rows($ea_filter_read);
            if (($ea_filter_count > 0) && !empty($target_id)) {
                $ea_filter_update_sql = "UPDATE evp_email_filter_list SET email_address = '$email_add', reason = '$reason_add' WHERE id = $target_id AND uid = '$user_id'";
            } else {
                $ea_filter_update_sql = "INSERT INTO `evp_email_filter_list` (`uid`, `email_address`, `reason`) VALUES ('$user_id', '$email_add', '$reason_add')";
            }
            $ea_filter_update_read = $db->update($ea_filter_update_sql);
            if ($ea_filter_update_read) {
                if (empty($target_id)) {
                    $target_id = mysqli_insert_id($db->link);
                }
                $response = [
                    'msg' => 'success',
                    'success' => 'Email and reason updated successfully!',
                    'target_id' => $target_id,
                    'email_add' => $email_add,
                    'reason_add' => $reason_add
                ];
                exit(json_encode($response));
            } else {
                $response = [
                    'msg' => 'error',
                    'error' => 'Failed to update the record.'
                ];
                exit(json_encode($response));
            }
        } else {
            $response = [
                'msg' => 'error',
                'error' => 'Database connection error.'
            ];
            exit(json_encode($response));
        }
    } elseif (isset($_POST['ea_filter']) && $_POST['ea_filter'] === 'add_email') {
        $email_address = sanitize_input($_POST['email_address']);
        $reason_add = sanitize_input($_POST['email_reason']);
        $pattern = "/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/";
        if (!preg_match($pattern, $email_address)) {
            $response = array(
                'msg' => 'error',
                'error' => 'Invalid email format!'
            );
            exit(json_encode($response));
        }
        $check_email_sql = "SELECT * FROM evp_email_filter_list WHERE email_address = '$email_address' AND uid = '$user_id'";
        $check_email_read = $db->select($check_email_sql);
        if ($check_email_read && mysqli_num_rows($check_email_read) > 0) {
            $response = array(
                'msg' => 'info',
                'info' => 'Email already exists!'
            );
            exit(json_encode($response));
        }
        $insert_email_sql = "INSERT INTO evp_email_filter_list (email_address, reason, uid) VALUES ('$email_address', '$reason_add', '$user_id')";
        $insert_email_read = $db->insert($insert_email_sql);
        if ($insert_email_read) {
            $response = array(
                'msg' => 'success',
                'success' => 'Email added successfully!'
            );
        } else {
            $response = array(
                'msg' => 'error',
                'error' => 'Failed to add email. Please try again later.'
            );
        }
        exit(json_encode($response));
    } else {
        $error = true;
        $message = 'Data Not Found';
        error_log("Data Not Found Error: POST Data - " . json_encode($_POST));
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    }
} elseif (isset($_POST['de_filter']) && !empty($_POST['de_filter'])) {
    $de_filter = sanitize_input($_POST['de_filter']);
    $user_id = sanitize_input($user_id);
    $target_id = sanitize_input($_POST['target_id']);
    $de_data = $_POST['de_data'];
    if ($de_filter == 'delete' && !empty($target_id)) {
        $delete_data_sql = "DELETE FROM evp_dummy_emails WHERE id = '$target_id' ";
        $delete_data_read = $db->delete($delete_data_sql);
        if ($delete_data_read) {
            $error = false;
            $message = 'Successfully deleted';
            $response = array(
                'success' => $message
            );
            exit(json_encode($response));
        } else {
            $error = true;
            $message = 'Database connection failed';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } elseif ($de_filter == 'update' && !empty($de_data)) {
        $sub = sanitize_input($de_data[0]);
        $msg = $de_data[1];
        $de_filter_query = "SELECT * FROM evp_dummy_emails";
        $de_filter_read = $db->select($de_filter_query);
        if ($de_filter_read) {
            $de_filter_count = mysqli_num_rows($de_filter_read);
            if (($de_filter_count > 0) && !empty($target_id)) {
                $de_filter_update_sql = "UPDATE evp_dummy_emails SET sub = '$sub', msg = '$msg' WHERE id = $target_id AND user_id = '$user_id'";
            } else {
                $de_filter_update_sql = "INSERT INTO `evp_dummy_emails` (`user_id`, `sub`, `msg`) VALUES ('$user_id', '$sub', '$msg')";
            }
            $de_filter_update_read = $db->update($de_filter_update_sql);
            if ($de_filter_update_read) {
                if (empty($target_id)) {
                    $target_id = mysqli_insert_id($db->link);
                }
                $error = false;
                $message = "New changes saved!";
                $response = array(
                    'target_id' => $target_id,
                    'sub' => $sub,
                    'msg' => $msg,
                    'success' => $message
                );
                exit(json_encode($response));
            } else {
                $error = true;
                $message = "Database connection failed";
                $response = array(
                    'error' => $message
                );
                exit(json_encode($response));
            }
        } else {
            $error = false;
            $message = 'Database Connection Error';
            $response = array(
                'error' => $message
            );
            exit(json_encode($response));
        }
    } else {
        $error = true;
        $message = 'Data Not Found';
        $response = array(
            'error' => $message
        );
        exit(json_encode($response));
    }
} elseif (isset($_POST['profile_img_btn'])) {
    $action_std = true;
    $action_cat = 'profile_img';
    $user_id = test_input($_POST['user_id']);
    $img_url = test_input($_FILES['img_url']['name']);
    if (!empty($img_url)) {
        $fileinfo = @getimagesize($_FILES["img_url"]["tmp_name"]);
        $width = $fileinfo[0];
        $height = $fileinfo[1];
        $allowed_image_extension = array("png", "jpg", "jpeg");
        $file_extension = pathinfo($_FILES["img_url"]["name"], PATHINFO_EXTENSION);
        $file_extension = strtolower($file_extension);
        if (!file_exists($_FILES["img_url"]["tmp_name"])) {
            $error = true;
            $message = "Choose image file to upload.";
        } elseif (!in_array($file_extension, $allowed_image_extension)) {
            $error = true;
            $message = "Upload valid images. Only PNG, JPG and JPEG are allowed.";
        } elseif (($_FILES["img_url"]["size"] > 500000)) {
            $error = true;
            $message = "Image size exceeds 500KB";
        } else {
            $img_url = $user_id . "." . $file_extension;
            $img_url = $user_name . '_' . $img_url;
            $target = "../uploads/" . $img_url;
            if (!empty($user_image_url) && $user_image_url != 0) {
                unlink('../uploads/' . $user_image_url);
            }
            if (move_uploaded_file($_FILES["img_url"]["tmp_name"], $target)) {
                $user_update_sql = "UPDATE evp_options
                    SET option_value = CASE option_name
                        WHEN 'image' THEN '$img_url'
                    END
                    WHERE option_name IN ('image')";
                $user_insert_read = $db->update($user_update_sql);
                if ($user_insert_read) {
                    $error = false;
                    $message = "Image uploaded successfully.";
                } else {
                    $error = true;
                    $message = "Problem in uploading database files.";
                }
            } else {
                $error = true;
                $message = "Problem in uploading image files.";
            }
        }
    } else {
        $error = true;
        $message = "No Image found";
    }
} elseif (isset($_POST['save_warmup_config'])) {
    if (isset($_SESSION['auth_log']) && $_SESSION['auth_log'] == true) {
        $config = [];
        $config['global_enabled'] = isset($_POST['warmup_global_enabled']) ? (bool) $_POST['warmup_global_enabled'] : false;
        $config['global_limit'] = isset($_POST['warmup_global_limit']) ? intval($_POST['warmup_global_limit']) : 20;

        $config['providers'] = [];
        if (isset($_POST['providers']) && is_array($_POST['providers'])) {
            foreach ($_POST['providers'] as $p) {
                $clean_p = [
                    'name' => htmlspecialchars(trim($p['name'])),
                    'slug' => strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $p['name'])),
                    'domains' => htmlspecialchars(trim($p['domains'])),
                    'limit' => intval($p['limit']),
                    'status' => isset($p['status']) && $p['status'] == 'active' ? 'active' : 'inactive'
                ];
                $config['providers'][] = $clean_p;
            }
        }

        $json_config = json_encode($config);
        $escaped_config = mysqli_real_escape_string($db->link, $json_config);

        $check_sql = "SELECT option_name FROM evp_options WHERE option_name = 'warmup_config'";
        $check = $db->select($check_sql);

        if ($check && $check->num_rows > 0) {
            $sql = "UPDATE evp_options SET option_value = '$escaped_config' WHERE option_name = 'warmup_config'";
            $res = $db->update($sql);
        } else {
            $sql = "INSERT INTO evp_options (option_name, option_value) VALUES ('warmup_config', '$escaped_config')";
            $res = $db->insert($sql);
        }

        if ($res || $db->link->affected_rows >= 0) {
            exit(json_encode(['success' => 'Warm-up configuration saved successfully.']));
        } else {
            exit(json_encode(['error' => 'Database error: ' . $db->link->error]));
        }
    }
    exit(json_encode(['error' => 'Authentication failed']));
} else {
    header("Location: $a_url/" . $error_404_page);
}

if ($action_std && !empty($action_cat)) {
    Session::set("action_cat", $action_cat);
    Session::set("action", $error);
    Session::set("action_message", $message);
    header("Location: $a_url/" . $settings_page);
} else {
    header("Location: $a_url/" . $error_404_page);
}

?>