<?php
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
require 'vendor/phpmailer/phpmailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

function sendEmailViaGmail($smtp_email, $smtp_password, $target_email, $email_data) {
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = $smtp_email;
        $mail->Password = $smtp_password;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        
        // Recipients
        $mail->setFrom($smtp_email, 'Email Sender');
        $mail->addAddress($target_email);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = $email_data['subject'];
        $mail->Body = $email_data['html_body'];
        
        // Hanya tambah header yang aman
        $mail->addCustomHeader('X-Custom-IP: ' . $email_data['custom_ip']);
        $mail->addCustomHeader('X-Original-From: ' . $email_data['from_email']);
        
        $mail->send();
        return [
            'status' => 'success', 
            'message' => 'Email berhasil dikirim ke ' . $target_email
        ];
        
    } catch (Exception $e) {
        return [
            'status' => 'error', 
            'message' => 'Gagal mengirim email: ' . $mail->ErrorInfo
        ];
    }
}
?>