<?php
// Buffer y configuración
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/crypto.php';
require_role('superadmin');
csrf_check();

// Función para armar mailbox IMAP (sin flags)
function getMailbox($host, $port, $encryption) {
  return sprintf('{%s:%d/imap/%s}INBOX', $host, $port, strtolower($encryption));
}

// Función para probar la conexión IMAP (retorna html para toast)
function probarConexion($id) {
  $st = pdo()->prepare('SELECT * FROM imap_accounts WHERE id=?');
  $st->execute([$id]);
  $account = $st->fetch();

  if (!$account) {
    return '<div class="alert alert-danger">Configuración IMAP no encontrada.</div>';
  }

  $mailbox = getMailbox($account['host'], (int)$account['port'], $account['encryption']);
  $password = decrypt_text($account['password_enc']);

  $imap_stream = @imap_open($mailbox, $account['username'], $password, 0, 1);

  if ($imap_stream === false) {
    $error = imap_last_error() ?: 'Error desconocido al conectar IMAP.';
    return '<div class="alert alert-danger">Error al conectar: ' . htmlspecialchars($error) . '</div>';
  } else {
    imap_close($imap_stream);
    return '<div class="alert alert-success">Conexión IMAP exitosa a ' . htmlspecialchars($account['host']) . '.</div>';
  }
}

// Procesamiento de acciones POST y AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (isset($_POST['ajax_action']) && $_POST['ajax_action'] === 'probar_conexion') {
    csrf_check();
    $id = (int)($_POST['id'] ?? 0);
    echo probarConexion($id);
    exit;
  }

  $action = $_POST['action'] ?? '';
  if ($action === 'create') {
    $label = trim($_POST['label'] ?? '');
    $provider = trim($_POST['provider'] ?? 'gmail');
    $host = trim($_POST['host'] ?? '');
    $port = (int)($_POST['port'] ?? 993);
    $enc  = trim($_POST['encryption'] ?? 'ssl');
    $user = trim($_POST['username'] ?? '');
    $pass = (string)($_POST['password'] ?? '');
    $encr = encrypt_text($pass);
    $st = pdo()->prepare('INSERT INTO imap_accounts (label, provider, host, port, encryption, username, password_enc, enabled) VALUES (?,?,?,?,?,?,?,1)');
    $st->execute([$label, $provider, $host, $port, $enc, $user, $encr]);
  } elseif ($action === 'update') {
    $id = (int)($_POST['id'] ?? 0);
    $label = trim($_POST['label'] ?? '');
    $provider = trim($_POST['provider'] ?? 'gmail');
    $host = trim($_POST['host'] ?? '');
    $port = (int)($_POST['port'] ?? 993);
    $enc  = trim($_POST['encryption'] ?? 'ssl');
    $user = trim($_POST['username'] ?? '');
    $pass = (string)($_POST['password'] ?? '');
    if ($pass !== '') {
      $encr = encrypt_text($pass);
      $st = pdo()->prepare('UPDATE imap_accounts SET label=?, provider=?, host=?, port=?, encryption=?, username=?, password_enc=? WHERE id=?');
      $st->execute([$label, $provider, $host, $port, $enc, $user, $encr, $id]);
    } else {
      $st = pdo()->prepare('UPDATE imap_accounts SET label=?, provider=?, host=?, port=?, encryption=?, username=? WHERE id=?');
      $st->execute([$label, $provider, $host, $port, $enc, $user, $id]);
    }
  } elseif ($action === 'toggle') {
    $id = (int)($_POST['id'] ?? 0);
    $enabled = (int)($_POST['enabled'] ?? 0);
    $st = pdo()->prepare('UPDATE imap_accounts SET enabled=? WHERE id=?');
    $st->execute([$enabled, $id]);
  } elseif ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    $st = pdo()->prepare('DELETE FROM imap_accounts WHERE id=?');
    $st->execute([$id]);
  }
  header('Location: imap.php');
  exit;
}

$title = 'IMAP';
require_once __DIR__ . '/../templates/header.php';
$rows = pdo()->query('SELECT * FROM imap_accounts ORDER BY id DESC')->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h3>Configuraciones IMAP</h3>
  <button class="btn btn-success" data-bs-toggle="collapse" data-bs-target="#frmNew">+ Agregar IMAP</button>
</div>

<div class="alert alert-secondary small">
  Ejemplo Gmail: host <code>imap.gmail.com</code>, puerto <code>993</code>, cifrado <code>SSL</code>. Usa contraseña de aplicación (16 dígitos).<br>
</div>

<div id="frmNew" class="collapse">
  <div class="card card-body mb-3">
    <form method="post" class="row g-2">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">
      <div class="col-md-3">
        <label class="form-label">Etiqueta</label>
        <input class="form-control" name="label" placeholder="streaming" required>
      </div>
      <div class="col-md-2">
        <label class="form-label">Proveedor</label>
        <select class="form-select" name="provider">
          <option value="gmail">Gmail</option>
          <option value="namecheap">Namecheap</option>
          <option value="otro">Otro</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Host</label>
        <input class="form-control" name="host" value="imap.gmail.com" required>
      </div>
      <div class="col-md-1">
        <label class="form-label">Puerto</label>
        <input class="form-control" name="port" type="number" value="993">
      </div>
      <div class="col-md-1">
        <label class="form-label">Cifrado</label>
        <select class="form-select" name="encryption">
          <option value="ssl">ssl</option>
          <option value="tls">tls</option>
          <option value="none">none</option>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Usuario</label>
        <input class="form-control" name="username" required placeholder="ejemplo@gmail.com">
      </div>
      <div class="col-md-4">
        <label class="form-label">Contraseña</label>
        <input class="form-control" name="password" required placeholder="clave 16 dígitos">
      </div>
      <div class="col-12">
        <button class="btn btn-primary">Guardar</button>
      </div>
    </form>
  </div>
</div>

<div class="table-responsive">
  <table class="table table-striped align-middle">
    <thead>
      <tr>
        <th>ID</th>
        <th>Etiqueta</th>
        <th>Proveedor</th>
        <th>Host</th>
        <th>Usuario</th>
        <th>Habilitado</th>
        <th>Cadena IMAP</th>
        <th>Acciones</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($rows as $r): ?>
        <?php
          $mailbox = getMailbox($r['host'], (int)$r['port'], $r['encryption']);
        ?>
        <tr>
          <td><?= e($r['id']) ?></td>
          <td><?= e($r['label']) ?></td>
          <td><?= e($r['provider']) ?></td>
          <td><?= e($r['host']) ?>:<?= e($r['port']) ?>/<?= e($r['encryption']) ?></td>
          <td><?= e($r['username']) ?></td>
          <td><?= $r['enabled'] ? 'Sí' : 'No' ?></td>
          <td><code><?= htmlentities($mailbox) ?></code></td>
          <td>
            <button class="btn btn-sm btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#edit<?= e($r['id']) ?>">Editar</button>
            <form method="post" class="d-inline">
              <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
              <input type="hidden" name="action" value="toggle">
              <input type="hidden" name="id" value="<?= e($r['id']) ?>">
              <input type="hidden" name="enabled" value="<?= $r['enabled'] ? 0 : 1 ?>">
              <button class="btn btn-sm btn-outline-warning"><?= $r['enabled'] ? 'Deshabilitar' : 'Habilitar' ?></button>
            </form>
            <form method="post" class="d-inline" onsubmit="return confirm('¿Eliminar configuración IMAP?');">
              <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= e($r['id']) ?>">
              <button class="btn btn-sm btn-outline-danger">Eliminar</button>
            </form>
            <button type="button" class="btn btn-sm btn-info" onclick="probarConexionIMAP(<?= e($r['id']) ?>, this)">Probar conexión</button>
          </td>
        </tr>
        <tr class="collapse" id="edit<?= e($r['id']) ?>">
          <td colspan="8">
            <div class="card card-body">
              <form method="post" class="row g-2">
                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?= e($r['id']) ?>">
                <div class="col-md-3">
                  <label class="form-label">Etiqueta</label>
                  <input class="form-control" name="label" value="<?= e($r['label']) ?>">
                </div>
                <div class="col-md-2">
                  <label class="form-label">Proveedor</label>
                  <select class="form-select" name="provider">
                    <option value="gmail" <?= $r['provider'] == 'gmail' ? 'selected' : '' ?>>Gmail</option>
                    <option value="namecheap" <?= $r['provider'] == 'namecheap' ? 'selected' : '' ?>>Namecheap</option>
                    <option value="otro" <?= $r['provider'] == 'otro' ? 'selected' : '' ?>>Otro</option>
                  </select>
                </div>
                <div class="col-md-3">
                  <label class="form-label">Host</label>
                  <input class="form-control" name="host" value="<?= e($r['host']) ?>">
                </div>
                <div class="col-md-1">
                  <label class="form-label">Puerto</label>
                  <input class="form-control" name="port" type="number" value="<?= e($r['port']) ?>">
                </div>
                <div class="col-md-1">
                  <label class="form-label">Cifrado</label>
                  <select class="form-select" name="encryption">
                    <option value="ssl" <?= $r['encryption'] == 'ssl' ? 'selected' : '' ?>>ssl</option>
                    <option value="tls" <?= $r['encryption'] == 'tls' ? 'selected' : '' ?>>tls</option>
                    <option value="none" <?= $r['encryption'] == 'none' ? 'selected' : '' ?>>none</option>
                  </select>
                </div>
                <div class="col-md-4">
                  <label class="form-label">Usuario</label>
                  <input class="form-control" name="username" value="<?= e($r['username']) ?>">
                </div>
                <div class="col-md-4">
                  <label class="form-label">Contraseña (dejar vacío para mantener)</label>
                  <input class="form-control" name="password" placeholder="***********">
                </div>
                <div class="col-12">
                  <button class="btn btn-primary">Guardar</button>
                </div>
              </form>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 1100">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <strong class="me-auto" id="toastTitle">Notificación</strong>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Cerrar"></button>
    </div>
    <div class="toast-body" id="toastBody"></div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function probarConexionIMAP(id, btn) {
  btn.disabled = true;
  const originalText = btn.textContent;
  btn.textContent = 'Probando...';
  const csrfToken = '<?= e(csrf_token()) ?>';
  fetch('<?= $_SERVER['PHP_SELF'] ?>', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: 'ajax_action=probar_conexion&id=' + encodeURIComponent(id) + '&csrf=' + encodeURIComponent(csrfToken)
  })
  .then(res => res.text())
  .then(html => {
    const div = document.createElement('div');
    div.innerHTML = html;
    const isSuccess = div.querySelector('.alert-success') !== null;
    const isError = div.querySelector('.alert-danger') !== null;
    const toastTitle = document.getElementById('toastTitle');
    const toastBody = document.getElementById('toastBody');
    if (isSuccess) {
      toastTitle.textContent = 'Conexión Exitosa';
      toastBody.innerHTML = div.innerHTML;
      toastBody.style.color = 'green';
    } else if (isError) {
      toastTitle.textContent = 'Error de Conexión';
      toastBody.innerHTML = div.innerHTML;
      toastBody.style.color = 'red';
    } else {
      toastTitle.textContent = 'Resultado';
      toastBody.textContent = 'Respuesta desconocida';
      toastBody.style.color = 'black';
    }
    const toastEl = document.getElementById('liveToast');
    const toast = bootstrap.Toast.getOrCreateInstance(toastEl);
    toast.show();
  })
  .catch(() => {
    alert('Error en la comunicación con el servidor.');
  })
  .finally(() => {
    btn.disabled = false;
    btn.textContent = originalText;
  });
}
</script>

<?php
require_once __DIR__ . '/../templates/footer.php';
ob_end_flush();
?>
