<?php
// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors, we'll return them as JSON
ini_set('log_errors', 1);

session_start();
require_once '../layouts/dbconn.php';

// Import PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Check if PHPMailer files exist
$phpmailer_path = '../vendor/phpmailer/src/';
if (!file_exists($phpmailer_path . 'PHPMailer.php')) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'PHPMailer library not found. Please ensure vendor/phpmailer/src/ exists.',
        'error_details' => 'Path checked: ' . $phpmailer_path
    ]);
    exit();
}

require $phpmailer_path . 'Exception.php';
require $phpmailer_path . 'PHPMailer.php';
require $phpmailer_path . 'SMTP.php';

header('Content-Type: application/json');

// Check authorization
$allowed = (isset($_SESSION['role_code']) && $_SESSION['role_code'] === 'SUPER_ADMIN')
    || (isset($_SESSION['role_id']) && in_array($_SESSION['role_id'], [1, 2]));

if (!isset($_SESSION['user_id']) || !$allowed) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access. Please login as Super Admin or Hospital Admin.'
    ]);
    exit();
}

// Get test email address
$test_email = $_POST['test_email'] ?? '';

if (empty($test_email)) {
    echo json_encode([
        'success' => false,
        'message' => 'No email address provided'
    ]);
    exit();
}

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

try {
    // Get email settings from POST or database
    $smtp_host = $_POST['smtp_host'] ?? '';
    $smtp_port = $_POST['smtp_port'] ?? '';
    $smtp_username = $_POST['smtp_username'] ?? '';
    $smtp_password = $_POST['smtp_password'] ?? '';
    $smtp_encryption = $_POST['smtp_encryption'] ?? 'tls';
    $email_from = $_POST['email_from'] ?? '';
    $email_from_name = $_POST['email_from_name'] ?? '';
    
    // If not in POST, fetch from database
    if (empty($smtp_host)) {
        $sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'email'";
        $result = $conn->query($sql);
        
        if (!$result) {
            throw new Exception('Database query failed: ' . $conn->error);
        }
        
        $settings = [];
        while ($row = $result->fetch_assoc()) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
        
        $smtp_host = $settings['smtp_host'] ?? '';
        $smtp_port = $settings['smtp_port'] ?? '587';
        $smtp_username = $settings['smtp_username'] ?? '';
        $smtp_password = $settings['smtp_password'] ?? '';
        $smtp_encryption = $settings['smtp_encryption'] ?? 'tls';
        $email_from = $settings['email_from'] ?? '';
        $email_from_name = $settings['email_from_name'] ?? 'ENT Hospital';
    }
    
    // Validate required settings
    $missing_fields = [];
    if (empty($smtp_host)) $missing_fields[] = 'SMTP Host';
    if (empty($smtp_port)) $missing_fields[] = 'SMTP Port';
    if (empty($smtp_username)) $missing_fields[] = 'SMTP Username';
    if (empty($smtp_password)) $missing_fields[] = 'SMTP Password';
    
    if (!empty($missing_fields)) {
        echo json_encode([
            'success' => false,
            'message' => 'Missing required email settings: ' . implode(', ', $missing_fields),
            'error_details' => 'Please fill in all SMTP configuration fields and try again.'
        ]);
        exit();
    }
    
    // Create PHPMailer instance
    $mail = new PHPMailer(true);
    
    // Server settings
    $mail->SMTPDebug = SMTP::DEBUG_OFF; // Disable debug output
    $mail->isSMTP();
    $mail->Host = $smtp_host;
    $mail->SMTPAuth = true;
    $mail->Username = $smtp_username;
    $mail->Password = $smtp_password;
    $mail->Port = intval($smtp_port);
    
    // Set encryption
    if ($smtp_encryption === 'ssl') {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    } elseif ($smtp_encryption === 'tls') {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    }
    
    // Additional SMTP options for better compatibility
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    
    // Set timeout
    $mail->Timeout = 30;
    $mail->SMTPKeepAlive = false;
    
    // Sender information
    $from_email = $email_from ?: $smtp_username;
    $from_name = $email_from_name ?: 'ENT Hospital';
    
    $mail->setFrom($from_email, $from_name);
    $mail->addAddress($test_email);
    $mail->addReplyTo($from_email, $from_name);
    
    // Email content
    $mail->isHTML(true);
    $mail->CharSet = 'UTF-8';
    $mail->Subject = 'ENT Hospital - Email Configuration Test';
    
    $mail->Body = '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
        <div style="max-width: 600px; margin: 20px auto; background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 20px; text-align: center;">
                <h1 style="color: white; margin: 0; font-size: 28px;">✅ Email Test Successful!</h1>
            </div>
            
            <div style="padding: 40px 30px;">
                <p style="font-size: 16px; color: #333; line-height: 1.6; margin-bottom: 20px;">
                    Congratulations! Your email configuration is working correctly.
                </p>
                
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #059669;">
                    <h3 style="margin-top: 0; color: #059669;">SMTP Configuration Details:</h3>
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr>
                            <td style="padding: 8px 0; color: #666;"><strong>SMTP Server:</strong></td>
                            <td style="padding: 8px 0; color: #333;">' . htmlspecialchars($smtp_host) . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; color: #666;"><strong>Port:</strong></td>
                            <td style="padding: 8px 0; color: #333;">' . htmlspecialchars($smtp_port) . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; color: #666;"><strong>Encryption:</strong></td>
                            <td style="padding: 8px 0; color: #333;">' . strtoupper(htmlspecialchars($smtp_encryption)) . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 0; color: #666;"><strong>From:</strong></td>
                            <td style="padding: 8px 0; color: #333;">' . htmlspecialchars($from_name) . ' &lt;' . htmlspecialchars($from_email) . '&gt;</td>
                        </tr>
                    </table>
                </div>
                
                <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin: 20px 0;">
                    <p style="margin: 0; font-size: 14px; color: #1565c0;">
                        <strong>✓ Your system is ready to send:</strong><br>
                        • Appointment confirmations<br>
                        • Medical reports<br>
                        • Invoices and receipts<br>
                        • Patient notifications
                    </p>
                </div>
                
                <p style="font-size: 14px; color: #666; line-height: 1.6; margin-top: 30px;">
                    This is an automated test email from your ENT Hospital Management System.
                </p>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0;">
                <p style="font-size: 12px; color: #999; margin: 0;">
                    ENT Hospital Management System<br>
                    Powered by ProdigyKenya
                </p>
            </div>
        </div>
    </body>
    </html>
    ';
    
    $mail->AltBody = "✅ Email Test Successful!\n\n" .
                     "Congratulations! Your email configuration is working correctly.\n\n" .
                     "SMTP Configuration:\n" .
                     "• Server: $smtp_host\n" .
                     "• Port: $smtp_port\n" .
                     "• Encryption: " . strtoupper($smtp_encryption) . "\n" .
                     "• From: $from_name <$from_email>\n\n" .
                     "Your system is ready to send appointment confirmations, medical reports, invoices, and patient notifications.\n\n" .
                     "ENT Hospital Management System\n" .
                     "Powered by ProdigyKenya";
    
    // Send email
    if (!$mail->send()) {
        throw new Exception($mail->ErrorInfo);
    }
    
    // Reconnect to database before logging (in case connection timed out during email sending)
    if (!$conn->ping()) {
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($conn->connect_error) {
            // If reconnection fails, continue anyway - logging is not critical
            error_log("Database reconnection failed: " . $conn->connect_error);
        }
    }
    
    // Log successful test (using try-catch so logging errors don't break the success response)
    try {
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_type, ip_address) 
                    VALUES (?, 'TEST', 'email_settings', ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        if ($log_stmt) {
            $log_record_type = "Email test to: $test_email";
            $log_stmt->bind_param("iss", $_SESSION['user_id'], $log_record_type, $_SERVER['REMOTE_ADDR']);
            $log_stmt->execute();
            $log_stmt->close();
        }
    } catch (Exception $log_error) {
        // Log error but don't fail the request
        error_log("Activity log failed: " . $log_error->getMessage());
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Test email sent successfully to $test_email",
        'details' => [
            'smtp_host' => $smtp_host,
            'smtp_port' => $smtp_port,
            'encryption' => strtoupper($smtp_encryption),
            'from' => "$from_name <$from_email>"
        ]
    ]);
    
} catch (Exception $e) {
    // Log error
    $error_message = $e->getMessage();
    
    // Reconnect to database before logging (in case connection timed out)
    if (!$conn->ping()) {
        try {
            $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        } catch (Exception $reconnect_error) {
            // Continue even if reconnection fails
            error_log("Database reconnection failed: " . $reconnect_error->getMessage());
        }
    }
    
    // Try to log error (but don't fail if logging fails)
    try {
        $error_log_sql = "INSERT INTO activity_log (user_id, action, module, record_type, ip_address) 
                          VALUES (?, 'ERROR', 'email_settings', ?, ?)";
        $error_log_stmt = $conn->prepare($error_log_sql);
        if ($error_log_stmt) {
            $error_record_type = "Email test failed: " . substr($error_message, 0, 200);
            $error_log_stmt->bind_param("iss", $_SESSION['user_id'], $error_record_type, $_SERVER['REMOTE_ADDR']);
            $error_log_stmt->execute();
            $error_log_stmt->close();
        }
    } catch (Exception $log_error) {
        // Log error but don't fail the request
        error_log("Activity log failed: " . $log_error->getMessage());
    }
    
    // Determine user-friendly error message
    $user_message = "Email test failed";
    
    if (strpos($error_message, 'SMTP connect() failed') !== false) {
        $user_message = "Cannot connect to SMTP server. Please verify host and port settings.";
    } elseif (strpos($error_message, 'SMTP Error: Could not authenticate') !== false || 
              strpos($error_message, 'Authentication') !== false) {
        $user_message = "SMTP authentication failed. Please check your username and password. For Gmail, use an App Password.";
    } elseif (strpos($error_message, 'Invalid address') !== false) {
        $user_message = "Invalid email address in configuration. Please check the 'From Email' setting.";
    } elseif (strpos($error_message, 'timed out') !== false || 
              strpos($error_message, 'timeout') !== false) {
        $user_message = "Connection timed out. Please check if port " . ($smtp_port ?? 'N/A') . " is accessible and not blocked by firewall.";
    } elseif (strpos($error_message, 'Connection refused') !== false) {
        $user_message = "Connection refused. The SMTP server may be down or the port (" . ($smtp_port ?? 'N/A') . ") may be blocked.";
    }
    
    echo json_encode([
        'success' => false,
        'message' => $user_message,
        'error_details' => $error_message
    ]);
}

// Close connection if still open
if ($conn && $conn->ping()) {
    $conn->close();
}
?>