<?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);

if (!function_exists('imap_open')) {
    jsonResponse(false, 'mailboxes.imap_not_available', null, 500);
}

$mailboxId = isset($input['mailbox_id']) ? (int) $input['mailbox_id'] : 0;

if ($mailboxId > 0) {
    $saved = $repo->findById($mailboxId, true);
    if (!$saved) {
        jsonResponse(false, 'mailboxes.not_found', null, 404);
    }

    try {
        $password = decryptMailboxSecret((string) $saved['password_encrypted'], $config);
    } catch (Throwable $e) {
        jsonResponse(false, $e->getMessage() ?: 'mailboxes.decryption_failed', null, 500);
    }

    $name = (string) $saved['name'];
    $email = (string) $saved['email'];
    $username = (string) $saved['username'];
    $host = (string) $saved['host'];
    $port = (int) $saved['port'];
    $protocol = strtolower((string) $saved['protocol']);
    $encryption = strtolower((string) $saved['encryption']);
} else {
    $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')));

    if ($name === '' || $email === '' || $username === '' || $password === '' || $host === '' || $port <= 0) {
        jsonResponse(false, 'mailboxes.required_fields', 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);
}

$mailboxString = sprintf(
    '{%s:%d/%s%s}INBOX',
    $host,
    $port,
    $protocol,
    $encryption !== 'none' ? '/' . $encryption : ''
);

$errorsBefore = imap_errors();
$connection = @imap_open($mailboxString, $username, $password, (int) ($config['mailboxes']['imap_open_options'] ?? 0), 1);

if ($connection === false) {
    $errors = imap_errors() ?: [];
    $message = 'mailboxes.connection_failed';
    $details = [
        'mailbox_string' => $mailboxString,
        'errors' => $errors,
    ];

    if ($mailboxId > 0) {
        $repo->recordTestResult($mailboxId, false, $message);
    }

    jsonResponse(false, $message, $details, 422);
}

$totalMessages = imap_num_msg($connection);
imap_close($connection);
if ($mailboxId > 0) {
    $repo->recordTestResult($mailboxId, true, 'mailboxes.connection_success');
}

jsonResponse(true, 'mailboxes.connection_success', [
    'name' => $name,
    'email' => $email,
    'host' => $host,
    'port' => $port,
    'protocol' => $protocol,
    'encryption' => $encryption,
    'total_messages' => $totalMessages,
]);
