<?php
require_once __DIR__ . '/../includes/crypto.php';
require_once __DIR__ . '/../includes/db.php';

header('Content-Type: text/html; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $id = (int)($_POST['id'] ?? 0);
  $stmt = pdo()->prepare('SELECT * FROM imap_accounts WHERE id = ?');
  $stmt->execute([$id]);
  $acc = $stmt->fetch();

  if (!$acc) {
    echo "<div class='alert alert-danger'>Cuenta IMAP no encontrada.</div>";
    exit;
  }

  $host = $acc['host'];
  $port = $acc['port'];
  $encryption = $acc['encryption'];
  $username = $acc['username'];
  $password = decrypt_text($acc['password_enc']);

  $mailbox = "{" . $host . ":" . $port . "/" . $encryption . "}INBOX";

  $stream = @imap_open($mailbox, $username, $password);

  if ($stream) {
    imap_close($stream);
    echo "<div class='alert alert-success'>Conexión IMAP exitosa para <strong>" . htmlentities($username) . "</strong>!</div>";
  } else {
    $error = imap_last_error();
    echo "<div class='alert alert-danger'>Error de conexión IMAP: " . htmlentities($error) . "</div>";
  }
}
?>