<?php
// JSON API Response - NO OUTPUT BEFORE HEADERS
header('Content-Type: application/json; charset=utf-8');

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Validate authentication
$isLoggedIn = !empty($_SESSION['user_id']);
$isAdmin = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';

if (!$isLoggedIn) {
    http_response_code(403);
    exit(json_encode(['success' => false, 'message' => 'Unauthorized - Please login first']));
}

if (!$isAdmin) {
    http_response_code(403);
    exit(json_encode(['success' => false, 'message' => 'Forbidden - Admin access required']));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit(json_encode(['success' => false, 'message' => 'Method not allowed']));
}

$testEmail = filter_var($_POST['test_email'] ?? '', FILTER_VALIDATE_EMAIL);

if (!$testEmail) {
    http_response_code(400);
    exit(json_encode(['success' => false, 'message' => 'Invalid email address']));
}

try {
    // Load database
    $projectRoot = dirname(dirname(dirname(__FILE__)));
    require_once $projectRoot . '/config/config.php';
    require_once $projectRoot . '/classes/Database.php';
    
    $db = Database::getInstance();
    
    // Get email settings
    $settings = [];
    $keys = ['mail_host', 'mail_port', 'mail_encryption', 'mail_username', 'mail_from_email', 'mail_from_name'];
    
    foreach ($keys as $key) {
        $setting = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', [$key]);
        if ($setting) {
            $settings[$key] = $setting['setting_value'];
        }
    }
    
    $passwordSetting = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', ['mail_password_encrypted']);
    $password = !empty($passwordSetting['setting_value']) ? base64_decode($passwordSetting['setting_value']) : '';
    
    // Validate configuration
    if (empty($settings['mail_host']) || empty($settings['mail_username']) || empty($password)) {
        http_response_code(400);
        exit(json_encode(['success' => false, 'message' => 'Email settings not configured. Please set SMTP Host, Username, and Password.']));
    }
    
    $host = $settings['mail_host'];
    $port = (int)($settings['mail_port'] ?? 465);
    $encryption = $settings['mail_encryption'] ?? 'ssl';
    $username = $settings['mail_username'];
    $fromEmail = $settings['mail_from_email'] ?? $username;
    $fromName = $settings['mail_from_name'] ?? 'Advanced Mobile Info';
    
    // Email content
    $subject = "Test Email from Advanced Mobile Info";
    $body = "This is a test email from your Admin Email Settings panel.\n\n";
    $body .= "Time: " . date('Y-m-d H:i:s') . "\n";
    $body .= "From: $fromEmail\n";
    $body .= "Application: Advanced Mobile Info\n\n";
    $body .= "If you received this, your email configuration is working correctly!";
    
    // Try SMTP
    $protocol = ($encryption === 'tls') ? 'tls' : 'ssl';
    $fp = fsockopen($protocol . '://' . $host, $port, $errno, $errstr, 10);
    
    $emailSent = false;
    $errorMessage = '';
    
    if ($fp) {
        stream_set_blocking($fp, true);
        stream_set_timeout($fp, 10);
        
        fgets($fp, 1024);
        fwrite($fp, "EHLO localhost\r\n");
        while ($line = fgets($fp, 1024)) {
            if (preg_match('/^\d{3} /', $line)) break;
        }
        
        fwrite($fp, "AUTH LOGIN\r\n");
        fgets($fp, 1024);
        fwrite($fp, base64_encode($username) . "\r\n");
        fgets($fp, 1024);
        fwrite($fp, base64_encode($password) . "\r\n");
        $response = fgets($fp, 1024);
        
        if (strpos($response, '235') !== false) {
            fwrite($fp, "MAIL FROM:<$fromEmail>\r\n");
            fgets($fp, 1024);
            fwrite($fp, "RCPT TO:<$testEmail>\r\n");
            fgets($fp, 1024);
            fwrite($fp, "DATA\r\n");
            fgets($fp, 1024);
            
            $headers = "From: $fromName <$fromEmail>\r\n";
            $headers .= "To: $testEmail\r\n";
            $headers .= "Subject: $subject\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
            
            $message = $headers . "\r\n" . $body . "\r\n.\r\n";
            
            fwrite($fp, $message);
            $result = fgets($fp, 1024);
            
            if (strpos($result, '250') === 0) {
                $emailSent = true;
            }
            
            fwrite($fp, "QUIT\r\n");
        } else {
            $errorMessage = 'SMTP Authentication failed';
        }
        
        fclose($fp);
    }
    
    // Fallback to PHP mail()
    if (!$emailSent && empty($errorMessage)) {
        $headers = "From: $fromName <$fromEmail>\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        
        if (mail($testEmail, $subject, $body, $headers)) {
            $emailSent = true;
        } else {
            $errorMessage = 'Failed to send via both SMTP and PHP mail()';
        }
    }
    
    if ($emailSent) {
        http_response_code(200);
        exit(json_encode(['success' => true, 'message' => "✅ Test email sent successfully to $testEmail"]));
    } else {
        http_response_code(400);
        exit(json_encode(['success' => false, 'message' => 'Failed to send test email: ' . ($errorMessage ?: 'Unknown error')]));
    }
    
} catch (Exception $e) {
    http_response_code(500);
    exit(json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]));
}