<?php
require_once 'auth_check.php';
require_once 'db.php';
session_start();

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $db = getDB1Connection();
    $stmt = $db->prepare("SELECT config FROM email_configs WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        throw new Exception('Email not configured');
    }

    $config = json_decode($result['config'], true);
    $password = decrypt($config['password']);

    $to = $_POST['to'];
    $subject = $_POST['subject'];
    $body = $_POST['body'];

    $mailer = setupMailer($config, $password);
    $mailer->addAddress($to);
    $mailer->Subject = $subject;
    $mailer->Body = $body;
    $mailer->isHTML(true);

    if (!$mailer->send()) {
        throw new Exception($mailer->ErrorInfo);
    }

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

function decrypt($data) {
    $key = getenv('ENCRYPTION_KEY');
    $data = base64_decode($data);
    $iv = substr($data, 0, 16);
    $encrypted = substr($data, 16);
    return openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
}

function setupMailer($config, $password) {
    $mailer = new PHPMailer\PHPMailer\PHPMailer(true);

    $mailer->isSMTP();
    $mailer->CharSet = 'UTF-8';

    switch($config['service']) {
        case 'gmail':
            $mailer->Host = 'smtp.gmail.com';
            $mailer->Port = 587;
            break;
        case 'outlook':
            $mailer->Host = 'smtp.office365.com';
            $mailer->Port = 587;
            break;
        case 'yahoo':
            $mailer->Host = 'smtp.mail.yahoo.com';
            $mailer->Port = 587;
            break;
        case 'custom':
            $mailer->Host = $config['smtp_server'];
            $mailer->Port = $config['smtp_port'];
            break;
    }

    $mailer->SMTPAuth = true;
    $mailer->Username = $config['email'];
    $mailer->Password = $password;
    $mailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
    $mailer->setFrom($config['email']);

    return $mailer;
}