<?php

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../config/helpers.php';
require_once __DIR__ . '/../../../middleware/admin.php';
require_once __DIR__ . '/MailboxRepository.php';

requireAdmin();
global $pdo;
$config = require __DIR__ . '/../../../config/app.php';
$input = getJsonInput();
$repo = new MailboxRepository($pdo);

$name = trim((string) ($input['name'] ?? ''));
$email = strtolower(trim((string) ($input['email'] ?? '')));
$username = trim((string) ($input['username'] ?? ''));
$password = (string) ($input['password'] ?? '');
$host = trim((string) ($input['host'] ?? ''));
$port = (int) ($input['port'] ?? 0);
$protocol = strtolower(trim((string) ($input['protocol'] ?? 'imap')));
$encryption = strtolower(trim((string) ($input['encryption'] ?? 'ssl')));
$isActive = normalizeBool($input['is_active'] ?? true, true) ? 1 : 0;
$isDefault = normalizeBool($input['is_default'] ?? false, false) ? 1 : 0;
$notes = trim((string) ($input['notes'] ?? ''));

if ($name === '' || $email === '' || $username === '' || $password === '' || $host === '' || $port <= 0) {
    jsonResponse(false, 'mailboxes.required_fields', null, 422);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    jsonResponse(false, 'mailboxes.invalid_email', null, 422);
}

if (!in_array($protocol, ['imap', 'pop3'], true)) {
    jsonResponse(false, 'mailboxes.invalid_protocol', null, 422);
}

if (!in_array($encryption, ['ssl', 'tls', 'none'], true)) {
    jsonResponse(false, 'mailboxes.invalid_encryption', null, 422);
}

if ($repo->findByEmail($email)) {
    jsonResponse(false, 'mailboxes.email_exists', null, 409);
}

try {
    $passwordEncrypted = encryptMailboxSecret($password, $config);
} catch (Throwable $e) {
    jsonResponse(false, $e->getMessage() ?: 'mailboxes.encryption_failed', null, 500);
}

if ($isDefault === 1) {
    $repo->clearDefaultFlag();
}

$id = $repo->create([
    'name' => $name,
    'email' => $email,
    'username' => $username,
    'password_encrypted' => $passwordEncrypted,
    'host' => $host,
    'port' => $port,
    'protocol' => $protocol,
    'encryption' => $encryption,
    'is_active' => $isActive,
    'is_default' => $isDefault,
    'notes' => $notes !== '' ? $notes : null,
]);

jsonResponse(true, 'mailboxes.created', $repo->findById($id), 201);
