<?php
require_once 'db.php';
require_once 'vendor/autoload.php';

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

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

try {
    if (!isset($_POST['recipient_id']) || !is_numeric($_POST['recipient_id']) || 
        !isset($_POST['subject']) || empty(trim($_POST['subject'])) ||
        !isset($_POST['content']) || empty(trim($_POST['content']))) {
        throw new Exception('Invalid or missing required fields');
    }

    $db = getDB1Connection();
    $stmt = $db->prepare("SELECT username, email FROM utilisateurs WHERE id = ?");
    $stmt->execute([$_POST['recipient_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        throw new Exception('User not found');
    }

    if (!filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Invalid email format');
    }

    $emailContent = str_replace('{username}', $user['username'], $_POST['content']);
    
    $htmlContent = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="x-apple-disable-message-reformatting">
    <meta name="format-detection" content="telephone=no, address=no, email=no, date=no">
    <title>Imators Communication</title>
</head>
<body style="background-color: #1a1a1a; margin: 0; padding: 0; font-family: Arial, sans-serif; color: #ffffff;">
    <div style="max-width: 600px; margin: 0 auto; background-color: #262626;">
        <div style="padding: 20px; background-color: #000000;">
            <table role="presentation" border="0" cellpadding="0" cellspacing="0" style="width: 100%;">
                <tr>
                    <td style="padding-left: 15px; border-left: 1px solid #333333; vertical-align: middle;">
                        <h1 style="margin: 0; font-size: 18px; color: #ffffff; line-height: 1.2;">Imators</h1>
                        <p style="margin: 5px 0 0 0; font-size: 12px; color: #888888; line-height: 1.2;">Official Communication</p>
                    </td>
                </tr>
            </table>
        </div>
        <div style="padding: 30px; color: #ffffff; line-height: 1.5;">' . $emailContent . '</div>
        <div style="background-color: #1a1a1a; padding: 20px; text-align: center; border-top: 1px solid #333333;">
            <p style="margin: 0; color: #888888; font-size: 12px;">
                This email was sent by an official Imators team member.<br>
                © ' . date('Y') . ' Imators LLC. All rights reserved.
            </p>
            <div style="margin-top: 15px;">
                <a href="https://imators.com" style="color: #888888; text-decoration: none; font-size: 12px;">imators.com</a>
                <span style="color: #888888; margin: 0 10px;">|</span>
                <a href="https://imators.com/privacy" style="color: #888888; text-decoration: none; font-size: 12px;">Privacy Policy</a>
            </div>
        </div>
    </div>
</body>
</html>';

    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host = 'web05.ouiheberg.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'no-reply@imators.systems';
    $mail->Password = 'imators.managements4455*#@';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port = 465;
    
    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true,
            'allow_self_signed' => false,
            'verify_depth' => 3,
            'SNI_enabled' => true
        ]
    ];

    $mail->XMailer = 'Imators Mailer 1.0';
    $mail->CharSet = 'UTF-8';
    $mail->Encoding = 'base64';
    $mail->Timeout = 30;
    $mail->setLanguage('fr');

    $systemEmail = 'no-reply@imators.systems';
    $supportEmail = 'support@imators.systems';
    $domainName = 'imators.systems';

    if (!filter_var($systemEmail, FILTER_VALIDATE_EMAIL) || !filter_var($supportEmail, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Invalid system email configuration');
    }

    $mail->setFrom($systemEmail, 'Imators Team', false);
    $mail->addReplyTo($supportEmail, 'Imators Support');
    
    // En-têtes anti-spam
    $mail->addCustomHeader('Organization', 'Imators LLC');
    $mail->addCustomHeader('X-Report-Abuse', 'Please report abuse here: abuse@' . $domainName);
    $mail->addCustomHeader('List-Unsubscribe', '<https://imators.com/unsubscribe>, <mailto:unsubscribe@' . $domainName . '>');
    $mail->addCustomHeader('Feedback-ID', 'notification:imators:' . time());
    $mail->addCustomHeader('X-Entity-Ref-ID', uniqid('im_', true));
    $mail->addCustomHeader('X-Sender', $systemEmail);
    $mail->addCustomHeader('X-Sender-Domain', $domainName);
    
    // DKIM est important pour la délivrabilité
    $mail->DKIM_domain = $domainName;
    $mail->DKIM_selector = 'default';
    $mail->DKIM_identity = $systemEmail;
    
    $mail->Priority = 3;
    $mail->addAddress($user['email'], $user['username']);
    $mail->isHTML(true);
    $mail->Subject = $_POST['subject'];
    $mail->Body = $htmlContent;
    $mail->AltBody = strip_tags($emailContent);

    $mail->send();
    ob_clean();
    echo json_encode(['success' => true]);
    exit;

} catch (Exception $e) {
    ob_clean();
    error_log("Mail Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to send email',
        'details' => $e->getMessage()
    ]);
    exit;
}