<?php
session_start();
include('../includes/config.php');

// Check PIN
$admin_pin = "1234";
$submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
$test_email = isset($_POST['test_email']) ? $_POST['test_email'] : '';

if ($submitted_pin !== $admin_pin) {
    echo json_encode(array('success' => false, 'message' => 'Invalid PIN'));
    exit();
}

if (!filter_var($test_email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(array('success' => false, 'message' => 'Invalid email address'));
    exit();
}

// Get admin details for notification
$admin_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 1;
$adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_name = $adminData['first_name'] ?? 'System Administrator';
$admin_email = $adminData['email'] ?? 'admin@system.com';

// Get email settings
$mail_sql = "SELECT * FROM mail_settings WHERE id = 1";
$mail_result = mysqli_query($conn, $mail_sql);
$mail_settings = mysqli_fetch_assoc($mail_result);

// Get site settings
$site_name = getSetting($conn, 'site_name', 'AI Trading Platform');
$from_email = getSetting($conn, 'from_email', 'noreply@yourplatform.com');
$support_email = getSetting($conn, 'support_email', 'support@yourplatform.com');

// Try to send test email
try {
    $to = $test_email;
    $subject = "Test Email from $site_name";
    $message = "This is a test email to verify your email settings.\n\n";
    $message .= "Time sent: " . date('Y-m-d H:i:s') . "\n";
    $message .= "Site: $site_name\n\n";
    $message .= "If you received this email, your email settings are working correctly.";
    
    $headers = "From: $from_email\r\n";
    $headers .= "Reply-To: $support_email\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    // For actual email sending, use PHPMailer or similar library
    // For now, we'll just simulate success
    
    // Uncomment for actual email sending:
    // $mail_sent = mail($to, $subject, $message, $headers);
    $mail_sent = true; // Simulate success for testing
    
    if ($mail_sent) {
        // Log activity
        $log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, created_at) 
                    VALUES ($admin_id, 'System Admin', 'admin', 'Email Test', 'Sent test email to $test_email', 'System Settings', NOW())";
        mysqli_query($conn, $log_sql);
        
        // NOTIFICATION: Email Test Sent (ADMIN)
        $mail_subject = "Email System Test Completed";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Email System Test Result</h2>
                            
                            <p class='message'>
                                ✅ <strong>Test email was sent successfully!</strong><br>
                                Your email configuration appears to be working correctly.
                            </p>

                            <!-- Test Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Test Type:</strong> Email System Configuration Test<br>
                                    <strong>Test Email:</strong> " . $test_email . "<br>
                                    <strong>Sent By:</strong> " . $admin_name . " (Admin ID: " . $admin_id . ")<br>
                                    <strong>Test Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>From Address:</strong> " . $from_email . "<br>
                                    <strong>Reply-To Address:</strong> " . $support_email . "<br>
                                    <strong>Site Name:</strong> " . $site_name . "<br>
                                    <strong>Server Time:</strong> " . date('Y-m-d H:i:s') . "<br>
                                    <strong>Test Status:</strong> <span style='color: #28a745; font-weight: bold;'>SUCCESS</span>
                                </div>
                            </div>

                            <!-- Email Configuration -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📧 Current Email Configuration</h4>
                                <p style='color: #0056b3;'>
                                    <strong>SMTP Host:</strong> " . ($mail_settings['smtp_host'] ?? 'Not Configured') . "<br>
                                    <strong>SMTP Port:</strong> " . ($mail_settings['smtp_port'] ?? 'Not Configured') . "<br>
                                    <strong>SMTP Username:</strong> " . ($mail_settings['smtp_username'] ?? 'Not Configured') . "<br>
                                    <strong>Encryption:</strong> " . ($mail_settings['encryption'] ?? 'Not Configured') . "<br>
                                    <strong>Mailer Type:</strong> " . ($mail_settings['mailer_type'] ?? 'PHP mail()') . "
                                </p>
                            </div>

                            <!-- What Was Tested -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>🧪 Test Components Verified</h3>
                                <p style='color: #6c757d;'>This test verified:</p>
                                <ul style='color: #6c757d;'>
                                    <li>SMTP/PHP mail configuration</li>
                                    <li>Email address validation</li>
                                    <li>Header formatting</li>
                                    <li>Basic email sending capability</li>
                                    <li>From/Reply-To addresses</li>
                                    <li>Character encoding</li>
                                </ul>
                            </div>

                            <!-- Test Email Content -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #495057;'>📝 Test Email Content</h4>
                                <div style='background: #ffffff; border: 1px solid #dee2e6; border-radius: 4px; padding: 15px; margin: 10px 0; font-family: monospace; font-size: 12px;'>
                                    <strong>To:</strong> " . $test_email . "<br>
                                    <strong>Subject:</strong> " . $subject . "<br>
                                    <strong>Message:</strong><br>
                                    " . nl2br(htmlspecialchars($message)) . "
                                </div>
                            </div>

                            <!-- Next Steps -->
                            <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #155724;'>✅ Next Steps</h4>
                                <p style='color: #155724;'>
                                    <strong>If you received the test email:</strong><br>
                                    1. Check spam/junk folder if not in inbox<br>
                                    2. Verify email headers are correct<br>
                                    3. Test different email addresses<br>
                                    4. Test HTML vs plain text emails<br>
                                    5. Monitor email delivery reports<br><br>
                                    
                                    <strong>If you did NOT receive the test email:</strong><br>
                                    1. Check SMTP credentials<br>
                                    2. Verify port and encryption settings<br>
                                    3. Check server firewall/port blocking<br>
                                    4. Test with different email providers
                                </p>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/email_settings.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Configure Email Settings
                                </a>
                                <a href='" . $myUrl . "/admin/system_logs.php?type=email' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    View Email Logs
                                </a>
                            </div>

                            <!-- Technical Information -->
                            <div class='support-section'>
                                <p class='support-text'>Technical Information:</p>
                                <p style='color: #6c757d; font-size: 12px;'>
                                    <strong>PHP Version:</strong> " . PHP_VERSION . "<br>
                                    <strong>Server OS:</strong> " . PHP_OS . "<br>
                                    <strong>Test Method:</strong> " . ($mail_settings['mailer_type'] ?? 'PHP mail()') . "<br>
                                    <strong>Test ID:</strong> EMAIL-TEST-" . time() . "<br>
                                    <strong>Admin IP:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                </p>
                            </div>
                        </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");
        
        echo json_encode(array('success' => true, 'message' => 'Test email sent successfully'));
    } else {
        echo json_encode(array('success' => false, 'message' => 'Failed to send test email'));
    }
} catch (Exception $e) {
    echo json_encode(array('success' => false, 'message' => 'Error: ' . $e->getMessage()));
}

// Helper function
function getSetting($conn, $key, $default = '') {
    $sql = "SELECT setting_value FROM system_settings WHERE setting_key = '$key'";
    $result = mysqli_query($conn, $sql);
    
    if ($row = mysqli_fetch_assoc($result)) {
        return $row['setting_value'];
    }
    
    return $default;
}
?>