<?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();
    
    $service = $_POST['email-service'];
    $email = $_POST['email-address'];
    $password = $_POST['email-password'];
    
    $config = [
        'service' => $service,
        'email' => $email,
        'password' => encrypt($password),
    ];
    
    if ($service === 'custom') {
        $config['imap_server'] = $_POST['imap-server'];
        $config['imap_port'] = $_POST['imap-port'];
        $config['smtp_server'] = $_POST['smtp-server'];
        $config['smtp_port'] = $_POST['smtp-port'];
    }
    
    $stmt = $db->prepare("INSERT INTO email_configs (user_id, config) VALUES (?, ?) ON DUPLICATE KEY UPDATE config = ?");
    $configJson = json_encode($config);
    $stmt->execute([$_SESSION['user_id'], $configJson, $configJson]);

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

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

function encrypt($data) {
    $key = getenv('ENCRYPTION_KEY');
    $iv = random_bytes(16);
    $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}