<?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();
$route = getApiRouteSegments();
$id = isset($route[2]) ? (int) $route[2] : 0;

if ($id <= 0) {
    jsonResponse(false, 'mailboxes.invalid_id', null, 422);
}

$repo = new MailboxRepository($pdo);
$current = $repo->findById($id, true);
if (!$current) {
    jsonResponse(false, 'mailboxes.not_found', null, 404);
}

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

if ($name === '' || $email === '' || $username === '' || $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, $id)) {
    jsonResponse(false, 'mailboxes.email_exists', null, 409);
}

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

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

$repo->update($id, [
    '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.updated', $repo->findById($id));
